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
57 # define CLEAR_RANDOM_T(rnd) ((void)0)
60 #if defined SINGLE_APPLET_MAIN
61 /* STANDALONE does not make sense, and won't compile */
62 # undef CONFIG_FEATURE_SH_STANDALONE
63 # undef ENABLE_FEATURE_SH_STANDALONE
64 # undef IF_FEATURE_SH_STANDALONE
65 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
66 # define ENABLE_FEATURE_SH_STANDALONE 0
67 # define IF_FEATURE_SH_STANDALONE(...)
68 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
72 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
75 #if defined(__uClinux__)
76 # error "Do not even bother, ash will not run on NOMMU machine"
80 /* ============ Hash table sizes. Configurable. */
84 #define CMDTABLESIZE 31 /* should be prime */
87 /* ============ Shell options */
89 static const char *const optletters_optnames[] = {
110 #define optletters(n) optletters_optnames[(n)][0]
111 #define optnames(n) (&optletters_optnames[(n)][1])
113 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
116 /* ============ Misc data */
118 static const char homestr[] ALIGN1 = "HOME";
119 static const char snlfmt[] ALIGN1 = "%s\n";
120 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
123 * We enclose jmp_buf in a structure so that we can declare pointers to
124 * jump locations. The global variable handler contains the location to
125 * jump to when an exception occurs, and the global variable exception_type
126 * contains a code identifying the exception. To implement nested
127 * exception handlers, the user should save the value of handler on entry
128 * to an inner scope, set handler to point to a jmploc structure for the
129 * inner scope, and restore handler on exit from the scope.
135 struct globals_misc {
136 /* pid of main shell */
138 /* shell level: 0 for the main shell, 1 for its children, and so on */
140 #define rootshell (!shlvl)
141 char *minusc; /* argument to -c option */
143 char *curdir; // = nullstr; /* current working directory */
144 char *physdir; // = nullstr; /* physical working directory */
146 char *arg0; /* value of $0 */
148 struct jmploc *exception_handler;
150 volatile int suppress_int; /* counter */
151 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
152 /* last pending signal */
153 volatile /*sig_atomic_t*/ smallint pending_sig;
154 smallint exception_type; /* kind of exception (0..5) */
156 #define EXINT 0 /* SIGINT received */
157 #define EXERROR 1 /* a generic error */
158 #define EXSHELLPROC 2 /* execute a shell procedure */
159 #define EXEXEC 3 /* command execution failed */
160 #define EXEXIT 4 /* exit the shell */
161 #define EXSIG 5 /* trapped signal in wait(1) */
164 char nullstr[1]; /* zero length string */
167 #define eflag optlist[0]
168 #define fflag optlist[1]
169 #define Iflag optlist[2]
170 #define iflag optlist[3]
171 #define mflag optlist[4]
172 #define nflag optlist[5]
173 #define sflag optlist[6]
174 #define xflag optlist[7]
175 #define vflag optlist[8]
176 #define Cflag optlist[9]
177 #define aflag optlist[10]
178 #define bflag optlist[11]
179 #define uflag optlist[12]
180 #define viflag optlist[13]
182 #define nolog optlist[14]
183 #define debug optlist[15]
186 /* trap handler commands */
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
192 char sigmode[NSIG - 1];
193 #define S_DFL 1 /* default signal handling (SIG_DFL) */
194 #define S_CATCH 2 /* signal is caught */
195 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
196 #define S_HARD_IGN 4 /* signal is ignored permenantly */
198 /* indicates specified signal received */
199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
201 char **trap_ptr; /* used only by "trap hack" */
203 /* Rarely referenced stuff */
204 #if ENABLE_ASH_RANDOM_SUPPORT
207 pid_t backgndpid; /* pid of last background process */
208 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
210 extern struct globals_misc *const ash_ptr_to_globals_misc;
211 #define G_misc (*ash_ptr_to_globals_misc)
212 #define rootpid (G_misc.rootpid )
213 #define shlvl (G_misc.shlvl )
214 #define minusc (G_misc.minusc )
215 #define curdir (G_misc.curdir )
216 #define physdir (G_misc.physdir )
217 #define arg0 (G_misc.arg0 )
218 #define exception_handler (G_misc.exception_handler)
219 #define exception_type (G_misc.exception_type )
220 #define suppress_int (G_misc.suppress_int )
221 #define pending_int (G_misc.pending_int )
222 #define pending_sig (G_misc.pending_sig )
223 #define isloginsh (G_misc.isloginsh )
224 #define nullstr (G_misc.nullstr )
225 #define optlist (G_misc.optlist )
226 #define sigmode (G_misc.sigmode )
227 #define gotsig (G_misc.gotsig )
228 #define trap (G_misc.trap )
229 #define trap_ptr (G_misc.trap_ptr )
230 #define random_gen (G_misc.random_gen )
231 #define backgndpid (G_misc.backgndpid )
232 #define job_warning (G_misc.job_warning)
233 #define INIT_G_misc() do { \
234 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
242 /* ============ DEBUG */
244 static void trace_printf(const char *fmt, ...);
245 static void trace_vprintf(const char *fmt, va_list va);
246 # define TRACE(param) trace_printf param
247 # define TRACEV(param) trace_vprintf param
248 # define close(fd) do { \
250 if (close(dfd) < 0) \
251 bb_error_msg("bug on %d: closing %d(0x%x)", \
252 __LINE__, dfd, dfd); \
255 # define TRACE(param)
256 # define TRACEV(param)
260 /* ============ Utility functions */
261 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
263 /* C99 says: "char" declaration may be signed or unsigned by default */
264 #define signed_char2int(sc) ((int)(signed char)(sc))
266 static int isdigit_str9(const char *str)
268 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
269 while (--maxlen && isdigit(*str))
271 return (*str == '\0');
275 /* ============ Interrupts / exceptions */
277 * These macros allow the user to suspend the handling of interrupt signals
278 * over a period of time. This is similar to SIGHOLD or to sigblock, but
279 * much more efficient and portable. (But hacking the kernel is so much
280 * more fun than worrying about efficiency and portability. :-))
282 #define INT_OFF do { \
288 * Called to raise an exception. Since C doesn't include exceptions, we
289 * just do a longjmp to the exception handler. The type of exception is
290 * stored in the global variable "exception_type".
292 static void raise_exception(int) NORETURN;
294 raise_exception(int e)
297 if (exception_handler == NULL)
302 longjmp(exception_handler->loc, 1);
305 #define raise_exception(e) do { \
306 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
307 raise_exception(e); \
312 * Called from trap.c when a SIGINT is received. (If the user specifies
313 * that SIGINT is to be trapped or ignored using the trap builtin, then
314 * this routine is not called.) Suppressint is nonzero when interrupts
315 * are held using the INT_OFF macro. (The test for iflag is just
316 * defensive programming.)
318 static void raise_interrupt(void) NORETURN;
320 raise_interrupt(void)
325 /* Signal is not automatically unmasked after it is raised,
326 * do it ourself - unmask all signals */
327 sigprocmask_allsigs(SIG_UNBLOCK);
328 /* pending_sig = 0; - now done in onsig() */
331 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
332 if (!(rootshell && iflag)) {
333 /* Kill ourself with SIGINT */
334 signal(SIGINT, SIG_DFL);
339 raise_exception(ex_type);
343 #define raise_interrupt() do { \
344 TRACE(("raising interrupt on line %d\n", __LINE__)); \
349 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
353 if (--suppress_int == 0 && pending_int) {
357 #define INT_ON int_on()
358 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
366 #define FORCE_INT_ON force_int_on()
368 #define SAVE_INT(v) ((v) = suppress_int)
370 #define RESTORE_INT(v) do { \
372 suppress_int = (v); \
373 if (suppress_int == 0 && pending_int) \
378 /* ============ Stdout/stderr output */
381 outstr(const char *p, FILE *file)
389 flush_stdout_stderr(void)
397 outcslow(int c, FILE *dest)
405 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
407 out1fmt(const char *fmt, ...)
414 r = vprintf(fmt, ap);
420 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
422 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
429 ret = vsnprintf(outbuf, length, fmt, ap);
436 out1str(const char *p)
442 out2str(const char *p)
445 flush_stdout_stderr();
449 /* ============ Parser structures */
451 /* control characters in argument strings */
452 #define CTLESC ((unsigned char)'\201') /* escape next character */
453 #define CTLVAR ((unsigned char)'\202') /* variable defn */
454 #define CTLENDVAR ((unsigned char)'\203')
455 #define CTLBACKQ ((unsigned char)'\204')
456 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
457 /* CTLBACKQ | CTLQUOTE == '\205' */
458 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
459 #define CTLENDARI ((unsigned char)'\207')
460 #define CTLQUOTEMARK ((unsigned char)'\210')
462 /* variable substitution byte (follows CTLVAR) */
463 #define VSTYPE 0x0f /* type of variable substitution */
464 #define VSNUL 0x10 /* colon--treat the empty string as unset */
465 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
467 /* values of VSTYPE field */
468 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
469 #define VSMINUS 0x2 /* ${var-text} */
470 #define VSPLUS 0x3 /* ${var+text} */
471 #define VSQUESTION 0x4 /* ${var?message} */
472 #define VSASSIGN 0x5 /* ${var=text} */
473 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
474 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
475 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
476 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
477 #define VSLENGTH 0xa /* ${#var} */
478 #if ENABLE_ASH_BASH_COMPAT
479 #define VSSUBSTR 0xc /* ${var:position:length} */
480 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
481 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
484 static const char dolatstr[] ALIGN1 = {
485 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
505 #if ENABLE_ASH_BASH_COMPAT
522 smallint type; /* Nxxxx */
525 union node *redirect;
530 smallint pipe_backgnd;
531 struct nodelist *cmdlist;
537 union node *redirect;
550 union node *elsepart;
577 struct nodelist *backquote;
580 /* nfile and ndup layout must match!
581 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
582 * that it is actually NTO2 (>&file), and change its type.
599 char *_unused_expfname;
618 struct nredir nredir;
619 struct nbinary nbinary;
623 struct nclist nclist;
632 * NODE_EOF is returned by parsecmd when it encounters an end of file.
633 * It must be distinct from NULL.
635 #define NODE_EOF ((union node *) -1L)
638 struct nodelist *next;
651 freefunc(struct funcnode *f)
653 if (f && --f->count < 0)
658 /* ============ Debugging output */
662 static FILE *tracefile;
665 trace_printf(const char *fmt, ...)
672 fprintf(tracefile, "%u ", (int) time(NULL));
674 fprintf(tracefile, "[%u] ", (int) getpid());
676 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
678 vfprintf(tracefile, fmt, va);
683 trace_vprintf(const char *fmt, va_list va)
688 fprintf(tracefile, "%u ", (int) time(NULL));
690 fprintf(tracefile, "[%u] ", (int) getpid());
692 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
693 vfprintf(tracefile, fmt, va);
697 trace_puts(const char *s)
705 trace_puts_quoted(char *s)
712 putc('"', tracefile);
713 for (p = s; *p; p++) {
715 case '\n': c = 'n'; goto backslash;
716 case '\t': c = 't'; goto backslash;
717 case '\r': c = 'r'; goto backslash;
718 case '"': c = '"'; goto backslash;
719 case '\\': c = '\\'; goto backslash;
720 case CTLESC: c = 'e'; goto backslash;
721 case CTLVAR: c = 'v'; goto backslash;
722 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
723 case CTLBACKQ: c = 'q'; goto backslash;
724 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
726 putc('\\', tracefile);
730 if (*p >= ' ' && *p <= '~')
733 putc('\\', tracefile);
734 putc(*p >> 6 & 03, tracefile);
735 putc(*p >> 3 & 07, tracefile);
736 putc(*p & 07, tracefile);
741 putc('"', tracefile);
745 trace_puts_args(char **ap)
752 trace_puts_quoted(*ap);
754 putc('\n', tracefile);
757 putc(' ', tracefile);
772 /* leave open because libedit might be using it */
775 strcpy(s, "./trace");
777 if (!freopen(s, "a", tracefile)) {
778 fprintf(stderr, "Can't re-open %s\n", s);
783 tracefile = fopen(s, "a");
784 if (tracefile == NULL) {
785 fprintf(stderr, "Can't open %s\n", s);
791 flags = fcntl(fileno(tracefile), F_GETFL);
793 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
795 setlinebuf(tracefile);
796 fputs("\nTracing started.\n", tracefile);
800 indent(int amount, char *pfx, FILE *fp)
804 for (i = 0; i < amount; i++) {
805 if (pfx && i == amount - 1)
811 /* little circular references here... */
812 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
815 sharg(union node *arg, FILE *fp)
818 struct nodelist *bqlist;
821 if (arg->type != NARG) {
822 out1fmt("<node type %d>\n", arg->type);
825 bqlist = arg->narg.backquote;
826 for (p = arg->narg.text; *p; p++) {
835 if (subtype == VSLENGTH)
844 switch (subtype & VSTYPE) {
877 out1fmt("<subtype %d>", subtype);
884 case CTLBACKQ|CTLQUOTE:
887 shtree(bqlist->n, -1, NULL, fp);
898 shcmd(union node *cmd, FILE *fp)
906 for (np = cmd->ncmd.args; np; np = np->narg.next) {
912 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
916 switch (np->nfile.type) {
917 case NTO: s = ">>"+1; dftfd = 1; break;
918 case NCLOBBER: s = ">|"; dftfd = 1; break;
919 case NAPPEND: s = ">>"; dftfd = 1; break;
920 #if ENABLE_ASH_BASH_COMPAT
923 case NTOFD: s = ">&"; dftfd = 1; break;
924 case NFROM: s = "<"; break;
925 case NFROMFD: s = "<&"; break;
926 case NFROMTO: s = "<>"; break;
927 default: s = "*error*"; break;
929 if (np->nfile.fd != dftfd)
930 fprintf(fp, "%d", np->nfile.fd);
932 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
933 fprintf(fp, "%d", np->ndup.dupfd);
935 sharg(np->nfile.fname, fp);
942 shtree(union node *n, int ind, char *pfx, FILE *fp)
950 indent(ind, pfx, fp);
967 shtree(n->nbinary.ch1, ind, NULL, fp);
970 shtree(n->nbinary.ch2, ind, NULL, fp);
978 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
979 shtree(lp->n, 0, NULL, fp);
983 if (n->npipe.pipe_backgnd)
989 fprintf(fp, "<node type %d>", n->type);
997 showtree(union node *n)
999 trace_puts("showtree called\n");
1000 shtree(n, 1, NULL, stderr);
1006 /* ============ Parser data */
1009 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1012 struct strlist *next;
1019 struct strpush *prev; /* preceding string on stack */
1021 int prev_left_in_line;
1022 #if ENABLE_ASH_ALIAS
1023 struct alias *ap; /* if push was associated with an alias */
1025 char *string; /* remember the string since it may change */
1029 struct parsefile *prev; /* preceding file on stack */
1030 int linno; /* current line */
1031 int fd; /* file descriptor (or -1 if string) */
1032 int left_in_line; /* number of chars left in this line */
1033 int left_in_buffer; /* number of chars left in this buffer past the line */
1034 char *next_to_pgetc; /* next char in buffer */
1035 char *buf; /* input buffer */
1036 struct strpush *strpush; /* for pushing strings at this level */
1037 struct strpush basestrpush; /* so pushing one is fast */
1040 static struct parsefile basepf; /* top level input file */
1041 static struct parsefile *g_parsefile = &basepf; /* current input file */
1042 static int startlinno; /* line # where last token started */
1043 static char *commandname; /* currently executing command */
1044 static struct strlist *cmdenviron; /* environment for builtin command */
1045 static uint8_t exitstatus; /* exit status of last command */
1048 /* ============ Message printing */
1051 ash_vmsg(const char *msg, va_list ap)
1053 fprintf(stderr, "%s: ", arg0);
1055 if (strcmp(arg0, commandname))
1056 fprintf(stderr, "%s: ", commandname);
1057 if (!iflag || g_parsefile->fd)
1058 fprintf(stderr, "line %d: ", startlinno);
1060 vfprintf(stderr, msg, ap);
1061 outcslow('\n', stderr);
1065 * Exverror is called to raise the error exception. If the second argument
1066 * is not NULL then error prints an error message using printf style
1067 * formatting. It then raises the error exception.
1069 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1071 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1075 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1077 TRACE(("\") pid=%d\n", getpid()));
1079 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1084 flush_stdout_stderr();
1085 raise_exception(cond);
1089 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1091 ash_msg_and_raise_error(const char *msg, ...)
1096 ash_vmsg_and_raise(EXERROR, msg, ap);
1101 static void raise_error_syntax(const char *) NORETURN;
1103 raise_error_syntax(const char *msg)
1105 ash_msg_and_raise_error("syntax error: %s", msg);
1109 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1111 ash_msg_and_raise(int cond, const char *msg, ...)
1116 ash_vmsg_and_raise(cond, msg, ap);
1122 * error/warning routines for external builtins
1125 ash_msg(const char *fmt, ...)
1135 * Return a string describing an error. The returned string may be a
1136 * pointer to a static buffer that will be overwritten on the next call.
1137 * Action describes the operation that got the error.
1140 errmsg(int e, const char *em)
1142 if (e == ENOENT || e == ENOTDIR) {
1149 /* ============ Memory allocation */
1152 /* I consider these wrappers nearly useless:
1153 * ok, they return you to nearest exception handler, but
1154 * how much memory do you leak in the process, making
1155 * memory starvation worse?
1158 ckrealloc(void * p, size_t nbytes)
1160 p = realloc(p, nbytes);
1162 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1167 ckmalloc(size_t nbytes)
1169 return ckrealloc(NULL, nbytes);
1173 ckzalloc(size_t nbytes)
1175 return memset(ckmalloc(nbytes), 0, nbytes);
1179 ckstrdup(const char *s)
1181 char *p = strdup(s);
1183 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1187 /* Using bbox equivalents. They exit if out of memory */
1188 # define ckrealloc xrealloc
1189 # define ckmalloc xmalloc
1190 # define ckzalloc xzalloc
1191 # define ckstrdup xstrdup
1195 * It appears that grabstackstr() will barf with such alignments
1196 * because stalloc() will return a string allocated in a new stackblock.
1198 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1200 /* Most machines require the value returned from malloc to be aligned
1201 * in some way. The following macro will get this right
1202 * on many machines. */
1203 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1204 /* Minimum size of a block */
1205 MINSIZE = SHELL_ALIGN(504),
1208 struct stack_block {
1209 struct stack_block *prev;
1210 char space[MINSIZE];
1214 struct stack_block *stackp;
1217 struct stackmark *marknext;
1221 struct globals_memstack {
1222 struct stack_block *g_stackp; // = &stackbase;
1223 struct stackmark *markp;
1224 char *g_stacknxt; // = stackbase.space;
1225 char *sstrend; // = stackbase.space + MINSIZE;
1226 size_t g_stacknleft; // = MINSIZE;
1227 int herefd; // = -1;
1228 struct stack_block stackbase;
1230 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1231 #define G_memstack (*ash_ptr_to_globals_memstack)
1232 #define g_stackp (G_memstack.g_stackp )
1233 #define markp (G_memstack.markp )
1234 #define g_stacknxt (G_memstack.g_stacknxt )
1235 #define sstrend (G_memstack.sstrend )
1236 #define g_stacknleft (G_memstack.g_stacknleft)
1237 #define herefd (G_memstack.herefd )
1238 #define stackbase (G_memstack.stackbase )
1239 #define INIT_G_memstack() do { \
1240 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1242 g_stackp = &stackbase; \
1243 g_stacknxt = stackbase.space; \
1244 g_stacknleft = MINSIZE; \
1245 sstrend = stackbase.space + MINSIZE; \
1250 #define stackblock() ((void *)g_stacknxt)
1251 #define stackblocksize() g_stacknleft
1254 * Parse trees for commands are allocated in lifo order, so we use a stack
1255 * to make this more efficient, and also to avoid all sorts of exception
1256 * handling code to handle interrupts in the middle of a parse.
1258 * The size 504 was chosen because the Ultrix malloc handles that size
1262 stalloc(size_t nbytes)
1267 aligned = SHELL_ALIGN(nbytes);
1268 if (aligned > g_stacknleft) {
1271 struct stack_block *sp;
1273 blocksize = aligned;
1274 if (blocksize < MINSIZE)
1275 blocksize = MINSIZE;
1276 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1277 if (len < blocksize)
1278 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1281 sp->prev = g_stackp;
1282 g_stacknxt = sp->space;
1283 g_stacknleft = blocksize;
1284 sstrend = g_stacknxt + blocksize;
1289 g_stacknxt += aligned;
1290 g_stacknleft -= aligned;
1295 stzalloc(size_t nbytes)
1297 return memset(stalloc(nbytes), 0, nbytes);
1304 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1305 write(STDERR_FILENO, "stunalloc\n", 10);
1309 g_stacknleft += g_stacknxt - (char *)p;
1314 * Like strdup but works with the ash stack.
1317 ststrdup(const char *p)
1319 size_t len = strlen(p) + 1;
1320 return memcpy(stalloc(len), p, len);
1324 setstackmark(struct stackmark *mark)
1326 mark->stackp = g_stackp;
1327 mark->stacknxt = g_stacknxt;
1328 mark->stacknleft = g_stacknleft;
1329 mark->marknext = markp;
1334 popstackmark(struct stackmark *mark)
1336 struct stack_block *sp;
1342 markp = mark->marknext;
1343 while (g_stackp != mark->stackp) {
1345 g_stackp = sp->prev;
1348 g_stacknxt = mark->stacknxt;
1349 g_stacknleft = mark->stacknleft;
1350 sstrend = mark->stacknxt + mark->stacknleft;
1355 * When the parser reads in a string, it wants to stick the string on the
1356 * stack and only adjust the stack pointer when it knows how big the
1357 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1358 * of space on top of the stack and stackblocklen returns the length of
1359 * this block. Growstackblock will grow this space by at least one byte,
1360 * possibly moving it (like realloc). Grabstackblock actually allocates the
1361 * part of the block that has been used.
1364 growstackblock(void)
1368 newlen = g_stacknleft * 2;
1369 if (newlen < g_stacknleft)
1370 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1374 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1375 struct stack_block *oldstackp;
1376 struct stackmark *xmark;
1377 struct stack_block *sp;
1378 struct stack_block *prevstackp;
1382 oldstackp = g_stackp;
1384 prevstackp = sp->prev;
1385 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1386 sp = ckrealloc(sp, grosslen);
1387 sp->prev = prevstackp;
1389 g_stacknxt = sp->space;
1390 g_stacknleft = newlen;
1391 sstrend = sp->space + newlen;
1394 * Stack marks pointing to the start of the old block
1395 * must be relocated to point to the new block
1398 while (xmark != NULL && xmark->stackp == oldstackp) {
1399 xmark->stackp = g_stackp;
1400 xmark->stacknxt = g_stacknxt;
1401 xmark->stacknleft = g_stacknleft;
1402 xmark = xmark->marknext;
1406 char *oldspace = g_stacknxt;
1407 size_t oldlen = g_stacknleft;
1408 char *p = stalloc(newlen);
1410 /* free the space we just allocated */
1411 g_stacknxt = memcpy(p, oldspace, oldlen);
1412 g_stacknleft += newlen;
1417 grabstackblock(size_t len)
1419 len = SHELL_ALIGN(len);
1421 g_stacknleft -= len;
1425 * The following routines are somewhat easier to use than the above.
1426 * The user declares a variable of type STACKSTR, which may be declared
1427 * to be a register. The macro STARTSTACKSTR initializes things. Then
1428 * the user uses the macro STPUTC to add characters to the string. In
1429 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1430 * grown as necessary. When the user is done, she can just leave the
1431 * string there and refer to it using stackblock(). Or she can allocate
1432 * the space for it using grabstackstr(). If it is necessary to allow
1433 * someone else to use the stack temporarily and then continue to grow
1434 * the string, the user should use grabstack to allocate the space, and
1435 * then call ungrabstr(p) to return to the previous mode of operation.
1437 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1438 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1439 * is space for at least one character.
1444 size_t len = stackblocksize();
1445 if (herefd >= 0 && len >= 1024) {
1446 full_write(herefd, stackblock(), len);
1447 return stackblock();
1450 return (char *)stackblock() + len;
1454 * Called from CHECKSTRSPACE.
1457 makestrspace(size_t newlen, char *p)
1459 size_t len = p - g_stacknxt;
1460 size_t size = stackblocksize();
1465 size = stackblocksize();
1467 if (nleft >= newlen)
1471 return (char *)stackblock() + len;
1475 stack_nputstr(const char *s, size_t n, char *p)
1477 p = makestrspace(n, p);
1478 p = (char *)memcpy(p, s, n) + n;
1483 stack_putstr(const char *s, char *p)
1485 return stack_nputstr(s, strlen(s), p);
1489 _STPUTC(int c, char *p)
1497 #define STARTSTACKSTR(p) ((p) = stackblock())
1498 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1499 #define CHECKSTRSPACE(n, p) do { \
1502 size_t m = sstrend - q; \
1504 (p) = makestrspace(l, q); \
1506 #define USTPUTC(c, p) (*(p)++ = (c))
1507 #define STACKSTRNUL(p) do { \
1508 if ((p) == sstrend) \
1509 (p) = growstackstr(); \
1512 #define STUNPUTC(p) (--(p))
1513 #define STTOPC(p) ((p)[-1])
1514 #define STADJUST(amount, p) ((p) += (amount))
1516 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1517 #define ungrabstackstr(s, p) stunalloc(s)
1518 #define stackstrend() ((void *)sstrend)
1521 /* ============ String helpers */
1524 * prefix -- see if pfx is a prefix of string.
1527 prefix(const char *string, const char *pfx)
1530 if (*pfx++ != *string++)
1533 return (char *) string;
1537 * Check for a valid number. This should be elsewhere.
1540 is_number(const char *p)
1545 } while (*++p != '\0');
1550 * Convert a string of digits to an integer, printing an error message on
1554 number(const char *s)
1557 ash_msg_and_raise_error(msg_illnum, s);
1562 * Produce a possibly single quoted string suitable as input to the shell.
1563 * The return string is allocated on the stack.
1566 single_quote(const char *s)
1576 len = strchrnul(s, '\'') - s;
1578 q = p = makestrspace(len + 3, p);
1581 q = (char *)memcpy(q, s, len) + len;
1587 len = strspn(s, "'");
1591 q = p = makestrspace(len + 3, p);
1594 q = (char *)memcpy(q, s, len) + len;
1603 return stackblock();
1607 /* ============ nextopt */
1609 static char **argptr; /* argument list for builtin commands */
1610 static char *optionarg; /* set by nextopt (like getopt) */
1611 static char *optptr; /* used by nextopt */
1614 * XXX - should get rid of. Have all builtins use getopt(3).
1615 * The library getopt must have the BSD extension static variable
1616 * "optreset", otherwise it can't be used within the shell safely.
1618 * Standard option processing (a la getopt) for builtin routines.
1619 * The only argument that is passed to nextopt is the option string;
1620 * the other arguments are unnecessary. It returns the character,
1621 * or '\0' on end of input.
1624 nextopt(const char *optstring)
1631 if (p == NULL || *p == '\0') {
1632 /* We ate entire "-param", take next one */
1638 if (*++p == '\0') /* just "-" ? */
1641 if (LONE_DASH(p)) /* "--" ? */
1643 /* p => next "-param" */
1645 /* p => some option char in the middle of a "-param" */
1647 for (q = optstring; *q != c;) {
1649 ash_msg_and_raise_error("illegal option -%c", c);
1657 ash_msg_and_raise_error("no arg for -%c option", c);
1667 /* ============ Shell variables */
1670 * The parsefile structure pointed to by the global variable parsefile
1671 * contains information about the current file being read.
1674 int nparam; /* # of positional parameters (without $0) */
1675 #if ENABLE_ASH_GETOPTS
1676 int optind; /* next parameter to be processed by getopts */
1677 int optoff; /* used by getopts */
1679 unsigned char malloced; /* if parameter list dynamically allocated */
1680 char **p; /* parameter list */
1684 * Free the list of positional parameters.
1687 freeparam(volatile struct shparam *param)
1689 if (param->malloced) {
1691 ap = ap1 = param->p;
1698 #if ENABLE_ASH_GETOPTS
1699 static void FAST_FUNC getoptsreset(const char *value);
1703 struct var *next; /* next entry in hash list */
1704 int flags; /* flags are defined above */
1705 const char *text; /* name=value */
1706 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1707 /* the variable gets set/unset */
1711 struct localvar *next; /* next local variable in list */
1712 struct var *vp; /* the variable that was made local */
1713 int flags; /* saved flags */
1714 const char *text; /* saved text */
1718 #define VEXPORT 0x01 /* variable is exported */
1719 #define VREADONLY 0x02 /* variable cannot be modified */
1720 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1721 #define VTEXTFIXED 0x08 /* text is statically allocated */
1722 #define VSTACK 0x10 /* text is allocated on the stack */
1723 #define VUNSET 0x20 /* the variable is not set */
1724 #define VNOFUNC 0x40 /* don't call the callback function */
1725 #define VNOSET 0x80 /* do not set variable - just readonly test */
1726 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1727 #if ENABLE_ASH_RANDOM_SUPPORT
1728 # define VDYNAMIC 0x200 /* dynamic variable */
1734 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1735 #define defifs (defifsvar + 4)
1737 static const char defifs[] ALIGN1 = " \t\n";
1741 /* Need to be before varinit_data[] */
1742 #if ENABLE_LOCALE_SUPPORT
1743 static void FAST_FUNC
1744 change_lc_all(const char *value)
1746 if (value && *value != '\0')
1747 setlocale(LC_ALL, value);
1749 static void FAST_FUNC
1750 change_lc_ctype(const char *value)
1752 if (value && *value != '\0')
1753 setlocale(LC_CTYPE, value);
1757 static void chkmail(void);
1758 static void changemail(const char *) FAST_FUNC;
1760 static void changepath(const char *) FAST_FUNC;
1761 #if ENABLE_ASH_RANDOM_SUPPORT
1762 static void change_random(const char *) FAST_FUNC;
1765 static const struct {
1768 void (*func)(const char *) FAST_FUNC;
1769 } varinit_data[] = {
1771 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1773 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1779 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1780 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1783 #if ENABLE_ASH_GETOPTS
1784 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1786 #if ENABLE_ASH_RANDOM_SUPPORT
1787 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1789 #if ENABLE_LOCALE_SUPPORT
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1793 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1794 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1800 struct globals_var {
1801 struct shparam shellparam; /* $@ current positional parameters */
1802 struct redirtab *redirlist;
1804 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1805 struct var *vartab[VTABSIZE];
1806 struct var varinit[ARRAY_SIZE(varinit_data)];
1808 extern struct globals_var *const ash_ptr_to_globals_var;
1809 #define G_var (*ash_ptr_to_globals_var)
1810 #define shellparam (G_var.shellparam )
1811 //#define redirlist (G_var.redirlist )
1812 #define g_nullredirs (G_var.g_nullredirs )
1813 #define preverrout_fd (G_var.preverrout_fd)
1814 #define vartab (G_var.vartab )
1815 #define varinit (G_var.varinit )
1816 #define INIT_G_var() do { \
1818 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1820 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1821 varinit[i].flags = varinit_data[i].flags; \
1822 varinit[i].text = varinit_data[i].text; \
1823 varinit[i].func = varinit_data[i].func; \
1827 #define vifs varinit[0]
1829 # define vmail (&vifs)[1]
1830 # define vmpath (&vmail)[1]
1831 # define vpath (&vmpath)[1]
1833 # define vpath (&vifs)[1]
1835 #define vps1 (&vpath)[1]
1836 #define vps2 (&vps1)[1]
1837 #define vps4 (&vps2)[1]
1838 #if ENABLE_ASH_GETOPTS
1839 # define voptind (&vps4)[1]
1840 # if ENABLE_ASH_RANDOM_SUPPORT
1841 # define vrandom (&voptind)[1]
1844 # if ENABLE_ASH_RANDOM_SUPPORT
1845 # define vrandom (&vps4)[1]
1850 * The following macros access the values of the above variables.
1851 * They have to skip over the name. They return the null string
1852 * for unset variables.
1854 #define ifsval() (vifs.text + 4)
1855 #define ifsset() ((vifs.flags & VUNSET) == 0)
1857 # define mailval() (vmail.text + 5)
1858 # define mpathval() (vmpath.text + 9)
1859 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1861 #define pathval() (vpath.text + 5)
1862 #define ps1val() (vps1.text + 4)
1863 #define ps2val() (vps2.text + 4)
1864 #define ps4val() (vps4.text + 4)
1865 #if ENABLE_ASH_GETOPTS
1866 # define optindval() (voptind.text + 7)
1870 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1871 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1873 #if ENABLE_ASH_GETOPTS
1874 static void FAST_FUNC
1875 getoptsreset(const char *value)
1877 shellparam.optind = number(value);
1878 shellparam.optoff = -1;
1883 * Return of a legal variable name (a letter or underscore followed by zero or
1884 * more letters, underscores, and digits).
1887 endofname(const char *name)
1895 if (!is_in_name(*p))
1902 * Compares two strings up to the first = or '\0'. The first
1903 * string must be terminated by '='; the second may be terminated by
1904 * either '=' or '\0'.
1907 varcmp(const char *p, const char *q)
1911 while ((c = *p) == (d = *q)) {
1926 varequal(const char *a, const char *b)
1928 return !varcmp(a, b);
1932 * Find the appropriate entry in the hash table from the name.
1934 static struct var **
1935 hashvar(const char *p)
1939 hashval = ((unsigned char) *p) << 4;
1940 while (*p && *p != '=')
1941 hashval += (unsigned char) *p++;
1942 return &vartab[hashval % VTABSIZE];
1946 vpcmp(const void *a, const void *b)
1948 return varcmp(*(const char **)a, *(const char **)b);
1952 * This routine initializes the builtin variables.
1962 * PS1 depends on uid
1964 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1965 vps1.text = "PS1=\\w \\$ ";
1968 vps1.text = "PS1=# ";
1971 end = vp + ARRAY_SIZE(varinit);
1973 vpp = hashvar(vp->text);
1976 } while (++vp < end);
1979 static struct var **
1980 findvar(struct var **vpp, const char *name)
1982 for (; *vpp; vpp = &(*vpp)->next) {
1983 if (varequal((*vpp)->text, name)) {
1991 * Find the value of a variable. Returns NULL if not set.
1994 lookupvar(const char *name)
1998 v = *findvar(hashvar(name), name);
2000 #if ENABLE_ASH_RANDOM_SUPPORT
2002 * Dynamic variables are implemented roughly the same way they are
2003 * in bash. Namely, they're "special" so long as they aren't unset.
2004 * As soon as they're unset, they're no longer dynamic, and dynamic
2005 * lookup will no longer happen at that point. -- PFM.
2007 if ((v->flags & VDYNAMIC))
2010 if (!(v->flags & VUNSET))
2011 return strchrnul(v->text, '=') + 1;
2017 * Search the environment of a builtin command.
2020 bltinlookup(const char *name)
2024 for (sp = cmdenviron; sp; sp = sp->next) {
2025 if (varequal(sp->text, name))
2026 return strchrnul(sp->text, '=') + 1;
2028 return lookupvar(name);
2032 * Same as setvar except that the variable and value are passed in
2033 * the first argument as name=value. Since the first argument will
2034 * be actually stored in the table, it should not be a string that
2036 * Called with interrupts off.
2039 setvareq(char *s, int flags)
2041 struct var *vp, **vpp;
2044 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2045 vp = *findvar(vpp, s);
2047 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2050 if (flags & VNOSAVE)
2053 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2059 if (vp->func && (flags & VNOFUNC) == 0)
2060 (*vp->func)(strchrnul(s, '=') + 1);
2062 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2063 free((char*)vp->text);
2065 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2070 vp = ckzalloc(sizeof(*vp));
2072 /*vp->func = NULL; - ckzalloc did it */
2075 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2082 * Set the value of a variable. The flags argument is ored with the
2083 * flags of the variable. If val is NULL, the variable is unset.
2086 setvar(const char *name, const char *val, int flags)
2093 q = endofname(name);
2094 p = strchrnul(q, '=');
2096 if (!namelen || p != q)
2097 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2102 vallen = strlen(val);
2105 nameeq = ckmalloc(namelen + vallen + 2);
2106 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2109 p = (char *)memcpy(p, val, vallen) + vallen;
2112 setvareq(nameeq, flags | VNOSAVE);
2116 #if ENABLE_ASH_GETOPTS
2118 * Safe version of setvar, returns 1 on success 0 on failure.
2121 setvarsafe(const char *name, const char *val, int flags)
2124 volatile int saveint;
2125 struct jmploc *volatile savehandler = exception_handler;
2126 struct jmploc jmploc;
2129 if (setjmp(jmploc.loc))
2132 exception_handler = &jmploc;
2133 setvar(name, val, flags);
2136 exception_handler = savehandler;
2137 RESTORE_INT(saveint);
2143 * Unset the specified variable.
2146 unsetvar(const char *s)
2152 vpp = findvar(hashvar(s), s);
2156 int flags = vp->flags;
2159 if (flags & VREADONLY)
2161 #if ENABLE_ASH_RANDOM_SUPPORT
2162 vp->flags &= ~VDYNAMIC;
2166 if ((flags & VSTRFIXED) == 0) {
2168 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2169 free((char*)vp->text);
2175 vp->flags &= ~VEXPORT;
2185 * Process a linked list of variable assignments.
2188 listsetvar(struct strlist *list_set_var, int flags)
2190 struct strlist *lp = list_set_var;
2196 setvareq(lp->text, flags);
2203 * Generate a list of variables satisfying the given conditions.
2206 listvars(int on, int off, char ***end)
2217 for (vp = *vpp; vp; vp = vp->next) {
2218 if ((vp->flags & mask) == on) {
2219 if (ep == stackstrend())
2220 ep = growstackstr();
2221 *ep++ = (char *) vp->text;
2224 } while (++vpp < vartab + VTABSIZE);
2225 if (ep == stackstrend())
2226 ep = growstackstr();
2230 return grabstackstr(ep);
2234 /* ============ Path search helper
2236 * The variable path (passed by reference) should be set to the start
2237 * of the path before the first call; path_advance will update
2238 * this value as it proceeds. Successive calls to path_advance will return
2239 * the possible path expansions in sequence. If an option (indicated by
2240 * a percent sign) appears in the path entry then the global variable
2241 * pathopt will be set to point to it; otherwise pathopt will be set to
2244 static const char *pathopt; /* set by path_advance */
2247 path_advance(const char **path, const char *name)
2257 for (p = start; *p && *p != ':' && *p != '%'; p++)
2259 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2260 while (stackblocksize() < len)
2264 memcpy(q, start, p - start);
2272 while (*p && *p != ':')
2279 return stalloc(len);
2283 /* ============ Prompt */
2285 static smallint doprompt; /* if set, prompt the user */
2286 static smallint needprompt; /* true if interactive and at start of line */
2288 #if ENABLE_FEATURE_EDITING
2289 static line_input_t *line_input_state;
2290 static const char *cmdedit_prompt;
2292 putprompt(const char *s)
2294 if (ENABLE_ASH_EXPAND_PRMT) {
2295 free((char*)cmdedit_prompt);
2296 cmdedit_prompt = ckstrdup(s);
2303 putprompt(const char *s)
2309 #if ENABLE_ASH_EXPAND_PRMT
2310 /* expandstr() needs parsing machinery, so it is far away ahead... */
2311 static const char *expandstr(const char *ps);
2313 #define expandstr(s) s
2317 setprompt(int whichprompt)
2320 #if ENABLE_ASH_EXPAND_PRMT
2321 struct stackmark smark;
2326 switch (whichprompt) {
2336 #if ENABLE_ASH_EXPAND_PRMT
2337 setstackmark(&smark);
2338 stalloc(stackblocksize());
2340 putprompt(expandstr(prompt));
2341 #if ENABLE_ASH_EXPAND_PRMT
2342 popstackmark(&smark);
2347 /* ============ The cd and pwd commands */
2349 #define CD_PHYSICAL 1
2359 while ((i = nextopt("LP")) != '\0') {
2361 flags ^= CD_PHYSICAL;
2370 * Update curdir (the name of the current directory) in response to a
2374 updatepwd(const char *dir)
2381 cdcomppath = ststrdup(dir);
2384 if (curdir == nullstr)
2386 new = stack_putstr(curdir, new);
2388 new = makestrspace(strlen(dir) + 2, new);
2389 lim = (char *)stackblock() + 1;
2393 if (new > lim && *lim == '/')
2398 if (dir[1] == '/' && dir[2] != '/') {
2404 p = strtok(cdcomppath, "/");
2408 if (p[1] == '.' && p[2] == '\0') {
2420 new = stack_putstr(p, new);
2428 return stackblock();
2432 * Find out what the current directory is. If we already know the current
2433 * directory, this routine returns immediately.
2438 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2439 return dir ? dir : nullstr;
2443 setpwd(const char *val, int setold)
2447 oldcur = dir = curdir;
2450 setvar("OLDPWD", oldcur, VEXPORT);
2453 if (physdir != nullstr) {
2454 if (physdir != oldcur)
2458 if (oldcur == val || !val) {
2464 dir = ckstrdup(val);
2465 if (oldcur != dir && oldcur != nullstr) {
2470 setvar("PWD", dir, VEXPORT);
2473 static void hashcd(void);
2476 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2477 * know that the current directory has changed.
2480 docd(const char *dest, int flags)
2482 const char *dir = 0;
2485 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2488 if (!(flags & CD_PHYSICAL)) {
2489 dir = updatepwd(dest);
2503 static int FAST_FUNC
2504 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2516 dest = bltinlookup(homestr);
2517 else if (LONE_DASH(dest)) {
2518 dest = bltinlookup("OLDPWD");
2540 path = bltinlookup("CDPATH");
2549 p = path_advance(&path, dest);
2550 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2554 if (!docd(p, flags))
2559 ash_msg_and_raise_error("can't cd to %s", dest);
2562 if (flags & CD_PRINT)
2563 out1fmt(snlfmt, curdir);
2567 static int FAST_FUNC
2568 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2571 const char *dir = curdir;
2575 if (physdir == nullstr)
2579 out1fmt(snlfmt, dir);
2584 /* ============ ... */
2587 #define IBUFSIZ COMMON_BUFSIZE
2588 /* buffer for top level input file */
2589 #define basebuf bb_common_bufsiz1
2591 /* Syntax classes */
2592 #define CWORD 0 /* character is nothing special */
2593 #define CNL 1 /* newline character */
2594 #define CBACK 2 /* a backslash character */
2595 #define CSQUOTE 3 /* single quote */
2596 #define CDQUOTE 4 /* double quote */
2597 #define CENDQUOTE 5 /* a terminating quote */
2598 #define CBQUOTE 6 /* backwards single quote */
2599 #define CVAR 7 /* a dollar sign */
2600 #define CENDVAR 8 /* a '}' character */
2601 #define CLP 9 /* a left paren in arithmetic */
2602 #define CRP 10 /* a right paren in arithmetic */
2603 #define CENDFILE 11 /* end of file */
2604 #define CCTL 12 /* like CWORD, except it must be escaped */
2605 #define CSPCL 13 /* these terminate a word */
2606 #define CIGN 14 /* character should be ignored */
2608 #if ENABLE_ASH_ALIAS
2612 #define PEOA_OR_PEOF PEOA
2616 #define PEOA_OR_PEOF PEOF
2619 /* number syntax index */
2620 #define BASESYNTAX 0 /* not in quotes */
2621 #define DQSYNTAX 1 /* in double quotes */
2622 #define SQSYNTAX 2 /* in single quotes */
2623 #define ARISYNTAX 3 /* in arithmetic */
2624 #define PSSYNTAX 4 /* prompt */
2626 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2627 #define USE_SIT_FUNCTION
2630 #if ENABLE_SH_MATH_SUPPORT
2631 static const char S_I_T[][4] = {
2632 #if ENABLE_ASH_ALIAS
2633 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2635 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2636 { CNL, CNL, CNL, CNL }, /* 2, \n */
2637 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2638 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2639 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2640 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2641 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2642 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2643 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2644 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2645 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2646 #ifndef USE_SIT_FUNCTION
2647 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2648 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2649 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2653 static const char S_I_T[][3] = {
2654 #if ENABLE_ASH_ALIAS
2655 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2657 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2658 { CNL, CNL, CNL }, /* 2, \n */
2659 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2660 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2661 { CVAR, CVAR, CWORD }, /* 5, $ */
2662 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2663 { CSPCL, CWORD, CWORD }, /* 7, ( */
2664 { CSPCL, CWORD, CWORD }, /* 8, ) */
2665 { CBACK, CBACK, CCTL }, /* 9, \ */
2666 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2667 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2668 #ifndef USE_SIT_FUNCTION
2669 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2670 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2671 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2674 #endif /* SH_MATH_SUPPORT */
2676 #ifdef USE_SIT_FUNCTION
2679 SIT(int c, int syntax)
2681 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2682 #if ENABLE_ASH_ALIAS
2683 static const char syntax_index_table[] ALIGN1 = {
2684 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2685 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2686 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2690 static const char syntax_index_table[] ALIGN1 = {
2691 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2692 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2693 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2700 if (c == PEOF) { /* 2^8+2 */
2703 #if ENABLE_ASH_ALIAS
2704 if (c == PEOA) { /* 2^8+1 */
2709 if ((unsigned char)c >= CTLESC
2710 && (unsigned char)c <= CTLQUOTEMARK
2714 s = strchrnul(spec_symbls, c);
2718 indx = syntax_index_table[s - spec_symbls];
2720 return S_I_T[indx][syntax];
2723 #else /* !USE_SIT_FUNCTION */
2725 #if ENABLE_ASH_ALIAS
2726 #define CSPCL_CIGN_CIGN_CIGN 0
2727 #define CSPCL_CWORD_CWORD_CWORD 1
2728 #define CNL_CNL_CNL_CNL 2
2729 #define CWORD_CCTL_CCTL_CWORD 3
2730 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2731 #define CVAR_CVAR_CWORD_CVAR 5
2732 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2733 #define CSPCL_CWORD_CWORD_CLP 7
2734 #define CSPCL_CWORD_CWORD_CRP 8
2735 #define CBACK_CBACK_CCTL_CBACK 9
2736 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2737 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2738 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2739 #define CWORD_CWORD_CWORD_CWORD 13
2740 #define CCTL_CCTL_CCTL_CCTL 14
2742 #define CSPCL_CWORD_CWORD_CWORD 0
2743 #define CNL_CNL_CNL_CNL 1
2744 #define CWORD_CCTL_CCTL_CWORD 2
2745 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2746 #define CVAR_CVAR_CWORD_CVAR 4
2747 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2748 #define CSPCL_CWORD_CWORD_CLP 6
2749 #define CSPCL_CWORD_CWORD_CRP 7
2750 #define CBACK_CBACK_CCTL_CBACK 8
2751 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2752 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2753 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2754 #define CWORD_CWORD_CWORD_CWORD 12
2755 #define CCTL_CCTL_CCTL_CCTL 13
2758 static const char syntax_index_table[258] = {
2759 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2760 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2761 #if ENABLE_ASH_ALIAS
2762 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2764 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2766 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2767 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2768 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2769 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2770 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2771 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2772 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2773 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2903 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2926 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2927 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2929 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2931 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2932 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2933 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2934 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2937 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2939 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2953 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2954 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2955 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2985 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2986 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2989 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3017 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3018 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3019 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3022 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3024 #endif /* USE_SIT_FUNCTION */
3027 /* ============ Alias handling */
3029 #if ENABLE_ASH_ALIAS
3031 #define ALIASINUSE 1
3042 static struct alias **atab; // [ATABSIZE];
3043 #define INIT_G_alias() do { \
3044 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3048 static struct alias **
3049 __lookupalias(const char *name) {
3050 unsigned int hashval;
3057 ch = (unsigned char)*p;
3061 ch = (unsigned char)*++p;
3063 app = &atab[hashval % ATABSIZE];
3065 for (; *app; app = &(*app)->next) {
3066 if (strcmp(name, (*app)->name) == 0) {
3074 static struct alias *
3075 lookupalias(const char *name, int check)
3077 struct alias *ap = *__lookupalias(name);
3079 if (check && ap && (ap->flag & ALIASINUSE))
3084 static struct alias *
3085 freealias(struct alias *ap)
3089 if (ap->flag & ALIASINUSE) {
3090 ap->flag |= ALIASDEAD;
3102 setalias(const char *name, const char *val)
3104 struct alias *ap, **app;
3106 app = __lookupalias(name);
3110 if (!(ap->flag & ALIASINUSE)) {
3113 ap->val = ckstrdup(val);
3114 ap->flag &= ~ALIASDEAD;
3117 ap = ckzalloc(sizeof(struct alias));
3118 ap->name = ckstrdup(name);
3119 ap->val = ckstrdup(val);
3120 /*ap->flag = 0; - ckzalloc did it */
3121 /*ap->next = NULL;*/
3128 unalias(const char *name)
3132 app = __lookupalias(name);
3136 *app = freealias(*app);
3147 struct alias *ap, **app;
3151 for (i = 0; i < ATABSIZE; i++) {
3153 for (ap = *app; ap; ap = *app) {
3154 *app = freealias(*app);
3164 printalias(const struct alias *ap)
3166 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3170 * TODO - sort output
3172 static int FAST_FUNC
3173 aliascmd(int argc UNUSED_PARAM, char **argv)
3182 for (i = 0; i < ATABSIZE; i++) {
3183 for (ap = atab[i]; ap; ap = ap->next) {
3189 while ((n = *++argv) != NULL) {
3190 v = strchr(n+1, '=');
3191 if (v == NULL) { /* n+1: funny ksh stuff */
3192 ap = *__lookupalias(n);
3194 fprintf(stderr, "%s: %s not found\n", "alias", n);
3207 static int FAST_FUNC
3208 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3212 while ((i = nextopt("a")) != '\0') {
3218 for (i = 0; *argptr; argptr++) {
3219 if (unalias(*argptr)) {
3220 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3228 #endif /* ASH_ALIAS */
3231 /* ============ jobs.c */
3233 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3236 #define FORK_NOJOB 2
3238 /* mode flags for showjob(s) */
3239 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3240 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3241 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3244 * A job structure contains information about a job. A job is either a
3245 * single process or a set of processes contained in a pipeline. In the
3246 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3250 pid_t pid; /* process id */
3251 int status; /* last process status from wait() */
3252 char *cmd; /* text of command being run */
3256 struct procstat ps0; /* status of process */
3257 struct procstat *ps; /* status or processes when more than one */
3259 int stopstatus; /* status of a stopped job */
3262 nprocs: 16, /* number of processes */
3264 #define JOBRUNNING 0 /* at least one proc running */
3265 #define JOBSTOPPED 1 /* all procs are stopped */
3266 #define JOBDONE 2 /* all procs are completed */
3268 sigint: 1, /* job was killed by SIGINT */
3269 jobctl: 1, /* job running under job control */
3271 waited: 1, /* true if this entry has been waited for */
3272 used: 1, /* true if this entry is in used */
3273 changed: 1; /* true if status has changed */
3274 struct job *prev_job; /* previous job */
3277 static struct job *makejob(/*union node *,*/ int);
3278 static int forkshell(struct job *, union node *, int);
3279 static int waitforjob(struct job *);
3282 enum { doing_jobctl = 0 };
3283 #define setjobctl(on) do {} while (0)
3285 static smallint doing_jobctl; //references:8
3286 static void setjobctl(int);
3293 ignoresig(int signo)
3295 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3296 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3297 /* No, need to do it */
3298 signal(signo, SIG_IGN);
3300 sigmode[signo - 1] = S_HARD_IGN;
3304 * Signal handler. Only one usage site - in setsignal()
3309 gotsig[signo - 1] = 1;
3311 if (signo == SIGINT && !trap[SIGINT]) {
3312 if (!suppress_int) {
3314 raise_interrupt(); /* does not return */
3318 pending_sig = signo;
3323 * Set the signal handler for the specified signal. The routine figures
3324 * out what it should be set to.
3327 setsignal(int signo)
3330 char cur_act, new_act;
3331 struct sigaction act;
3335 if (t != NULL) { /* trap for this sig is set */
3337 if (t[0] == '\0') /* trap is "": ignore this sig */
3341 if (rootshell && new_act == S_DFL) {
3344 if (iflag || minusc || sflag == 0)
3353 * "In all cases, bash ignores SIGQUIT. Non-builtin
3354 * commands run by bash have signal handlers
3355 * set to the values inherited by the shell
3356 * from its parent". */
3372 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3373 //whereas we have to restore it to what shell got on entry
3374 //from the parent. See comment above
3376 t = &sigmode[signo - 1];
3379 /* current setting is not yet known */
3380 if (sigaction(signo, NULL, &act)) {
3381 /* pretend it worked; maybe we should give a warning,
3382 * but other shells don't. We don't alter sigmode,
3383 * so we retry every time.
3384 * btw, in Linux it never fails. --vda */
3387 if (act.sa_handler == SIG_IGN) {
3388 cur_act = S_HARD_IGN;
3390 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3392 cur_act = S_IGN; /* don't hard ignore these */
3396 if (cur_act == S_HARD_IGN || cur_act == new_act)
3399 act.sa_handler = SIG_DFL;
3402 act.sa_handler = onsig;
3403 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3404 sigfillset(&act.sa_mask); /* ditto */
3407 act.sa_handler = SIG_IGN;
3410 sigaction_set(signo, &act);
3415 /* mode flags for set_curjob */
3416 #define CUR_DELETE 2
3417 #define CUR_RUNNING 1
3418 #define CUR_STOPPED 0
3420 /* mode flags for dowait */
3421 #define DOWAIT_NONBLOCK WNOHANG
3422 #define DOWAIT_BLOCK 0
3425 /* pgrp of shell on invocation */
3426 static int initialpgrp; //references:2
3427 static int ttyfd = -1; //5
3430 static struct job *jobtab; //5
3432 static unsigned njobs; //4
3434 static struct job *curjob; //lots
3435 /* number of presumed living untracked jobs */
3436 static int jobless; //4
3439 set_curjob(struct job *jp, unsigned mode)
3442 struct job **jpp, **curp;
3444 /* first remove from list */
3445 jpp = curp = &curjob;
3450 jpp = &jp1->prev_job;
3452 *jpp = jp1->prev_job;
3454 /* Then re-insert in correct position */
3462 /* job being deleted */
3465 /* newly created job or backgrounded job,
3466 put after all stopped jobs. */
3470 if (!jp1 || jp1->state != JOBSTOPPED)
3473 jpp = &jp1->prev_job;
3479 /* newly stopped job - becomes curjob */
3480 jp->prev_job = *jpp;
3488 jobno(const struct job *jp)
3490 return jp - jobtab + 1;
3495 * Convert a job name to a job structure.
3498 #define getjob(name, getctl) getjob(name)
3501 getjob(const char *name, int getctl)
3505 const char *err_msg = "%s: no such job";
3509 char *(*match)(const char *, const char *);
3524 if (c == '+' || c == '%') {
3526 err_msg = "No current job";
3532 err_msg = "No previous job";
3543 jp = jobtab + num - 1;
3558 if (match(jp->ps[0].cmd, p)) {
3562 err_msg = "%s: ambiguous";
3572 err_msg = "job %s not created under job control";
3573 if (getctl && jp->jobctl == 0)
3578 ash_msg_and_raise_error(err_msg, name);
3582 * Mark a job structure as unused.
3585 freejob(struct job *jp)
3587 struct procstat *ps;
3591 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3592 if (ps->cmd != nullstr)
3595 if (jp->ps != &jp->ps0)
3598 set_curjob(jp, CUR_DELETE);
3604 xtcsetpgrp(int fd, pid_t pgrp)
3606 if (tcsetpgrp(fd, pgrp))
3607 ash_msg_and_raise_error("can't set tty process group (%m)");
3611 * Turn job control on and off.
3613 * Note: This code assumes that the third arg to ioctl is a character
3614 * pointer, which is true on Berkeley systems but not System V. Since
3615 * System V doesn't have job control yet, this isn't a problem now.
3617 * Called with interrupts off.
3625 if (on == doing_jobctl || rootshell == 0)
3629 ofd = fd = open(_PATH_TTY, O_RDWR);
3631 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3632 * That sometimes helps to acquire controlling tty.
3633 * Obviously, a workaround for bugs when someone
3634 * failed to provide a controlling tty to bash! :) */
3640 fd = fcntl(fd, F_DUPFD, 10);
3645 /* fd is a tty at this point */
3646 close_on_exec_on(fd);
3647 do { /* while we are in the background */
3648 pgrp = tcgetpgrp(fd);
3651 ash_msg("can't access tty; job control turned off");
3655 if (pgrp == getpgrp())
3666 xtcsetpgrp(fd, pgrp);
3668 /* turning job control off */
3671 /* was xtcsetpgrp, but this can make exiting ash
3672 * loop forever if pty is already deleted */
3673 tcsetpgrp(fd, pgrp);
3687 static int FAST_FUNC
3688 killcmd(int argc, char **argv)
3691 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3693 if (argv[i][0] == '%') {
3694 struct job *jp = getjob(argv[i], 0);
3695 unsigned pid = jp->ps[0].pid;
3696 /* Enough space for ' -NNN<nul>' */
3697 argv[i] = alloca(sizeof(int)*3 + 3);
3698 /* kill_main has matching code to expect
3699 * leading space. Needed to not confuse
3700 * negative pids with "kill -SIGNAL_NO" syntax */
3701 sprintf(argv[i], " -%u", pid);
3703 } while (argv[++i]);
3705 return kill_main(argc, argv);
3709 showpipe(struct job *jp, FILE *out)
3711 struct procstat *sp;
3712 struct procstat *spend;
3714 spend = jp->ps + jp->nprocs;
3715 for (sp = jp->ps + 1; sp < spend; sp++)
3716 fprintf(out, " | %s", sp->cmd);
3717 outcslow('\n', out);
3718 flush_stdout_stderr();
3723 restartjob(struct job *jp, int mode)
3725 struct procstat *ps;
3731 if (jp->state == JOBDONE)
3733 jp->state = JOBRUNNING;
3735 if (mode == FORK_FG)
3736 xtcsetpgrp(ttyfd, pgid);
3737 killpg(pgid, SIGCONT);
3741 if (WIFSTOPPED(ps->status)) {
3747 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3752 static int FAST_FUNC
3753 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3760 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3765 jp = getjob(*argv, 1);
3766 if (mode == FORK_BG) {
3767 set_curjob(jp, CUR_RUNNING);
3768 fprintf(out, "[%d] ", jobno(jp));
3770 outstr(jp->ps->cmd, out);
3772 retval = restartjob(jp, mode);
3773 } while (*argv && *++argv);
3779 sprint_status(char *s, int status, int sigonly)
3785 if (!WIFEXITED(status)) {
3787 if (WIFSTOPPED(status))
3788 st = WSTOPSIG(status);
3791 st = WTERMSIG(status);
3793 if (st == SIGINT || st == SIGPIPE)
3796 if (WIFSTOPPED(status))
3801 col = fmtstr(s, 32, strsignal(st));
3802 if (WCOREDUMP(status)) {
3803 col += fmtstr(s + col, 16, " (core dumped)");
3805 } else if (!sigonly) {
3806 st = WEXITSTATUS(status);
3808 col = fmtstr(s, 16, "Done(%d)", st);
3810 col = fmtstr(s, 16, "Done");
3817 dowait(int wait_flags, struct job *job)
3822 struct job *thisjob;
3825 TRACE(("dowait(0x%x) called\n", wait_flags));
3827 /* Do a wait system call. If job control is compiled in, we accept
3828 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3829 * NB: _not_ safe_waitpid, we need to detect EINTR */
3830 pid = waitpid(-1, &status,
3831 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3832 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3833 pid, status, errno, strerror(errno)));
3839 for (jp = curjob; jp; jp = jp->prev_job) {
3840 struct procstat *sp;
3841 struct procstat *spend;
3842 if (jp->state == JOBDONE)
3845 spend = jp->ps + jp->nprocs;
3848 if (sp->pid == pid) {
3849 TRACE(("Job %d: changing status of proc %d "
3850 "from 0x%x to 0x%x\n",
3851 jobno(jp), pid, sp->status, status));
3852 sp->status = status;
3855 if (sp->status == -1)
3858 if (state == JOBRUNNING)
3860 if (WIFSTOPPED(sp->status)) {
3861 jp->stopstatus = sp->status;
3865 } while (++sp < spend);
3870 if (!WIFSTOPPED(status))
3876 if (state != JOBRUNNING) {
3877 thisjob->changed = 1;
3879 if (thisjob->state != state) {
3880 TRACE(("Job %d: changing state from %d to %d\n",
3881 jobno(thisjob), thisjob->state, state));
3882 thisjob->state = state;
3884 if (state == JOBSTOPPED) {
3885 set_curjob(thisjob, CUR_STOPPED);
3894 if (thisjob && thisjob == job) {
3898 len = sprint_status(s, status, 1);
3909 blocking_wait_with_raise_on_sig(struct job *job)
3911 pid_t pid = dowait(DOWAIT_BLOCK, job);
3912 if (pid <= 0 && pending_sig)
3913 raise_exception(EXSIG);
3919 showjob(FILE *out, struct job *jp, int mode)
3921 struct procstat *ps;
3922 struct procstat *psend;
3929 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3930 /* just output process (group) id of pipeline */
3931 fprintf(out, "%d\n", ps->pid);
3935 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3940 else if (curjob && jp == curjob->prev_job)
3943 if (mode & SHOW_PIDS)
3944 col += fmtstr(s + col, 16, "%d ", ps->pid);
3946 psend = ps + jp->nprocs;
3948 if (jp->state == JOBRUNNING) {
3949 strcpy(s + col, "Running");
3950 col += sizeof("Running") - 1;
3952 int status = psend[-1].status;
3953 if (jp->state == JOBSTOPPED)
3954 status = jp->stopstatus;
3955 col += sprint_status(s + col, status, 0);
3957 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3959 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3960 * or prints several "PID | <cmdN>" lines,
3961 * depending on SHOW_PIDS bit.
3962 * We do not print status of individual processes
3963 * between PID and <cmdN>. bash does it, but not very well:
3964 * first line shows overall job status, not process status,
3965 * making it impossible to know 1st process status.
3969 /* for each process */
3972 if (mode & SHOW_PIDS)
3973 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3975 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3978 fprintf(out, "%s", ps->cmd);
3982 outcslow('\n', out);
3986 if (jp->state == JOBDONE) {
3987 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3993 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3994 * statuses have changed since the last call to showjobs.
3997 showjobs(FILE *out, int mode)
4001 TRACE(("showjobs(0x%x) called\n", mode));
4003 /* Handle all finished jobs */
4004 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4007 for (jp = curjob; jp; jp = jp->prev_job) {
4008 if (!(mode & SHOW_CHANGED) || jp->changed) {
4009 showjob(out, jp, mode);
4014 static int FAST_FUNC
4015 jobscmd(int argc UNUSED_PARAM, char **argv)
4020 while ((m = nextopt("lp")) != '\0') {
4024 mode |= SHOW_ONLY_PGID;
4030 showjob(stdout, getjob(*argv, 0), mode);
4033 showjobs(stdout, mode);
4040 getstatus(struct job *job)
4045 status = job->ps[job->nprocs - 1].status;
4046 retval = WEXITSTATUS(status);
4047 if (!WIFEXITED(status)) {
4049 retval = WSTOPSIG(status);
4050 if (!WIFSTOPPED(status))
4053 /* XXX: limits number of signals */
4054 retval = WTERMSIG(status);
4056 if (retval == SIGINT)
4062 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4063 jobno(job), job->nprocs, status, retval));
4067 static int FAST_FUNC
4068 waitcmd(int argc UNUSED_PARAM, char **argv)
4075 raise_exception(EXSIG);
4082 /* wait for all jobs */
4086 if (!jp) /* no running procs */
4088 if (jp->state == JOBRUNNING)
4094 * "When bash is waiting for an asynchronous command via
4095 * the wait builtin, the reception of a signal for which a trap
4096 * has been set will cause the wait builtin to return immediately
4097 * with an exit status greater than 128, immediately after which
4098 * the trap is executed."
4099 * Do we do it that way? */
4100 blocking_wait_with_raise_on_sig(NULL);
4106 if (**argv != '%') {
4107 pid_t pid = number(*argv);
4112 if (job->ps[job->nprocs - 1].pid == pid)
4114 job = job->prev_job;
4117 job = getjob(*argv, 0);
4118 /* loop until process terminated or stopped */
4119 while (job->state == JOBRUNNING)
4120 blocking_wait_with_raise_on_sig(NULL);
4122 retval = getstatus(job);
4135 struct job *jp, *jq;
4137 len = njobs * sizeof(*jp);
4139 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4141 offset = (char *)jp - (char *)jq;
4143 /* Relocate pointers */
4146 jq = (struct job *)((char *)jq + l);
4150 #define joff(p) ((struct job *)((char *)(p) + l))
4151 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4152 if (joff(jp)->ps == &jq->ps0)
4153 jmove(joff(jp)->ps);
4154 if (joff(jp)->prev_job)
4155 jmove(joff(jp)->prev_job);
4165 jp = (struct job *)((char *)jp + len);
4169 } while (--jq >= jp);
4174 * Return a new job structure.
4175 * Called with interrupts off.
4178 makejob(/*union node *node,*/ int nprocs)
4183 for (i = njobs, jp = jobtab; ; jp++) {
4190 if (jp->state != JOBDONE || !jp->waited)
4199 memset(jp, 0, sizeof(*jp));
4201 /* jp->jobctl is a bitfield.
4202 * "jp->jobctl |= jobctl" likely to give awful code */
4206 jp->prev_job = curjob;
4211 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4213 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4220 * Return a string identifying a command (to be printed by the
4223 static char *cmdnextc;
4226 cmdputs(const char *s)
4228 static const char vstype[VSTYPE + 1][3] = {
4229 "", "}", "-", "+", "?", "=",
4230 "%", "%%", "#", "##"
4231 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4234 const char *p, *str;
4235 char c, cc[2] = " ";
4240 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4242 while ((c = *p++) != 0) {
4250 if ((subtype & VSTYPE) == VSLENGTH)
4254 if (!(subtype & VSQUOTE) == !(quoted & 1))
4260 str = "\"}" + !(quoted & 1);
4267 case CTLBACKQ+CTLQUOTE:
4270 #if ENABLE_SH_MATH_SUPPORT
4285 if ((subtype & VSTYPE) != VSNORMAL)
4287 str = vstype[subtype & VSTYPE];
4288 if (subtype & VSNUL)
4297 /* These can only happen inside quotes */
4310 while ((c = *str++) != '\0') {
4315 USTPUTC('"', nextc);
4321 /* cmdtxt() and cmdlist() call each other */
4322 static void cmdtxt(union node *n);
4325 cmdlist(union node *np, int sep)
4327 for (; np; np = np->narg.next) {
4331 if (sep && np->narg.next)
4337 cmdtxt(union node *n)
4340 struct nodelist *lp;
4351 lp = n->npipe.cmdlist;
4369 cmdtxt(n->nbinary.ch1);
4385 cmdtxt(n->nif.test);
4387 if (n->nif.elsepart) {
4388 cmdtxt(n->nif.ifpart);
4390 n = n->nif.elsepart;
4408 cmdtxt(n->nbinary.ch1);
4418 cmdputs(n->nfor.var);
4420 cmdlist(n->nfor.args, 1);
4425 cmdputs(n->narg.text);
4429 cmdlist(n->ncmd.args, 1);
4430 cmdlist(n->ncmd.redirect, 0);
4443 cmdputs(n->ncase.expr->narg.text);
4445 for (np = n->ncase.cases; np; np = np->nclist.next) {
4446 cmdtxt(np->nclist.pattern);
4448 cmdtxt(np->nclist.body);
4462 #if ENABLE_ASH_BASH_COMPAT
4477 cmdputs(utoa(n->nfile.fd));
4479 if (n->type == NTOFD || n->type == NFROMFD) {
4480 cmdputs(utoa(n->ndup.dupfd));
4489 commandtext(union node *n)
4493 STARTSTACKSTR(cmdnextc);
4495 name = stackblock();
4496 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4497 name, cmdnextc, cmdnextc));
4498 return ckstrdup(name);
4503 * Fork off a subshell. If we are doing job control, give the subshell its
4504 * own process group. Jp is a job structure that the job is to be added to.
4505 * N is the command that will be evaluated by the child. Both jp and n may
4506 * be NULL. The mode parameter can be one of the following:
4507 * FORK_FG - Fork off a foreground process.
4508 * FORK_BG - Fork off a background process.
4509 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4510 * process group even if job control is on.
4512 * When job control is turned off, background processes have their standard
4513 * input redirected to /dev/null (except for the second and later processes
4516 * Called with interrupts off.
4519 * Clear traps on a fork.
4526 for (tp = trap; tp < &trap[NSIG]; tp++) {
4527 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4529 if (trap_ptr == trap)
4531 /* else: it "belongs" to trap_ptr vector, don't free */
4533 if ((tp - trap) != 0)
4534 setsignal(tp - trap);
4540 /* Lives far away from here, needed for forkchild */
4541 static void closescript(void);
4543 /* Called after fork(), in child */
4544 static NOINLINE void
4545 forkchild(struct job *jp, union node *n, int mode)
4549 TRACE(("Child shell %d\n", getpid()));
4553 /* man bash: "Non-builtin commands run by bash have signal handlers
4554 * set to the values inherited by the shell from its parent".
4555 * Do we do it correctly? */
4559 if (mode == FORK_NOJOB /* is it `xxx` ? */
4560 && n && n->type == NCMD /* is it single cmd? */
4561 /* && n->ncmd.args->type == NARG - always true? */
4562 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4563 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4564 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4566 TRACE(("Trap hack\n"));
4567 /* Awful hack for `trap` or $(trap).
4569 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4570 * contains an example where "trap" is executed in a subshell:
4572 * save_traps=$(trap)
4574 * eval "$save_traps"
4576 * Standard does not say that "trap" in subshell shall print
4577 * parent shell's traps. It only says that its output
4578 * must have suitable form, but then, in the above example
4579 * (which is not supposed to be normative), it implies that.
4581 * bash (and probably other shell) does implement it
4582 * (traps are reset to defaults, but "trap" still shows them),
4583 * but as a result, "trap" logic is hopelessly messed up:
4586 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4587 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4588 * # true | trap <--- trap is in subshell - no output (ditto)
4589 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4590 * trap -- 'echo Ho' SIGWINCH
4591 * # echo `(trap)` <--- in subshell in subshell - output
4592 * trap -- 'echo Ho' SIGWINCH
4593 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4594 * trap -- 'echo Ho' SIGWINCH
4596 * The rules when to forget and when to not forget traps
4597 * get really complex and nonsensical.
4599 * Our solution: ONLY bare $(trap) or `trap` is special.
4601 /* Save trap handler strings for trap builtin to print */
4602 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4603 /* Fall through into clearing traps */
4607 /* do job control only in root shell */
4609 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4612 if (jp->nprocs == 0)
4615 pgrp = jp->ps[0].pid;
4616 /* this can fail because we are doing it in the parent also */
4618 if (mode == FORK_FG)
4619 xtcsetpgrp(ttyfd, pgrp);
4624 if (mode == FORK_BG) {
4625 /* man bash: "When job control is not in effect,
4626 * asynchronous commands ignore SIGINT and SIGQUIT" */
4629 if (jp->nprocs == 0) {
4631 if (open(bb_dev_null, O_RDONLY) != 0)
4632 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4636 if (iflag) { /* why if iflag only? */
4641 * "In all cases, bash ignores SIGQUIT. Non-builtin
4642 * commands run by bash have signal handlers
4643 * set to the values inherited by the shell
4645 * Take care of the second rule: */
4649 if (n && n->type == NCMD
4650 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4652 TRACE(("Job hack\n"));
4653 /* "jobs": we do not want to clear job list for it,
4654 * instead we remove only _its_ own_ job from job list.
4655 * This makes "jobs .... | cat" more useful.
4661 for (jp = curjob; jp; jp = jp->prev_job)
4666 /* Called after fork(), in parent */
4668 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4671 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4673 TRACE(("In parent shell: child = %d\n", pid));
4675 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4681 if (mode != FORK_NOJOB && jp->jobctl) {
4684 if (jp->nprocs == 0)
4687 pgrp = jp->ps[0].pid;
4688 /* This can fail because we are doing it in the child also */
4692 if (mode == FORK_BG) {
4693 backgndpid = pid; /* set $! */
4694 set_curjob(jp, CUR_RUNNING);
4697 struct procstat *ps = &jp->ps[jp->nprocs++];
4702 if (doing_jobctl && n)
4703 ps->cmd = commandtext(n);
4709 forkshell(struct job *jp, union node *n, int mode)
4713 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4716 TRACE(("Fork failed, errno=%d", errno));
4719 ash_msg_and_raise_error("can't fork");
4722 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4723 forkchild(jp, n, mode);
4725 forkparent(jp, n, mode, pid);
4731 * Wait for job to finish.
4733 * Under job control we have the problem that while a child process
4734 * is running interrupts generated by the user are sent to the child
4735 * but not to the shell. This means that an infinite loop started by
4736 * an interactive user may be hard to kill. With job control turned off,
4737 * an interactive user may place an interactive program inside a loop.
4738 * If the interactive program catches interrupts, the user doesn't want
4739 * these interrupts to also abort the loop. The approach we take here
4740 * is to have the shell ignore interrupt signals while waiting for a
4741 * foreground process to terminate, and then send itself an interrupt
4742 * signal if the child process was terminated by an interrupt signal.
4743 * Unfortunately, some programs want to do a bit of cleanup and then
4744 * exit on interrupt; unless these processes terminate themselves by
4745 * sending a signal to themselves (instead of calling exit) they will
4746 * confuse this approach.
4748 * Called with interrupts off.
4751 waitforjob(struct job *jp)
4755 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4758 while (jp->state == JOBRUNNING) {
4759 /* In non-interactive shells, we _can_ get
4760 * a keyboard signal here and be EINTRed,
4761 * but we just loop back, waiting for command to complete.
4764 * "If bash is waiting for a command to complete and receives
4765 * a signal for which a trap has been set, the trap
4766 * will not be executed until the command completes."
4768 * Reality is that even if trap is not set, bash
4769 * will not act on the signal until command completes.
4770 * Try this. sleep5intoff.c:
4771 * #include <signal.h>
4772 * #include <unistd.h>
4775 * sigemptyset(&set);
4776 * sigaddset(&set, SIGINT);
4777 * sigaddset(&set, SIGQUIT);
4778 * sigprocmask(SIG_BLOCK, &set, NULL);
4782 * $ bash -c './sleep5intoff; echo hi'
4783 * ^C^C^C^C <--- pressing ^C once a second
4785 * $ bash -c './sleep5intoff; echo hi'
4786 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4789 dowait(DOWAIT_BLOCK, jp);
4796 xtcsetpgrp(ttyfd, rootpid);
4798 * This is truly gross.
4799 * If we're doing job control, then we did a TIOCSPGRP which
4800 * caused us (the shell) to no longer be in the controlling
4801 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4802 * intuit from the subprocess exit status whether a SIGINT
4803 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4805 if (jp->sigint) /* TODO: do the same with all signals */
4806 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4808 if (jp->state == JOBDONE)
4815 * return 1 if there are stopped jobs, otherwise 0
4827 if (jp && jp->state == JOBSTOPPED) {
4828 out2str("You have stopped jobs.\n");
4837 /* ============ redir.c
4839 * Code for dealing with input/output redirection.
4842 #define EMPTY -2 /* marks an unused slot in redirtab */
4843 #define CLOSED -3 /* marks a slot of previously-closed fd */
4846 * Open a file in noclobber mode.
4847 * The code was copied from bash.
4850 noclobberopen(const char *fname)
4853 struct stat finfo, finfo2;
4856 * If the file exists and is a regular file, return an error
4859 r = stat(fname, &finfo);
4860 if (r == 0 && S_ISREG(finfo.st_mode)) {
4866 * If the file was not present (r != 0), make sure we open it
4867 * exclusively so that if it is created before we open it, our open
4868 * will fail. Make sure that we do not truncate an existing file.
4869 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4870 * file was not a regular file, we leave O_EXCL off.
4873 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4874 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4876 /* If the open failed, return the file descriptor right away. */
4881 * OK, the open succeeded, but the file may have been changed from a
4882 * non-regular file to a regular file between the stat and the open.
4883 * We are assuming that the O_EXCL open handles the case where FILENAME
4884 * did not exist and is symlinked to an existing file between the stat
4889 * If we can open it and fstat the file descriptor, and neither check
4890 * revealed that it was a regular file, and the file has not been
4891 * replaced, return the file descriptor.
4893 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4894 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4897 /* The file has been replaced. badness. */
4904 * Handle here documents. Normally we fork off a process to write the
4905 * data to a pipe. If the document is short, we can stuff the data in
4906 * the pipe without forking.
4908 /* openhere needs this forward reference */
4909 static void expandhere(union node *arg, int fd);
4911 openhere(union node *redir)
4917 ash_msg_and_raise_error("pipe call failed");
4918 if (redir->type == NHERE) {
4919 len = strlen(redir->nhere.doc->narg.text);
4920 if (len <= PIPE_BUF) {
4921 full_write(pip[1], redir->nhere.doc->narg.text, len);
4925 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4928 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4929 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4930 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4931 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4932 signal(SIGPIPE, SIG_DFL);
4933 if (redir->type == NHERE)
4934 full_write(pip[1], redir->nhere.doc->narg.text, len);
4936 expandhere(redir->nhere.doc, pip[1]);
4937 _exit(EXIT_SUCCESS);
4945 openredirect(union node *redir)
4950 switch (redir->nfile.type) {
4952 fname = redir->nfile.expfname;
4953 f = open(fname, O_RDONLY);
4958 fname = redir->nfile.expfname;
4959 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4964 #if ENABLE_ASH_BASH_COMPAT
4967 /* Take care of noclobber mode. */
4969 fname = redir->nfile.expfname;
4970 f = noclobberopen(fname);
4977 fname = redir->nfile.expfname;
4978 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4983 fname = redir->nfile.expfname;
4984 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4992 /* Fall through to eliminate warning. */
4993 /* Our single caller does this itself */
5000 f = openhere(redir);
5006 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5008 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5012 * Copy a file descriptor to be >= to. Returns -1
5013 * if the source file descriptor is closed, EMPTY if there are no unused
5014 * file descriptors left.
5016 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5017 * old code was doing close(to) prior to copyfd() to achieve the same */
5019 COPYFD_EXACT = (int)~(INT_MAX),
5020 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5023 copyfd(int from, int to)
5027 if (to & COPYFD_EXACT) {
5028 to &= ~COPYFD_EXACT;
5030 newfd = dup2(from, to);
5032 newfd = fcntl(from, F_DUPFD, to);
5035 if (errno == EMFILE)
5037 /* Happens when source fd is not open: try "echo >&99" */
5038 ash_msg_and_raise_error("%d: %m", from);
5043 /* Struct def and variable are moved down to the first usage site */
5048 struct redirtab *next;
5051 struct two_fd_t two_fd[];
5053 #define redirlist (G_var.redirlist)
5055 static int need_to_remember(struct redirtab *rp, int fd)
5059 if (!rp) /* remembering was not requested */
5062 for (i = 0; i < rp->pair_count; i++) {
5063 if (rp->two_fd[i].orig == fd) {
5064 /* already remembered */
5071 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5072 static int is_hidden_fd(struct redirtab *rp, int fd)
5075 struct parsefile *pf;
5088 fd |= COPYFD_RESTORE;
5089 for (i = 0; i < rp->pair_count; i++) {
5090 if (rp->two_fd[i].copy == fd) {
5098 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5099 * old file descriptors are stashed away so that the redirection can be
5100 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5101 * standard output, and the standard error if it becomes a duplicate of
5102 * stdout, is saved in memory.
5104 /* flags passed to redirect */
5105 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5106 #define REDIR_SAVEFD2 03 /* set preverrout */
5108 redirect(union node *redir, int flags)
5110 struct redirtab *sv;
5115 int copied_fd2 = -1;
5125 if (flags & REDIR_PUSH) {
5126 union node *tmp = redir;
5129 #if ENABLE_ASH_BASH_COMPAT
5130 if (redir->nfile.type == NTO2)
5133 tmp = tmp->nfile.next;
5135 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5136 sv->next = redirlist;
5137 sv->pair_count = sv_pos;
5139 sv->nullredirs = g_nullredirs - 1;
5141 while (sv_pos > 0) {
5143 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5148 fd = redir->nfile.fd;
5149 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5150 int right_fd = redir->ndup.dupfd;
5151 /* redirect from/to same file descriptor? */
5154 /* echo >&10 and 10 is a fd opened to the sh script? */
5155 if (is_hidden_fd(sv, right_fd)) {
5156 errno = EBADF; /* as if it is closed */
5157 ash_msg_and_raise_error("%d: %m", right_fd);
5161 newfd = openredirect(redir); /* always >= 0 */
5163 /* Descriptor wasn't open before redirect.
5164 * Mark it for close in the future */
5165 if (need_to_remember(sv, fd)) {
5166 goto remember_to_close;
5171 #if ENABLE_ASH_BASH_COMPAT
5174 if (need_to_remember(sv, fd)) {
5175 /* Copy old descriptor */
5176 i = fcntl(fd, F_DUPFD, 10);
5177 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5178 * are closed in popredir() in the child, preventing them from leaking
5179 * into child. (popredir() also cleans up the mess in case of failures)
5184 /* Strange error (e.g. "too many files" EMFILE?) */
5188 ash_msg_and_raise_error("%d: %m", fd);
5191 /* EBADF: it is not open - good, remember to close it */
5194 } else { /* fd is open, save its copy */
5195 /* "exec fd>&-" should not close fds
5196 * which point to script file(s).
5197 * Force them to be restored afterwards */
5198 if (is_hidden_fd(sv, fd))
5199 i |= COPYFD_RESTORE;
5203 sv->two_fd[sv_pos].orig = fd;
5204 sv->two_fd[sv_pos].copy = i;
5208 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5209 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5210 /* Don't want to trigger debugging */
5214 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5216 } else if (fd != newfd) { /* move newfd to fd */
5217 copyfd(newfd, fd | COPYFD_EXACT);
5218 #if ENABLE_ASH_BASH_COMPAT
5219 if (!(redir->nfile.type == NTO2 && fd == 2))
5223 #if ENABLE_ASH_BASH_COMPAT
5224 if (redir->nfile.type == NTO2 && fd == 1) {
5225 /* We already redirected it to fd 1, now copy it to 2 */
5231 } while ((redir = redir->nfile.next) != NULL);
5234 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5235 preverrout_fd = copied_fd2;
5239 * Undo the effects of the last redirection.
5242 popredir(int drop, int restore)
5244 struct redirtab *rp;
5247 if (--g_nullredirs >= 0)
5251 for (i = 0; i < rp->pair_count; i++) {
5252 int fd = rp->two_fd[i].orig;
5253 int copy = rp->two_fd[i].copy;
5254 if (copy == CLOSED) {
5259 if (copy != EMPTY) {
5260 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5261 copy &= ~COPYFD_RESTORE;
5263 copyfd(copy, fd | COPYFD_EXACT);
5265 close(copy & ~COPYFD_RESTORE);
5268 redirlist = rp->next;
5269 g_nullredirs = rp->nullredirs;
5275 * Undo all redirections. Called on error or interrupt.
5279 * Discard all saved file descriptors.
5282 clearredir(int drop)
5288 popredir(drop, /*restore:*/ 0);
5293 redirectsafe(union node *redir, int flags)
5296 volatile int saveint;
5297 struct jmploc *volatile savehandler = exception_handler;
5298 struct jmploc jmploc;
5301 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5302 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5304 exception_handler = &jmploc;
5305 redirect(redir, flags);
5307 exception_handler = savehandler;
5308 if (err && exception_type != EXERROR)
5309 longjmp(exception_handler->loc, 1);
5310 RESTORE_INT(saveint);
5315 /* ============ Routines to expand arguments to commands
5317 * We have to deal with backquotes, shell variables, and file metacharacters.
5320 #if ENABLE_SH_MATH_SUPPORT
5322 ash_arith(const char *s)
5324 arith_eval_hooks_t math_hooks;
5328 math_hooks.lookupvar = lookupvar;
5329 math_hooks.setvar = setvar;
5330 math_hooks.endofname = endofname;
5333 result = arith(s, &errcode, &math_hooks);
5336 ash_msg_and_raise_error("exponent less than 0");
5338 ash_msg_and_raise_error("divide by zero");
5340 ash_msg_and_raise_error("expression recursion loop detected");
5341 raise_error_syntax(s);
5352 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5353 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5354 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5355 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5356 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5357 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5358 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5359 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5360 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5364 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5365 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5366 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5367 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5368 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5371 * Structure specifying which parts of the string should be searched
5372 * for IFS characters.
5375 struct ifsregion *next; /* next region in list */
5376 int begoff; /* offset of start of region */
5377 int endoff; /* offset of end of region */
5378 int nulonly; /* search for nul bytes only */
5382 struct strlist *list;
5383 struct strlist **lastp;
5386 /* output of current string */
5387 static char *expdest;
5388 /* list of back quote expressions */
5389 static struct nodelist *argbackq;
5390 /* first struct in list of ifs regions */
5391 static struct ifsregion ifsfirst;
5392 /* last struct in list */
5393 static struct ifsregion *ifslastp;
5394 /* holds expanded arg list */
5395 static struct arglist exparg;
5405 expdest = makestrspace(32, expdest);
5406 len = fmtstr(expdest, 32, arith_t_fmt, num);
5407 STADJUST(len, expdest);
5412 esclen(const char *start, const char *p)
5416 while (p > start && (unsigned char)*--p == CTLESC) {
5423 * Remove any CTLESC characters from a string.
5426 rmescapes(char *str, int flag)
5428 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5432 unsigned protect_against_glob;
5435 p = strpbrk(str, qchars);
5441 if (flag & RMESCAPE_ALLOC) {
5442 size_t len = p - str;
5443 size_t fulllen = len + strlen(p) + 1;
5445 if (flag & RMESCAPE_GROW) {
5446 r = makestrspace(fulllen, expdest);
5447 } else if (flag & RMESCAPE_HEAP) {
5448 r = ckmalloc(fulllen);
5450 r = stalloc(fulllen);
5454 q = (char *)memcpy(q, str, len) + len;
5458 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5459 globbing = flag & RMESCAPE_GLOB;
5460 protect_against_glob = globbing;
5462 if (*p == CTLQUOTEMARK) {
5463 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5464 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5465 // Note: both inquotes and protect_against_glob only affect whether
5466 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5467 inquotes = ~inquotes;
5469 protect_against_glob = globbing;
5473 /* naked back slash */
5474 protect_against_glob = 0;
5479 if (protect_against_glob && inquotes && *p != '/') {
5483 protect_against_glob = globbing;
5488 if (flag & RMESCAPE_GROW) {
5490 STADJUST(q - r + 1, expdest);
5494 #define pmatch(a, b) !fnmatch((a), (b), 0)
5497 * Prepare a pattern for a expmeta (internal glob(3)) call.
5499 * Returns an stalloced string.
5502 preglob(const char *pattern, int quoted, int flag)
5504 flag |= RMESCAPE_GLOB;
5506 flag |= RMESCAPE_QUOTED;
5508 return rmescapes((char *)pattern, flag);
5512 * Put a string on the stack.
5515 memtodest(const char *p, size_t len, int syntax, int quotes)
5519 q = makestrspace(quotes ? len * 2 : len, q);
5522 int c = signed_char2int(*p++);
5526 int n = SIT(c, syntax);
5527 if (n == CCTL || n == CBACK)
5537 strtodest(const char *p, int syntax, int quotes)
5539 memtodest(p, strlen(p), syntax, quotes);
5543 * Record the fact that we have to scan this region of the
5544 * string for IFS characters.
5547 recordregion(int start, int end, int nulonly)
5549 struct ifsregion *ifsp;
5551 if (ifslastp == NULL) {
5555 ifsp = ckzalloc(sizeof(*ifsp));
5556 /*ifsp->next = NULL; - ckzalloc did it */
5557 ifslastp->next = ifsp;
5561 ifslastp->begoff = start;
5562 ifslastp->endoff = end;
5563 ifslastp->nulonly = nulonly;
5567 removerecordregions(int endoff)
5569 if (ifslastp == NULL)
5572 if (ifsfirst.endoff > endoff) {
5573 while (ifsfirst.next != NULL) {
5574 struct ifsregion *ifsp;
5576 ifsp = ifsfirst.next->next;
5577 free(ifsfirst.next);
5578 ifsfirst.next = ifsp;
5581 if (ifsfirst.begoff > endoff)
5584 ifslastp = &ifsfirst;
5585 ifsfirst.endoff = endoff;
5590 ifslastp = &ifsfirst;
5591 while (ifslastp->next && ifslastp->next->begoff < endoff)
5592 ifslastp=ifslastp->next;
5593 while (ifslastp->next != NULL) {
5594 struct ifsregion *ifsp;
5596 ifsp = ifslastp->next->next;
5597 free(ifslastp->next);
5598 ifslastp->next = ifsp;
5601 if (ifslastp->endoff > endoff)
5602 ifslastp->endoff = endoff;
5606 exptilde(char *startp, char *p, int flags)
5612 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5617 while ((c = *++p) != '\0') {
5624 if (flags & EXP_VARTILDE)
5634 if (*name == '\0') {
5635 home = lookupvar(homestr);
5637 pw = getpwnam(name);
5642 if (!home || !*home)
5645 startloc = expdest - (char *)stackblock();
5646 strtodest(home, SQSYNTAX, quotes);
5647 recordregion(startloc, expdest - (char *)stackblock(), 0);
5655 * Execute a command inside back quotes. If it's a builtin command, we
5656 * want to save its output in a block obtained from malloc. Otherwise
5657 * we fork off a subprocess and get the output of the command via a pipe.
5658 * Should be called with interrupts off.
5660 struct backcmd { /* result of evalbackcmd */
5661 int fd; /* file descriptor to read from */
5662 int nleft; /* number of chars in buffer */
5663 char *buf; /* buffer */
5664 struct job *jp; /* job structure for command */
5667 /* These forward decls are needed to use "eval" code for backticks handling: */
5668 static uint8_t back_exitstatus; /* exit status of backquoted command */
5669 #define EV_EXIT 01 /* exit after evaluating tree */
5670 static void evaltree(union node *, int);
5672 static void FAST_FUNC
5673 evalbackcmd(union node *n, struct backcmd *result)
5684 saveherefd = herefd;
5692 ash_msg_and_raise_error("pipe call failed");
5693 jp = makejob(/*n,*/ 1);
5694 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5699 copyfd(pip[1], 1 | COPYFD_EXACT);
5703 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5707 result->fd = pip[0];
5710 herefd = saveherefd;
5712 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5713 result->fd, result->buf, result->nleft, result->jp));
5717 * Expand stuff in backwards quotes.
5720 expbackq(union node *cmd, int quoted, int quotes)
5728 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5729 struct stackmark smark;
5732 setstackmark(&smark);
5734 startloc = dest - (char *)stackblock();
5736 evalbackcmd(cmd, &in);
5737 popstackmark(&smark);
5744 memtodest(p, i, syntax, quotes);
5748 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5749 TRACE(("expbackq: read returns %d\n", i));
5758 back_exitstatus = waitforjob(in.jp);
5762 /* Eat all trailing newlines */
5764 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5769 recordregion(startloc, dest - (char *)stackblock(), 0);
5770 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5771 (dest - (char *)stackblock()) - startloc,
5772 (dest - (char *)stackblock()) - startloc,
5773 stackblock() + startloc));
5776 #if ENABLE_SH_MATH_SUPPORT
5778 * Expand arithmetic expression. Backup to start of expression,
5779 * evaluate, place result in (backed up) result, adjust string position.
5792 * This routine is slightly over-complicated for
5793 * efficiency. Next we scan backwards looking for the
5794 * start of arithmetic.
5796 start = stackblock();
5803 while (*p != CTLARI) {
5807 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5812 esc = esclen(start, p);
5822 removerecordregions(begoff);
5829 rmescapes(p + 2, 0);
5831 len = cvtnum(ash_arith(p + 2));
5834 recordregion(begoff, begoff + len, 0);
5838 /* argstr needs it */
5839 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5842 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5843 * characters to allow for further processing. Otherwise treat
5844 * $@ like $* since no splitting will be performed.
5846 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5847 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5848 * for correct expansion of "B=$A" word.
5851 argstr(char *p, int flags, struct strlist *var_str_list)
5853 static const char spclchars[] ALIGN1 = {
5861 CTLBACKQ | CTLQUOTE,
5862 #if ENABLE_SH_MATH_SUPPORT
5867 const char *reject = spclchars;
5869 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5870 int breakall = flags & EXP_WORD;
5875 if (!(flags & EXP_VARTILDE)) {
5877 } else if (flags & EXP_VARTILDE2) {
5882 if (flags & EXP_TILDE) {
5885 flags &= ~EXP_TILDE;
5888 if (*q == CTLESC && (flags & EXP_QWORD))
5891 p = exptilde(p, q, flags);
5894 startloc = expdest - (char *)stackblock();
5896 length += strcspn(p + length, reject);
5897 c = (unsigned char) p[length];
5900 #if ENABLE_SH_MATH_SUPPORT
5904 /* c == '=' || c == ':' || c == CTLENDARI */
5910 expdest = stack_nputstr(p, length, expdest);
5911 newloc = expdest - (char *)stackblock();
5912 if (breakall && !inquotes && newloc > startloc) {
5913 recordregion(startloc, newloc, 0);
5924 if (flags & EXP_VARTILDE2) {
5928 flags |= EXP_VARTILDE2;
5933 * sort of a hack - expand tildes in variable
5934 * assignments (after the first '=' and after ':'s).
5943 case CTLENDVAR: /* ??? */
5946 /* "$@" syntax adherence hack */
5948 && memcmp(p, dolatstr, 4) == 0
5949 && ( p[4] == CTLQUOTEMARK
5950 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5953 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5956 inquotes = !inquotes;
5969 p = evalvar(p, flags, var_str_list);
5973 case CTLBACKQ|CTLQUOTE:
5974 expbackq(argbackq->n, c, quotes);
5975 argbackq = argbackq->next;
5977 #if ENABLE_SH_MATH_SUPPORT
5990 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5993 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5994 // as part of a larger change when he added support for ${var/a/b}.
5995 // However, it broke # and % operators:
5999 //echo ${var#ab} abcdcd abcdcd
6000 //echo ${var##ab} abcdcd abcdcd
6001 //echo ${var#a*b} abcdcd ababcdcd (!)
6002 //echo ${var##a*b} cdcd cdcd
6003 //echo ${var#?} babcdcd ababcdcd (!)
6004 //echo ${var##?} babcdcd babcdcd
6005 //echo ${var#*} ababcdcd babcdcd (!)
6007 //echo ${var%cd} ababcd ababcd
6008 //echo ${var%%cd} ababcd abab (!)
6009 //echo ${var%c*d} ababcd ababcd
6010 //echo ${var%%c*d} abab ababcdcd (!)
6011 //echo ${var%?} ababcdc ababcdc
6012 //echo ${var%%?} ababcdc ababcdcd (!)
6013 //echo ${var%*} ababcdcd ababcdcd
6016 // Commenting it back out helped. Remove it completely if it really
6019 char *loc, *loc2; //, *full;
6025 int match; // = strlen(str);
6026 const char *s = loc2;
6033 match = pmatch(str, s); // this line was deleted
6035 // // chop off end if its '*'
6036 // full = strrchr(str, '*');
6037 // if (full && full != str)
6040 // // If str starts with '*' replace with s.
6041 // if ((*str == '*') && strlen(s) >= match) {
6042 // full = xstrdup(s);
6043 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6045 // full = xstrndup(str, match);
6046 // match = strncmp(s, full, strlen(full));
6050 if (match) // if (!match)
6052 if (quotes && *loc == CTLESC)
6061 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6068 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6071 const char *s = loc2;
6076 match = pmatch(str, s);
6083 esc = esclen(startp, loc);
6094 static void varunset(const char *, const char *, const char *, int) NORETURN;
6096 varunset(const char *end, const char *var, const char *umsg, int varflags)
6102 msg = "parameter not set";
6104 if (*end == CTLENDVAR) {
6105 if (varflags & VSNUL)
6111 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6114 #if ENABLE_ASH_BASH_COMPAT
6116 parse_sub_pattern(char *arg, int inquotes)
6118 char *idx, *repl = NULL;
6127 /* Only the first '/' seen is our separator */
6134 if (!inquotes && c == '\\' && arg[1] == '\\')
6135 arg++; /* skip both \\, not just first one */
6142 #endif /* ENABLE_ASH_BASH_COMPAT */
6145 subevalvar(char *p, char *str, int strloc, int subtype,
6146 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6148 struct nodelist *saveargbackq = argbackq;
6151 char *rmesc, *rmescend;
6152 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6153 IF_ASH_BASH_COMPAT(char null = '\0';)
6154 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6155 int saveherefd = herefd;
6156 int amount, workloc, resetloc;
6158 char *(*scan)(char*, char*, char*, char*, int, int);
6161 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6163 STPUTC('\0', expdest);
6164 herefd = saveherefd;
6165 argbackq = saveargbackq;
6166 startp = (char *)stackblock() + startloc;
6170 setvar(str, startp, 0);
6171 amount = startp - expdest;
6172 STADJUST(amount, expdest);
6175 #if ENABLE_ASH_BASH_COMPAT
6177 loc = str = stackblock() + strloc;
6178 /* Read POS in ${var:POS:LEN} */
6179 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6180 len = str - startp - 1;
6182 /* *loc != '\0', guaranteed by parser */
6186 /* Adjust the length by the number of escapes */
6187 for (ptr = startp; ptr < (str - 1); ptr++) {
6188 if (*ptr == CTLESC) {
6196 if (*loc++ == ':') {
6200 /* Skip POS in ${var:POS:LEN} */
6202 while (*loc && *loc != ':') {
6204 * bash complains on: var=qwe; echo ${var:1a:123}
6206 ash_msg_and_raise_error(msg_illnum, str);
6210 if (*loc++ == ':') {
6214 if (pos >= orig_len) {
6218 if (len > (orig_len - pos))
6219 len = orig_len - pos;
6221 for (str = startp; pos; str++, pos--) {
6222 if (quotes && *str == CTLESC)
6225 for (loc = startp; len; len--) {
6226 if (quotes && *str == CTLESC)
6231 amount = loc - expdest;
6232 STADJUST(amount, expdest);
6237 varunset(p, str, startp, varflags);
6240 resetloc = expdest - (char *)stackblock();
6242 /* We'll comeback here if we grow the stack while handling
6243 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6244 * stack will need rebasing, and we'll need to remove our work
6247 IF_ASH_BASH_COMPAT(restart:)
6249 amount = expdest - ((char *)stackblock() + resetloc);
6250 STADJUST(-amount, expdest);
6251 startp = (char *)stackblock() + startloc;
6254 rmescend = (char *)stackblock() + strloc;
6256 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6257 if (rmesc != startp) {
6259 startp = (char *)stackblock() + startloc;
6263 str = (char *)stackblock() + strloc;
6264 preglob(str, varflags & VSQUOTE, 0);
6265 workloc = expdest - (char *)stackblock();
6267 #if ENABLE_ASH_BASH_COMPAT
6268 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6269 char *idx, *end, *restart_detect;
6272 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6277 /* If there's no pattern to match, return the expansion unmolested */
6285 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6287 /* No match, advance */
6288 restart_detect = stackblock();
6289 STPUTC(*idx, expdest);
6290 if (quotes && *idx == CTLESC) {
6293 STPUTC(*idx, expdest);
6295 if (stackblock() != restart_detect)
6303 if (subtype == VSREPLACEALL) {
6305 if (quotes && *idx == CTLESC)
6314 for (loc = repl; *loc; loc++) {
6315 restart_detect = stackblock();
6316 STPUTC(*loc, expdest);
6317 if (stackblock() != restart_detect)
6322 if (subtype == VSREPLACE) {
6324 restart_detect = stackblock();
6325 STPUTC(*idx, expdest);
6326 if (stackblock() != restart_detect)
6335 /* We've put the replaced text into a buffer at workloc, now
6336 * move it to the right place and adjust the stack.
6338 startp = stackblock() + startloc;
6339 STPUTC('\0', expdest);
6340 memmove(startp, stackblock() + workloc, len);
6341 startp[len++] = '\0';
6342 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6343 STADJUST(-amount, expdest);
6346 #endif /* ENABLE_ASH_BASH_COMPAT */
6348 subtype -= VSTRIMRIGHT;
6350 if (subtype < 0 || subtype > 7)
6353 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6354 zero = subtype >> 1;
6355 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6356 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6358 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6361 memmove(startp, loc, str - loc);
6362 loc = startp + (str - loc) - 1;
6365 amount = loc - expdest;
6366 STADJUST(amount, expdest);
6372 * Add the value of a specialized variable to the stack string.
6373 * name parameter (examples):
6374 * ash -c 'echo $1' name:'1='
6375 * ash -c 'echo $qwe' name:'qwe='
6376 * ash -c 'echo $$' name:'$='
6377 * ash -c 'echo ${$}' name:'$='
6378 * ash -c 'echo ${$##q}' name:'$=q'
6379 * ash -c 'echo ${#$}' name:'$='
6380 * note: examples with bad shell syntax:
6381 * ash -c 'echo ${#$1}' name:'$=1'
6382 * ash -c 'echo ${#1#}' name:'1=#'
6384 static NOINLINE ssize_t
6385 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6395 int quoted = varflags & VSQUOTE;
6396 int subtype = varflags & VSTYPE;
6397 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6399 if (quoted && (flags & EXP_FULL))
6400 sep = 1 << CHAR_BIT;
6402 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6411 num = shellparam.nparam;
6419 goto check_1char_name;
6421 expdest = makestrspace(NOPTS, expdest);
6422 for (i = NOPTS - 1; i >= 0; i--) {
6424 USTPUTC(optletters(i), expdest);
6430 /* handles cases similar to ${#$1} */
6431 if (name[2] != '\0')
6432 raise_error_syntax("bad substitution");
6440 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6441 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6447 while ((p = *ap++) != NULL) {
6450 partlen = strlen(p);
6453 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6454 memtodest(p, partlen, syntax, quotes);
6460 if (subtype == VSPLUS || subtype == VSLENGTH) {
6481 num = atoi(name); /* number(name) fails on ${N#str} etc */
6482 if (num < 0 || num > shellparam.nparam)
6484 p = num ? shellparam.p[num - 1] : arg0;
6487 /* NB: name has form "VAR=..." */
6489 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6490 * which should be considered before we check variables. */
6492 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6496 str = var_str_list->text;
6497 eq = strchr(str, '=');
6498 if (!eq) /* stop at first non-assignment */
6501 if (name_len == (unsigned)(eq - str)
6502 && strncmp(str, name, name_len) == 0) {
6504 /* goto value; - WRONG! */
6505 /* think "A=1 A=2 B=$A" */
6507 var_str_list = var_str_list->next;
6508 } while (var_str_list);
6512 p = lookupvar(name);
6518 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6519 memtodest(p, len, syntax, quotes);
6523 if (subtype == VSPLUS || subtype == VSLENGTH)
6524 STADJUST(-len, expdest);
6529 * Expand a variable, and return a pointer to the next character in the
6533 evalvar(char *p, int flags, struct strlist *var_str_list)
6544 varflags = (unsigned char) *p++;
6545 subtype = varflags & VSTYPE;
6546 quoted = varflags & VSQUOTE;
6548 easy = (!quoted || (*var == '@' && shellparam.nparam));
6549 startloc = expdest - (char *)stackblock();
6550 p = strchr(p, '=') + 1;
6553 varlen = varvalue(var, varflags, flags, var_str_list);
6554 if (varflags & VSNUL)
6557 if (subtype == VSPLUS) {
6558 varlen = -1 - varlen;
6562 if (subtype == VSMINUS) {
6566 p, flags | EXP_TILDE |
6567 (quoted ? EXP_QWORD : EXP_WORD),
6577 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6579 if (subevalvar(p, var, /* strloc: */ 0,
6580 subtype, startloc, varflags,
6586 * Remove any recorded regions beyond
6589 removerecordregions(startloc);
6599 if (varlen < 0 && uflag)
6600 varunset(p, var, 0, 0);
6602 if (subtype == VSLENGTH) {
6603 cvtnum(varlen > 0 ? varlen : 0);
6607 if (subtype == VSNORMAL) {
6618 case VSTRIMRIGHTMAX:
6619 #if ENABLE_ASH_BASH_COMPAT
6632 * Terminate the string and start recording the pattern
6635 STPUTC('\0', expdest);
6636 patloc = expdest - (char *)stackblock();
6637 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6639 //TODO: | EXP_REDIR too? All other such places do it too
6640 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6643 int amount = expdest - (
6644 (char *)stackblock() + patloc - 1
6646 STADJUST(-amount, expdest);
6648 /* Remove any recorded regions beyond start of variable */
6649 removerecordregions(startloc);
6651 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6655 if (subtype != VSNORMAL) { /* skip to end of alternative */
6661 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6663 argbackq = argbackq->next;
6664 } else if (c == CTLVAR) {
6665 if ((*p++ & VSTYPE) != VSNORMAL)
6667 } else if (c == CTLENDVAR) {
6677 * Break the argument string into pieces based upon IFS and add the
6678 * strings to the argument list. The regions of the string to be
6679 * searched for IFS characters have been stored by recordregion.
6682 ifsbreakup(char *string, struct arglist *arglist)
6684 struct ifsregion *ifsp;
6689 const char *ifs, *realifs;
6694 if (ifslastp != NULL) {
6697 realifs = ifsset() ? ifsval() : defifs;
6700 p = string + ifsp->begoff;
6701 nulonly = ifsp->nulonly;
6702 ifs = nulonly ? nullstr : realifs;
6704 while (p < string + ifsp->endoff) {
6708 if (!strchr(ifs, *p)) {
6713 ifsspc = (strchr(defifs, *p) != NULL);
6714 /* Ignore IFS whitespace at start */
6715 if (q == start && ifsspc) {
6721 sp = stzalloc(sizeof(*sp));
6723 *arglist->lastp = sp;
6724 arglist->lastp = &sp->next;
6728 if (p >= string + ifsp->endoff) {
6734 if (strchr(ifs, *p) == NULL) {
6738 if (strchr(defifs, *p) == NULL) {
6753 } while (ifsp != NULL);
6762 sp = stzalloc(sizeof(*sp));
6764 *arglist->lastp = sp;
6765 arglist->lastp = &sp->next;
6771 struct ifsregion *p;
6776 struct ifsregion *ifsp;
6782 ifsfirst.next = NULL;
6787 * Add a file name to the list.
6790 addfname(const char *name)
6794 sp = stzalloc(sizeof(*sp));
6795 sp->text = ststrdup(name);
6797 exparg.lastp = &sp->next;
6800 static char *expdir;
6803 * Do metacharacter (i.e. *, ?, [...]) expansion.
6806 expmeta(char *enddir, char *name)
6821 for (p = name; *p; p++) {
6822 if (*p == '*' || *p == '?')
6824 else if (*p == '[') {
6831 if (*q == '/' || *q == '\0')
6838 } else if (*p == '\\')
6840 else if (*p == '/') {
6847 if (metaflag == 0) { /* we've reached the end of the file name */
6848 if (enddir != expdir)
6856 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6867 } while (p < start);
6869 if (enddir == expdir) {
6871 } else if (enddir == expdir + 1 && *expdir == '/') {
6880 if (enddir != expdir)
6882 if (*endname == 0) {
6894 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6895 if (dp->d_name[0] == '.' && !matchdot)
6897 if (pmatch(start, dp->d_name)) {
6899 strcpy(enddir, dp->d_name);
6902 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6905 expmeta(p, endname);
6914 static struct strlist *
6915 msort(struct strlist *list, int len)
6917 struct strlist *p, *q = NULL;
6918 struct strlist **lpp;
6926 for (n = half; --n >= 0;) {
6930 q->next = NULL; /* terminate first half of list */
6931 q = msort(list, half); /* sort first half of list */
6932 p = msort(p, len - half); /* sort second half */
6935 #if ENABLE_LOCALE_SUPPORT
6936 if (strcoll(p->text, q->text) < 0)
6938 if (strcmp(p->text, q->text) < 0)
6962 * Sort the results of file name expansion. It calculates the number of
6963 * strings to sort and then calls msort (short for merge sort) to do the
6966 static struct strlist *
6967 expsort(struct strlist *str)
6973 for (sp = str; sp; sp = sp->next)
6975 return msort(str, len);
6979 expandmeta(struct strlist *str /*, int flag*/)
6981 static const char metachars[] ALIGN1 = {
6984 /* TODO - EXP_REDIR */
6987 struct strlist **savelastp;
6993 if (!strpbrk(str->text, metachars))
6995 savelastp = exparg.lastp;
6998 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7000 int i = strlen(str->text);
7001 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7009 if (exparg.lastp == savelastp) {
7014 *exparg.lastp = str;
7015 rmescapes(str->text, 0);
7016 exparg.lastp = &str->next;
7018 *exparg.lastp = NULL;
7019 *savelastp = sp = expsort(*savelastp);
7020 while (sp->next != NULL)
7022 exparg.lastp = &sp->next;
7029 * Perform variable substitution and command substitution on an argument,
7030 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7031 * perform splitting and file name expansion. When arglist is NULL, perform
7032 * here document expansion.
7035 expandarg(union node *arg, struct arglist *arglist, int flag)
7040 argbackq = arg->narg.backquote;
7041 STARTSTACKSTR(expdest);
7042 ifsfirst.next = NULL;
7044 argstr(arg->narg.text, flag,
7045 /* var_str_list: */ arglist ? arglist->list : NULL);
7046 p = _STPUTC('\0', expdest);
7048 if (arglist == NULL) {
7049 return; /* here document expanded */
7051 p = grabstackstr(p);
7052 exparg.lastp = &exparg.list;
7056 if (flag & EXP_FULL) {
7057 ifsbreakup(p, &exparg);
7058 *exparg.lastp = NULL;
7059 exparg.lastp = &exparg.list;
7060 expandmeta(exparg.list /*, flag*/);
7062 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7064 sp = stzalloc(sizeof(*sp));
7067 exparg.lastp = &sp->next;
7071 *exparg.lastp = NULL;
7073 *arglist->lastp = exparg.list;
7074 arglist->lastp = exparg.lastp;
7079 * Expand shell variables and backquotes inside a here document.
7082 expandhere(union node *arg, int fd)
7085 expandarg(arg, (struct arglist *)NULL, 0);
7086 full_write(fd, stackblock(), expdest - (char *)stackblock());
7090 * Returns true if the pattern matches the string.
7093 patmatch(char *pattern, const char *string)
7095 return pmatch(preglob(pattern, 0, 0), string);
7099 * See if a pattern matches in a case statement.
7102 casematch(union node *pattern, char *val)
7104 struct stackmark smark;
7107 setstackmark(&smark);
7108 argbackq = pattern->narg.backquote;
7109 STARTSTACKSTR(expdest);
7111 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7112 /* var_str_list: */ NULL);
7113 STACKSTRNUL(expdest);
7114 result = patmatch(stackblock(), val);
7115 popstackmark(&smark);
7120 /* ============ find_command */
7124 int (*builtin)(int, char **) FAST_FUNC;
7125 /* unsigned flags; */
7127 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7128 /* "regular" builtins always take precedence over commands,
7129 * regardless of PATH=....%builtin... position */
7130 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7131 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7134 smallint cmdtype; /* CMDxxx */
7137 /* index >= 0 for commands without path (slashes) */
7138 /* (TODO: what exactly does the value mean? PATH position?) */
7139 /* index == -1 for commands with slashes */
7140 /* index == (-2 - applet_no) for NOFORK applets */
7141 const struct builtincmd *cmd;
7142 struct funcnode *func;
7145 /* values of cmdtype */
7146 #define CMDUNKNOWN -1 /* no entry in table for command */
7147 #define CMDNORMAL 0 /* command is an executable program */
7148 #define CMDFUNCTION 1 /* command is a shell function */
7149 #define CMDBUILTIN 2 /* command is a shell builtin */
7151 /* action to find_command() */
7152 #define DO_ERR 0x01 /* prints errors */
7153 #define DO_ABS 0x02 /* checks absolute paths */
7154 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7155 #define DO_ALTPATH 0x08 /* using alternate path */
7156 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7158 static void find_command(char *, struct cmdentry *, int, const char *);
7161 /* ============ Hashing commands */
7164 * When commands are first encountered, they are entered in a hash table.
7165 * This ensures that a full path search will not have to be done for them
7166 * on each invocation.
7168 * We should investigate converting to a linear search, even though that
7169 * would make the command name "hash" a misnomer.
7173 struct tblentry *next; /* next entry in hash chain */
7174 union param param; /* definition of builtin function */
7175 smallint cmdtype; /* CMDxxx */
7176 char rehash; /* if set, cd done since entry created */
7177 char cmdname[1]; /* name of command */
7180 static struct tblentry **cmdtable;
7181 #define INIT_G_cmdtable() do { \
7182 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7185 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7189 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7193 #if ENABLE_FEATURE_SH_STANDALONE
7194 if (applet_no >= 0) {
7195 if (APPLET_IS_NOEXEC(applet_no)) {
7198 run_applet_no_and_exit(applet_no, argv);
7200 /* re-exec ourselves with the new arguments */
7201 execve(bb_busybox_exec_path, argv, envp);
7202 /* If they called chroot or otherwise made the binary no longer
7203 * executable, fall through */
7210 execve(cmd, argv, envp);
7211 } while (errno == EINTR);
7213 execve(cmd, argv, envp);
7219 if (errno == ENOEXEC) {
7223 for (ap = argv; *ap; ap++)
7225 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7227 ap[0] = cmd = (char *)DEFAULT_SHELL;
7230 while ((*ap++ = *argv++) != NULL)
7239 * Exec a program. Never returns. If you change this routine, you may
7240 * have to change the find_command routine as well.
7242 static void shellexec(char **, const char *, int) NORETURN;
7244 shellexec(char **argv, const char *path, int idx)
7250 #if ENABLE_FEATURE_SH_STANDALONE
7254 clearredir(/*drop:*/ 1);
7255 envp = listvars(VEXPORT, VUNSET, 0);
7256 if (strchr(argv[0], '/') != NULL
7257 #if ENABLE_FEATURE_SH_STANDALONE
7258 || (applet_no = find_applet_by_name(argv[0])) >= 0
7261 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7265 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7266 if (--idx < 0 && pathopt == NULL) {
7267 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7268 if (errno != ENOENT && errno != ENOTDIR)
7275 /* Map to POSIX errors */
7287 exitstatus = exerrno;
7288 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7289 argv[0], e, suppress_int));
7290 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7295 printentry(struct tblentry *cmdp)
7301 idx = cmdp->param.index;
7304 name = path_advance(&path, cmdp->cmdname);
7306 } while (--idx >= 0);
7307 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7311 * Clear out command entries. The argument specifies the first entry in
7312 * PATH which has changed.
7315 clearcmdentry(int firstchange)
7317 struct tblentry **tblp;
7318 struct tblentry **pp;
7319 struct tblentry *cmdp;
7322 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7324 while ((cmdp = *pp) != NULL) {
7325 if ((cmdp->cmdtype == CMDNORMAL &&
7326 cmdp->param.index >= firstchange)
7327 || (cmdp->cmdtype == CMDBUILTIN &&
7328 builtinloc >= firstchange)
7341 * Locate a command in the command hash table. If "add" is nonzero,
7342 * add the command to the table if it is not already present. The
7343 * variable "lastcmdentry" is set to point to the address of the link
7344 * pointing to the entry, so that delete_cmd_entry can delete the
7347 * Interrupts must be off if called with add != 0.
7349 static struct tblentry **lastcmdentry;
7351 static struct tblentry *
7352 cmdlookup(const char *name, int add)
7354 unsigned int hashval;
7356 struct tblentry *cmdp;
7357 struct tblentry **pp;
7360 hashval = (unsigned char)*p << 4;
7362 hashval += (unsigned char)*p++;
7364 pp = &cmdtable[hashval % CMDTABLESIZE];
7365 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7366 if (strcmp(cmdp->cmdname, name) == 0)
7370 if (add && cmdp == NULL) {
7371 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7373 /* + 1 - already done because
7374 * tblentry::cmdname is char[1] */);
7375 /*cmdp->next = NULL; - ckzalloc did it */
7376 cmdp->cmdtype = CMDUNKNOWN;
7377 strcpy(cmdp->cmdname, name);
7384 * Delete the command entry returned on the last lookup.
7387 delete_cmd_entry(void)
7389 struct tblentry *cmdp;
7392 cmdp = *lastcmdentry;
7393 *lastcmdentry = cmdp->next;
7394 if (cmdp->cmdtype == CMDFUNCTION)
7395 freefunc(cmdp->param.func);
7401 * Add a new command entry, replacing any existing command entry for
7402 * the same name - except special builtins.
7405 addcmdentry(char *name, struct cmdentry *entry)
7407 struct tblentry *cmdp;
7409 cmdp = cmdlookup(name, 1);
7410 if (cmdp->cmdtype == CMDFUNCTION) {
7411 freefunc(cmdp->param.func);
7413 cmdp->cmdtype = entry->cmdtype;
7414 cmdp->param = entry->u;
7418 static int FAST_FUNC
7419 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7421 struct tblentry **pp;
7422 struct tblentry *cmdp;
7424 struct cmdentry entry;
7427 if (nextopt("r") != '\0') {
7432 if (*argptr == NULL) {
7433 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7434 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7435 if (cmdp->cmdtype == CMDNORMAL)
7443 while ((name = *argptr) != NULL) {
7444 cmdp = cmdlookup(name, 0);
7446 && (cmdp->cmdtype == CMDNORMAL
7447 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7451 find_command(name, &entry, DO_ERR, pathval());
7452 if (entry.cmdtype == CMDUNKNOWN)
7460 * Called when a cd is done. Marks all commands so the next time they
7461 * are executed they will be rehashed.
7466 struct tblentry **pp;
7467 struct tblentry *cmdp;
7469 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7470 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7471 if (cmdp->cmdtype == CMDNORMAL
7472 || (cmdp->cmdtype == CMDBUILTIN
7473 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7483 * Fix command hash table when PATH changed.
7484 * Called before PATH is changed. The argument is the new value of PATH;
7485 * pathval() still returns the old value at this point.
7486 * Called with interrupts off.
7488 static void FAST_FUNC
7489 changepath(const char *new)
7497 firstchange = 9999; /* assume no change */
7503 if ((*old == '\0' && *new == ':')
7504 || (*old == ':' && *new == '\0'))
7506 old = new; /* ignore subsequent differences */
7510 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7516 if (builtinloc < 0 && idx_bltin >= 0)
7517 builtinloc = idx_bltin; /* zap builtins */
7518 if (builtinloc >= 0 && idx_bltin < 0)
7520 clearcmdentry(firstchange);
7521 builtinloc = idx_bltin;
7536 #define TENDBQUOTE 12
7553 typedef smallint token_id_t;
7555 /* first char is indicating which tokens mark the end of a list */
7556 static const char *const tokname_array[] = {
7570 #define KWDOFFSET 13
7571 /* the following are keywords */
7593 static char buf[16];
7596 //if (tok < TSEMI) return tokname_array[tok] + 1;
7597 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7602 sprintf(buf + (tok >= TSEMI), "%s%c",
7603 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7607 /* Wrapper around strcmp for qsort/bsearch/... */
7609 pstrcmp(const void *a, const void *b)
7611 return strcmp((char*) a, (*(char**) b) + 1);
7614 static const char *const *
7615 findkwd(const char *s)
7617 return bsearch(s, tokname_array + KWDOFFSET,
7618 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7619 sizeof(tokname_array[0]), pstrcmp);
7623 * Locate and print what a word is...
7626 describe_command(char *command, int describe_command_verbose)
7628 struct cmdentry entry;
7629 struct tblentry *cmdp;
7630 #if ENABLE_ASH_ALIAS
7631 const struct alias *ap;
7633 const char *path = pathval();
7635 if (describe_command_verbose) {
7639 /* First look at the keywords */
7640 if (findkwd(command)) {
7641 out1str(describe_command_verbose ? " is a shell keyword" : command);
7645 #if ENABLE_ASH_ALIAS
7646 /* Then look at the aliases */
7647 ap = lookupalias(command, 0);
7649 if (!describe_command_verbose) {
7654 out1fmt(" is an alias for %s", ap->val);
7658 /* Then check if it is a tracked alias */
7659 cmdp = cmdlookup(command, 0);
7661 entry.cmdtype = cmdp->cmdtype;
7662 entry.u = cmdp->param;
7664 /* Finally use brute force */
7665 find_command(command, &entry, DO_ABS, path);
7668 switch (entry.cmdtype) {
7670 int j = entry.u.index;
7676 p = path_advance(&path, command);
7680 if (describe_command_verbose) {
7682 (cmdp ? " a tracked alias for" : nullstr), p
7691 if (describe_command_verbose) {
7692 out1str(" is a shell function");
7699 if (describe_command_verbose) {
7700 out1fmt(" is a %sshell builtin",
7701 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7702 "special " : nullstr
7710 if (describe_command_verbose) {
7711 out1str(": not found\n");
7716 outstr("\n", stdout);
7720 static int FAST_FUNC
7721 typecmd(int argc UNUSED_PARAM, char **argv)
7727 /* type -p ... ? (we don't bother checking for 'p') */
7728 if (argv[1] && argv[1][0] == '-') {
7733 err |= describe_command(argv[i++], verbose);
7738 #if ENABLE_ASH_CMDCMD
7739 static int FAST_FUNC
7740 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7748 while ((c = nextopt("pvV")) != '\0')
7750 verify |= VERIFY_VERBOSE;
7752 verify |= VERIFY_BRIEF;
7757 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7758 if (verify && (*argptr != NULL)) {
7759 return describe_command(*argptr, verify - VERIFY_BRIEF);
7767 /* ============ eval.c */
7769 static int funcblocksize; /* size of structures in function */
7770 static int funcstringsize; /* size of strings in node */
7771 static void *funcblock; /* block to allocate function from */
7772 static char *funcstring; /* block to allocate strings from */
7774 /* flags in argument to evaltree */
7775 #define EV_EXIT 01 /* exit after evaluating tree */
7776 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7777 #define EV_BACKCMD 04 /* command executing within back quotes */
7779 static const uint8_t nodesize[N_NUMBER] = {
7780 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7781 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7782 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7783 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7784 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7785 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7786 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7787 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7788 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7789 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7790 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7791 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7792 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7793 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7794 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7795 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7796 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7797 #if ENABLE_ASH_BASH_COMPAT
7798 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7800 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7801 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7802 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7803 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7804 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7805 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7806 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7807 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7808 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7811 static void calcsize(union node *n);
7814 sizenodelist(struct nodelist *lp)
7817 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7824 calcsize(union node *n)
7828 funcblocksize += nodesize[n->type];
7831 calcsize(n->ncmd.redirect);
7832 calcsize(n->ncmd.args);
7833 calcsize(n->ncmd.assign);
7836 sizenodelist(n->npipe.cmdlist);
7841 calcsize(n->nredir.redirect);
7842 calcsize(n->nredir.n);
7849 calcsize(n->nbinary.ch2);
7850 calcsize(n->nbinary.ch1);
7853 calcsize(n->nif.elsepart);
7854 calcsize(n->nif.ifpart);
7855 calcsize(n->nif.test);
7858 funcstringsize += strlen(n->nfor.var) + 1;
7859 calcsize(n->nfor.body);
7860 calcsize(n->nfor.args);
7863 calcsize(n->ncase.cases);
7864 calcsize(n->ncase.expr);
7867 calcsize(n->nclist.body);
7868 calcsize(n->nclist.pattern);
7869 calcsize(n->nclist.next);
7873 sizenodelist(n->narg.backquote);
7874 funcstringsize += strlen(n->narg.text) + 1;
7875 calcsize(n->narg.next);
7878 #if ENABLE_ASH_BASH_COMPAT
7885 calcsize(n->nfile.fname);
7886 calcsize(n->nfile.next);
7890 calcsize(n->ndup.vname);
7891 calcsize(n->ndup.next);
7895 calcsize(n->nhere.doc);
7896 calcsize(n->nhere.next);
7899 calcsize(n->nnot.com);
7905 nodeckstrdup(char *s)
7907 char *rtn = funcstring;
7909 strcpy(funcstring, s);
7910 funcstring += strlen(s) + 1;
7914 static union node *copynode(union node *);
7916 static struct nodelist *
7917 copynodelist(struct nodelist *lp)
7919 struct nodelist *start;
7920 struct nodelist **lpp;
7925 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7926 (*lpp)->n = copynode(lp->n);
7928 lpp = &(*lpp)->next;
7935 copynode(union node *n)
7942 funcblock = (char *) funcblock + nodesize[n->type];
7946 new->ncmd.redirect = copynode(n->ncmd.redirect);
7947 new->ncmd.args = copynode(n->ncmd.args);
7948 new->ncmd.assign = copynode(n->ncmd.assign);
7951 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7952 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7957 new->nredir.redirect = copynode(n->nredir.redirect);
7958 new->nredir.n = copynode(n->nredir.n);
7965 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7966 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7969 new->nif.elsepart = copynode(n->nif.elsepart);
7970 new->nif.ifpart = copynode(n->nif.ifpart);
7971 new->nif.test = copynode(n->nif.test);
7974 new->nfor.var = nodeckstrdup(n->nfor.var);
7975 new->nfor.body = copynode(n->nfor.body);
7976 new->nfor.args = copynode(n->nfor.args);
7979 new->ncase.cases = copynode(n->ncase.cases);
7980 new->ncase.expr = copynode(n->ncase.expr);
7983 new->nclist.body = copynode(n->nclist.body);
7984 new->nclist.pattern = copynode(n->nclist.pattern);
7985 new->nclist.next = copynode(n->nclist.next);
7989 new->narg.backquote = copynodelist(n->narg.backquote);
7990 new->narg.text = nodeckstrdup(n->narg.text);
7991 new->narg.next = copynode(n->narg.next);
7994 #if ENABLE_ASH_BASH_COMPAT
8001 new->nfile.fname = copynode(n->nfile.fname);
8002 new->nfile.fd = n->nfile.fd;
8003 new->nfile.next = copynode(n->nfile.next);
8007 new->ndup.vname = copynode(n->ndup.vname);
8008 new->ndup.dupfd = n->ndup.dupfd;
8009 new->ndup.fd = n->ndup.fd;
8010 new->ndup.next = copynode(n->ndup.next);
8014 new->nhere.doc = copynode(n->nhere.doc);
8015 new->nhere.fd = n->nhere.fd;
8016 new->nhere.next = copynode(n->nhere.next);
8019 new->nnot.com = copynode(n->nnot.com);
8022 new->type = n->type;
8027 * Make a copy of a parse tree.
8029 static struct funcnode *
8030 copyfunc(union node *n)
8035 funcblocksize = offsetof(struct funcnode, n);
8038 blocksize = funcblocksize;
8039 f = ckmalloc(blocksize + funcstringsize);
8040 funcblock = (char *) f + offsetof(struct funcnode, n);
8041 funcstring = (char *) f + blocksize;
8048 * Define a shell function.
8051 defun(char *name, union node *func)
8053 struct cmdentry entry;
8056 entry.cmdtype = CMDFUNCTION;
8057 entry.u.func = copyfunc(func);
8058 addcmdentry(name, &entry);
8062 /* Reasons for skipping commands (see comment on breakcmd routine) */
8063 #define SKIPBREAK (1 << 0)
8064 #define SKIPCONT (1 << 1)
8065 #define SKIPFUNC (1 << 2)
8066 #define SKIPFILE (1 << 3)
8067 #define SKIPEVAL (1 << 4)
8068 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8069 static int skipcount; /* number of levels to skip */
8070 static int funcnest; /* depth of function calls */
8071 static int loopnest; /* current loop nesting level */
8073 /* Forward decl way out to parsing code - dotrap needs it */
8074 static int evalstring(char *s, int mask);
8076 /* Called to execute a trap.
8077 * Single callsite - at the end of evaltree().
8078 * If we return non-zero, exaltree raises EXEXIT exception.
8080 * Perhaps we should avoid entering new trap handlers
8081 * while we are executing a trap handler. [is it a TODO?]
8090 savestatus = exitstatus;
8094 TRACE(("dotrap entered\n"));
8095 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8102 /* non-trapped SIGINT is handled separately by raise_interrupt,
8103 * don't upset it by resetting gotsig[SIGINT-1] */
8104 if (sig == SIGINT && !t)
8107 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8111 want_exexit = evalstring(t, SKIPEVAL);
8112 exitstatus = savestatus;
8114 TRACE(("dotrap returns %d\n", want_exexit));
8119 TRACE(("dotrap returns 0\n"));
8123 /* forward declarations - evaluation is fairly recursive business... */
8124 static void evalloop(union node *, int);
8125 static void evalfor(union node *, int);
8126 static void evalcase(union node *, int);
8127 static void evalsubshell(union node *, int);
8128 static void expredir(union node *);
8129 static void evalpipe(union node *, int);
8130 static void evalcommand(union node *, int);
8131 static int evalbltin(const struct builtincmd *, int, char **);
8132 static void prehash(union node *);
8135 * Evaluate a parse tree. The value is left in the global variable
8139 evaltree(union node *n, int flags)
8141 struct jmploc *volatile savehandler = exception_handler;
8142 struct jmploc jmploc;
8144 void (*evalfn)(union node *, int);
8148 SAVE_INT(int_level);
8151 TRACE(("evaltree(NULL) called\n"));
8154 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8156 exception_handler = &jmploc;
8158 int err = setjmp(jmploc.loc);
8160 /* if it was a signal, check for trap handlers */
8161 if (exception_type == EXSIG) {
8162 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8163 exception_type, err));
8166 /* continue on the way out */
8167 TRACE(("exception %d in evaltree, propagating err=%d\n",
8168 exception_type, err));
8169 exception_handler = savehandler;
8170 longjmp(exception_handler->loc, err);
8177 out1fmt("Node type = %d\n", n->type);
8182 evaltree(n->nnot.com, EV_TESTED);
8183 status = !exitstatus;
8186 expredir(n->nredir.redirect);
8187 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8189 evaltree(n->nredir.n, flags & EV_TESTED);
8190 status = exitstatus;
8192 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8195 evalfn = evalcommand;
8197 if (eflag && !(flags & EV_TESTED))
8209 evalfn = evalsubshell;
8222 #error NAND + 1 != NOR
8224 #if NOR + 1 != NSEMI
8225 #error NOR + 1 != NSEMI
8227 unsigned is_or = n->type - NAND;
8230 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8232 if (!exitstatus == is_or)
8245 evaltree(n->nif.test, EV_TESTED);
8248 if (exitstatus == 0) {
8252 if (n->nif.elsepart) {
8253 n = n->nif.elsepart;
8258 defun(n->narg.text, n->narg.next);
8262 exitstatus = status;
8267 exception_handler = savehandler;
8269 if (checkexit & exitstatus)
8270 evalskip |= SKIPEVAL;
8271 else if (pending_sig && dotrap())
8274 if (flags & EV_EXIT) {
8276 raise_exception(EXEXIT);
8279 RESTORE_INT(int_level);
8280 TRACE(("leaving evaltree (no interrupts)\n"));
8283 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8286 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8289 evalloop(union node *n, int flags)
8299 evaltree(n->nbinary.ch1, EV_TESTED);
8302 if (evalskip == SKIPCONT && --skipcount <= 0) {
8306 if (evalskip == SKIPBREAK && --skipcount <= 0)
8311 if (n->type != NWHILE)
8315 evaltree(n->nbinary.ch2, flags);
8316 status = exitstatus;
8321 exitstatus = status;
8325 evalfor(union node *n, int flags)
8327 struct arglist arglist;
8330 struct stackmark smark;
8332 setstackmark(&smark);
8333 arglist.list = NULL;
8334 arglist.lastp = &arglist.list;
8335 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8336 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8341 *arglist.lastp = NULL;
8346 for (sp = arglist.list; sp; sp = sp->next) {
8347 setvar(n->nfor.var, sp->text, 0);
8348 evaltree(n->nfor.body, flags);
8350 if (evalskip == SKIPCONT && --skipcount <= 0) {
8354 if (evalskip == SKIPBREAK && --skipcount <= 0)
8361 popstackmark(&smark);
8365 evalcase(union node *n, int flags)
8369 struct arglist arglist;
8370 struct stackmark smark;
8372 setstackmark(&smark);
8373 arglist.list = NULL;
8374 arglist.lastp = &arglist.list;
8375 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8377 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8378 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8379 if (casematch(patp, arglist.list->text)) {
8380 if (evalskip == 0) {
8381 evaltree(cp->nclist.body, flags);
8388 popstackmark(&smark);
8392 * Kick off a subshell to evaluate a tree.
8395 evalsubshell(union node *n, int flags)
8398 int backgnd = (n->type == NBACKGND);
8401 expredir(n->nredir.redirect);
8402 if (!backgnd && flags & EV_EXIT && !trap[0])
8405 jp = makejob(/*n,*/ 1);
8406 if (forkshell(jp, n, backgnd) == 0) {
8410 flags &=~ EV_TESTED;
8412 redirect(n->nredir.redirect, 0);
8413 evaltreenr(n->nredir.n, flags);
8418 status = waitforjob(jp);
8419 exitstatus = status;
8424 * Compute the names of the files in a redirection list.
8426 static void fixredir(union node *, const char *, int);
8428 expredir(union node *n)
8432 for (redir = n; redir; redir = redir->nfile.next) {
8436 fn.lastp = &fn.list;
8437 switch (redir->type) {
8441 #if ENABLE_ASH_BASH_COMPAT
8446 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8447 #if ENABLE_ASH_BASH_COMPAT
8450 redir->nfile.expfname = fn.list->text;
8453 case NTOFD: /* >& */
8454 if (redir->ndup.vname) {
8455 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8456 if (fn.list == NULL)
8457 ash_msg_and_raise_error("redir error");
8458 #if ENABLE_ASH_BASH_COMPAT
8459 //FIXME: we used expandarg with different args!
8460 if (!isdigit_str9(fn.list->text)) {
8461 /* >&file, not >&fd */
8462 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8463 ash_msg_and_raise_error("redir error");
8465 goto store_expfname;
8468 fixredir(redir, fn.list->text, 1);
8476 * Evaluate a pipeline. All the processes in the pipeline are children
8477 * of the process creating the pipeline. (This differs from some versions
8478 * of the shell, which make the last process in a pipeline the parent
8482 evalpipe(union node *n, int flags)
8485 struct nodelist *lp;
8490 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8492 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8496 jp = makejob(/*n,*/ pipelen);
8498 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8502 if (pipe(pip) < 0) {
8504 ash_msg_and_raise_error("pipe call failed");
8507 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8520 evaltreenr(lp->n, flags);
8526 /* Don't want to trigger debugging */
8530 if (n->npipe.pipe_backgnd == 0) {
8531 exitstatus = waitforjob(jp);
8532 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8538 * Controls whether the shell is interactive or not.
8541 setinteractive(int on)
8543 static smallint is_interactive;
8545 if (++on == is_interactive)
8547 is_interactive = on;
8551 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8552 if (is_interactive > 1) {
8553 /* Looks like they want an interactive shell */
8554 static smallint did_banner;
8557 /* note: ash and hush share this string */
8558 out1fmt("\n\n%s %s\n"
8559 "Enter 'help' for a list of built-in commands."
8562 "built-in shell (ash)"
8576 setinteractive(iflag);
8578 #if ENABLE_FEATURE_EDITING_VI
8580 line_input_state->flags |= VI_MODE;
8582 line_input_state->flags &= ~VI_MODE;
8584 viflag = 0; /* forcibly keep the option off */
8588 static struct localvar *localvars;
8591 * Called after a function returns.
8592 * Interrupts must be off.
8597 struct localvar *lvp;
8600 while ((lvp = localvars) != NULL) {
8601 localvars = lvp->next;
8603 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8604 if (vp == NULL) { /* $- saved */
8605 memcpy(optlist, lvp->text, sizeof(optlist));
8606 free((char*)lvp->text);
8608 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8612 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8613 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8614 free((char*)vp->text);
8615 vp->flags = lvp->flags;
8616 vp->text = lvp->text;
8623 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8625 volatile struct shparam saveparam;
8626 struct localvar *volatile savelocalvars;
8627 struct jmploc *volatile savehandler;
8628 struct jmploc jmploc;
8631 saveparam = shellparam;
8632 savelocalvars = localvars;
8633 e = setjmp(jmploc.loc);
8638 savehandler = exception_handler;
8639 exception_handler = &jmploc;
8641 shellparam.malloced = 0;
8645 shellparam.nparam = argc - 1;
8646 shellparam.p = argv + 1;
8647 #if ENABLE_ASH_GETOPTS
8648 shellparam.optind = 1;
8649 shellparam.optoff = -1;
8651 evaltree(&func->n, flags & EV_TESTED);
8657 localvars = savelocalvars;
8658 freeparam(&shellparam);
8659 shellparam = saveparam;
8660 exception_handler = savehandler;
8662 evalskip &= ~SKIPFUNC;
8666 #if ENABLE_ASH_CMDCMD
8668 parse_command_args(char **argv, const char **path)
8681 if (c == '-' && !*cp) {
8688 *path = bb_default_path;
8691 /* run 'typecmd' for other options */
8702 * Make a variable a local variable. When a variable is made local, it's
8703 * value and flags are saved in a localvar structure. The saved values
8704 * will be restored when the shell function returns. We handle the name
8705 * "-" as a special case.
8710 struct localvar *lvp;
8715 lvp = ckzalloc(sizeof(struct localvar));
8716 if (LONE_DASH(name)) {
8718 p = ckmalloc(sizeof(optlist));
8719 lvp->text = memcpy(p, optlist, sizeof(optlist));
8724 vpp = hashvar(name);
8725 vp = *findvar(vpp, name);
8726 eq = strchr(name, '=');
8729 setvareq(name, VSTRFIXED);
8731 setvar(name, NULL, VSTRFIXED);
8732 vp = *vpp; /* the new variable */
8733 lvp->flags = VUNSET;
8735 lvp->text = vp->text;
8736 lvp->flags = vp->flags;
8737 vp->flags |= VSTRFIXED|VTEXTFIXED;
8743 lvp->next = localvars;
8749 * The "local" command.
8751 static int FAST_FUNC
8752 localcmd(int argc UNUSED_PARAM, char **argv)
8757 while ((name = *argv++) != NULL) {
8763 static int FAST_FUNC
8764 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8769 static int FAST_FUNC
8770 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8775 static int FAST_FUNC
8776 execcmd(int argc UNUSED_PARAM, char **argv)
8779 iflag = 0; /* exit on error */
8782 shellexec(argv + 1, pathval(), 0);
8788 * The return command.
8790 static int FAST_FUNC
8791 returncmd(int argc UNUSED_PARAM, char **argv)
8794 * If called outside a function, do what ksh does;
8795 * skip the rest of the file.
8797 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8798 return argv[1] ? number(argv[1]) : exitstatus;
8801 /* Forward declarations for builtintab[] */
8802 static int breakcmd(int, char **) FAST_FUNC;
8803 static int dotcmd(int, char **) FAST_FUNC;
8804 static int evalcmd(int, char **) FAST_FUNC;
8805 static int exitcmd(int, char **) FAST_FUNC;
8806 static int exportcmd(int, char **) FAST_FUNC;
8807 #if ENABLE_ASH_GETOPTS
8808 static int getoptscmd(int, char **) FAST_FUNC;
8810 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8811 static int helpcmd(int, char **) FAST_FUNC;
8813 #if ENABLE_SH_MATH_SUPPORT
8814 static int letcmd(int, char **) FAST_FUNC;
8816 static int readcmd(int, char **) FAST_FUNC;
8817 static int setcmd(int, char **) FAST_FUNC;
8818 static int shiftcmd(int, char **) FAST_FUNC;
8819 static int timescmd(int, char **) FAST_FUNC;
8820 static int trapcmd(int, char **) FAST_FUNC;
8821 static int umaskcmd(int, char **) FAST_FUNC;
8822 static int unsetcmd(int, char **) FAST_FUNC;
8823 static int ulimitcmd(int, char **) FAST_FUNC;
8825 #define BUILTIN_NOSPEC "0"
8826 #define BUILTIN_SPECIAL "1"
8827 #define BUILTIN_REGULAR "2"
8828 #define BUILTIN_SPEC_REG "3"
8829 #define BUILTIN_ASSIGN "4"
8830 #define BUILTIN_SPEC_ASSG "5"
8831 #define BUILTIN_REG_ASSG "6"
8832 #define BUILTIN_SPEC_REG_ASSG "7"
8834 /* Stubs for calling non-FAST_FUNC's */
8835 #if ENABLE_ASH_BUILTIN_ECHO
8836 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8838 #if ENABLE_ASH_BUILTIN_PRINTF
8839 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8841 #if ENABLE_ASH_BUILTIN_TEST
8842 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8845 /* Keep these in proper order since it is searched via bsearch() */
8846 static const struct builtincmd builtintab[] = {
8847 { BUILTIN_SPEC_REG ".", dotcmd },
8848 { BUILTIN_SPEC_REG ":", truecmd },
8849 #if ENABLE_ASH_BUILTIN_TEST
8850 { BUILTIN_REGULAR "[", testcmd },
8851 #if ENABLE_ASH_BASH_COMPAT
8852 { BUILTIN_REGULAR "[[", testcmd },
8855 #if ENABLE_ASH_ALIAS
8856 { BUILTIN_REG_ASSG "alias", aliascmd },
8859 { BUILTIN_REGULAR "bg", fg_bgcmd },
8861 { BUILTIN_SPEC_REG "break", breakcmd },
8862 { BUILTIN_REGULAR "cd", cdcmd },
8863 { BUILTIN_NOSPEC "chdir", cdcmd },
8864 #if ENABLE_ASH_CMDCMD
8865 { BUILTIN_REGULAR "command", commandcmd },
8867 { BUILTIN_SPEC_REG "continue", breakcmd },
8868 #if ENABLE_ASH_BUILTIN_ECHO
8869 { BUILTIN_REGULAR "echo", echocmd },
8871 { BUILTIN_SPEC_REG "eval", evalcmd },
8872 { BUILTIN_SPEC_REG "exec", execcmd },
8873 { BUILTIN_SPEC_REG "exit", exitcmd },
8874 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8875 { BUILTIN_REGULAR "false", falsecmd },
8877 { BUILTIN_REGULAR "fg", fg_bgcmd },
8879 #if ENABLE_ASH_GETOPTS
8880 { BUILTIN_REGULAR "getopts", getoptscmd },
8882 { BUILTIN_NOSPEC "hash", hashcmd },
8883 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8884 { BUILTIN_NOSPEC "help", helpcmd },
8887 { BUILTIN_REGULAR "jobs", jobscmd },
8888 { BUILTIN_REGULAR "kill", killcmd },
8890 #if ENABLE_SH_MATH_SUPPORT
8891 { BUILTIN_NOSPEC "let", letcmd },
8893 { BUILTIN_ASSIGN "local", localcmd },
8894 #if ENABLE_ASH_BUILTIN_PRINTF
8895 { BUILTIN_REGULAR "printf", printfcmd },
8897 { BUILTIN_NOSPEC "pwd", pwdcmd },
8898 { BUILTIN_REGULAR "read", readcmd },
8899 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8900 { BUILTIN_SPEC_REG "return", returncmd },
8901 { BUILTIN_SPEC_REG "set", setcmd },
8902 { BUILTIN_SPEC_REG "shift", shiftcmd },
8903 { BUILTIN_SPEC_REG "source", dotcmd },
8904 #if ENABLE_ASH_BUILTIN_TEST
8905 { BUILTIN_REGULAR "test", testcmd },
8907 { BUILTIN_SPEC_REG "times", timescmd },
8908 { BUILTIN_SPEC_REG "trap", trapcmd },
8909 { BUILTIN_REGULAR "true", truecmd },
8910 { BUILTIN_NOSPEC "type", typecmd },
8911 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8912 { BUILTIN_REGULAR "umask", umaskcmd },
8913 #if ENABLE_ASH_ALIAS
8914 { BUILTIN_REGULAR "unalias", unaliascmd },
8916 { BUILTIN_SPEC_REG "unset", unsetcmd },
8917 { BUILTIN_REGULAR "wait", waitcmd },
8920 /* Should match the above table! */
8921 #define COMMANDCMD (builtintab + \
8923 1 * ENABLE_ASH_BUILTIN_TEST + \
8924 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8925 1 * ENABLE_ASH_ALIAS + \
8926 1 * ENABLE_ASH_JOB_CONTROL + \
8928 #define EXECCMD (builtintab + \
8930 1 * ENABLE_ASH_BUILTIN_TEST + \
8931 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8932 1 * ENABLE_ASH_ALIAS + \
8933 1 * ENABLE_ASH_JOB_CONTROL + \
8935 1 * ENABLE_ASH_CMDCMD + \
8937 ENABLE_ASH_BUILTIN_ECHO + \
8941 * Search the table of builtin commands.
8943 static struct builtincmd *
8944 find_builtin(const char *name)
8946 struct builtincmd *bp;
8949 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8956 * Execute a simple command.
8959 isassignment(const char *p)
8961 const char *q = endofname(p);
8966 static int FAST_FUNC
8967 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8969 /* Preserve exitstatus of a previous possible redirection
8970 * as POSIX mandates */
8971 return back_exitstatus;
8974 evalcommand(union node *cmd, int flags)
8976 static const struct builtincmd null_bltin = {
8977 "\0\0", bltincmd /* why three NULs? */
8979 struct stackmark smark;
8981 struct arglist arglist;
8982 struct arglist varlist;
8985 const struct strlist *sp;
8986 struct cmdentry cmdentry;
8993 struct builtincmd *bcmd;
8994 smallint cmd_is_exec;
8995 smallint pseudovarflag = 0;
8997 /* First expand the arguments. */
8998 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8999 setstackmark(&smark);
9000 back_exitstatus = 0;
9002 cmdentry.cmdtype = CMDBUILTIN;
9003 cmdentry.u.cmd = &null_bltin;
9004 varlist.lastp = &varlist.list;
9005 *varlist.lastp = NULL;
9006 arglist.lastp = &arglist.list;
9007 *arglist.lastp = NULL;
9010 if (cmd->ncmd.args) {
9011 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9012 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9015 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9016 struct strlist **spp;
9018 spp = arglist.lastp;
9019 if (pseudovarflag && isassignment(argp->narg.text))
9020 expandarg(argp, &arglist, EXP_VARTILDE);
9022 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9024 for (sp = *spp; sp; sp = sp->next)
9028 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9029 for (sp = arglist.list; sp; sp = sp->next) {
9030 TRACE(("evalcommand arg: %s\n", sp->text));
9031 *nargv++ = sp->text;
9036 if (iflag && funcnest == 0 && argc > 0)
9037 lastarg = nargv[-1];
9040 expredir(cmd->ncmd.redirect);
9041 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9044 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9045 struct strlist **spp;
9048 spp = varlist.lastp;
9049 expandarg(argp, &varlist, EXP_VARTILDE);
9052 * Modify the command lookup path, if a PATH= assignment
9056 if (varequal(p, path))
9060 /* Print the command if xflag is set. */
9063 const char *p = " %s";
9066 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9069 for (n = 0; n < 2; n++) {
9071 fdprintf(preverrout_fd, p, sp->text);
9079 safe_write(preverrout_fd, "\n", 1);
9085 /* Now locate the command. */
9087 const char *oldpath;
9088 int cmd_flag = DO_ERR;
9093 find_command(argv[0], &cmdentry, cmd_flag, path);
9094 if (cmdentry.cmdtype == CMDUNKNOWN) {
9095 flush_stdout_stderr();
9100 /* implement bltin and command here */
9101 if (cmdentry.cmdtype != CMDBUILTIN)
9104 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9105 if (cmdentry.u.cmd == EXECCMD)
9107 #if ENABLE_ASH_CMDCMD
9108 if (cmdentry.u.cmd == COMMANDCMD) {
9110 nargv = parse_command_args(argv, &path);
9113 argc -= nargv - argv;
9115 cmd_flag |= DO_NOFUNC;
9123 /* We have a redirection error. */
9125 raise_exception(EXERROR);
9127 exitstatus = status;
9131 /* Execute the command. */
9132 switch (cmdentry.cmdtype) {
9135 #if ENABLE_FEATURE_SH_NOFORK
9136 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9137 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9139 /* find_command() encodes applet_no as (-2 - applet_no) */
9140 int applet_no = (- cmdentry.u.index - 2);
9141 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9142 listsetvar(varlist.list, VEXPORT|VSTACK);
9143 /* run <applet>_main() */
9144 exitstatus = run_nofork_applet(applet_no, argv);
9149 /* Fork off a child process if necessary. */
9150 if (!(flags & EV_EXIT) || trap[0]) {
9152 jp = makejob(/*cmd,*/ 1);
9153 if (forkshell(jp, cmd, FORK_FG) != 0) {
9154 exitstatus = waitforjob(jp);
9156 TRACE(("forked child exited with %d\n", exitstatus));
9161 listsetvar(varlist.list, VEXPORT|VSTACK);
9162 shellexec(argv, path, cmdentry.u.index);
9166 cmdenviron = varlist.list;
9168 struct strlist *list = cmdenviron;
9170 if (spclbltin > 0 || argc == 0) {
9172 if (cmd_is_exec && argc > 1)
9175 listsetvar(list, i);
9177 /* Tight loop with builtins only:
9178 * "while kill -0 $child; do true; done"
9179 * will never exit even if $child died, unless we do this
9180 * to reap the zombie and make kill detect that it's gone: */
9181 dowait(DOWAIT_NONBLOCK, NULL);
9183 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9185 int i = exception_type;
9190 exit_status = 128 + SIGINT;
9192 exit_status = 128 + pending_sig;
9193 exitstatus = exit_status;
9194 if (i == EXINT || spclbltin > 0) {
9196 longjmp(exception_handler->loc, 1);
9203 listsetvar(varlist.list, 0);
9204 /* See above for the rationale */
9205 dowait(DOWAIT_NONBLOCK, NULL);
9206 if (evalfun(cmdentry.u.func, argc, argv, flags))
9212 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9214 /* dsl: I think this is intended to be used to support
9215 * '_' in 'vi' command mode during line editing...
9216 * However I implemented that within libedit itself.
9218 setvar("_", lastarg, 0);
9220 popstackmark(&smark);
9224 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9226 char *volatile savecmdname;
9227 struct jmploc *volatile savehandler;
9228 struct jmploc jmploc;
9231 savecmdname = commandname;
9232 i = setjmp(jmploc.loc);
9235 savehandler = exception_handler;
9236 exception_handler = &jmploc;
9237 commandname = argv[0];
9239 optptr = NULL; /* initialize nextopt */
9240 exitstatus = (*cmd->builtin)(argc, argv);
9241 flush_stdout_stderr();
9243 exitstatus |= ferror(stdout);
9245 commandname = savecmdname;
9246 exception_handler = savehandler;
9252 goodname(const char *p)
9254 return !*endofname(p);
9259 * Search for a command. This is called before we fork so that the
9260 * location of the command will be available in the parent as well as
9261 * the child. The check for "goodname" is an overly conservative
9262 * check that the name will not be subject to expansion.
9265 prehash(union node *n)
9267 struct cmdentry entry;
9269 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9270 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9274 /* ============ Builtin commands
9276 * Builtin commands whose functions are closely tied to evaluation
9277 * are implemented here.
9281 * Handle break and continue commands. Break, continue, and return are
9282 * all handled by setting the evalskip flag. The evaluation routines
9283 * above all check this flag, and if it is set they start skipping
9284 * commands rather than executing them. The variable skipcount is
9285 * the number of loops to break/continue, or the number of function
9286 * levels to return. (The latter is always 1.) It should probably
9287 * be an error to break out of more loops than exist, but it isn't
9288 * in the standard shell so we don't make it one here.
9290 static int FAST_FUNC
9291 breakcmd(int argc UNUSED_PARAM, char **argv)
9293 int n = argv[1] ? number(argv[1]) : 1;
9296 ash_msg_and_raise_error(msg_illnum, argv[1]);
9300 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9307 /* ============ input.c
9309 * This implements the input routines used by the parser.
9313 INPUT_PUSH_FILE = 1,
9314 INPUT_NOFILE_OK = 2,
9317 static smallint checkkwd;
9318 /* values of checkkwd variable */
9319 #define CHKALIAS 0x1
9324 * Push a string back onto the input at this current parsefile level.
9325 * We handle aliases this way.
9327 #if !ENABLE_ASH_ALIAS
9328 #define pushstring(s, ap) pushstring(s)
9331 pushstring(char *s, struct alias *ap)
9338 if (g_parsefile->strpush) {
9339 sp = ckzalloc(sizeof(*sp));
9340 sp->prev = g_parsefile->strpush;
9342 sp = &(g_parsefile->basestrpush);
9344 g_parsefile->strpush = sp;
9345 sp->prev_string = g_parsefile->next_to_pgetc;
9346 sp->prev_left_in_line = g_parsefile->left_in_line;
9347 #if ENABLE_ASH_ALIAS
9350 ap->flag |= ALIASINUSE;
9354 g_parsefile->next_to_pgetc = s;
9355 g_parsefile->left_in_line = len;
9362 struct strpush *sp = g_parsefile->strpush;
9365 #if ENABLE_ASH_ALIAS
9367 if (g_parsefile->next_to_pgetc[-1] == ' '
9368 || g_parsefile->next_to_pgetc[-1] == '\t'
9370 checkkwd |= CHKALIAS;
9372 if (sp->string != sp->ap->val) {
9375 sp->ap->flag &= ~ALIASINUSE;
9376 if (sp->ap->flag & ALIASDEAD) {
9377 unalias(sp->ap->name);
9381 g_parsefile->next_to_pgetc = sp->prev_string;
9382 g_parsefile->left_in_line = sp->prev_left_in_line;
9383 g_parsefile->strpush = sp->prev;
9384 if (sp != &(g_parsefile->basestrpush))
9389 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9390 //it peeks whether it is &>, and then pushes back both chars.
9391 //This function needs to save last *next_to_pgetc to buf[0]
9392 //to make two pungetc() reliable. Currently,
9393 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9398 char *buf = g_parsefile->buf;
9400 g_parsefile->next_to_pgetc = buf;
9401 #if ENABLE_FEATURE_EDITING
9403 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9404 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9406 #if ENABLE_FEATURE_TAB_COMPLETION
9407 line_input_state->path_lookup = pathval();
9409 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9411 /* Ctrl+C pressed */
9420 if (nr < 0 && errno == 0) {
9421 /* Ctrl+D pressed */
9426 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9430 /* nonblock_safe_read() handles this problem */
9432 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9433 int flags = fcntl(0, F_GETFL);
9434 if (flags >= 0 && (flags & O_NONBLOCK)) {
9435 flags &= ~O_NONBLOCK;
9436 if (fcntl(0, F_SETFL, flags) >= 0) {
9437 out2str("sh: turning off NDELAY mode\n");
9448 * Refill the input buffer and return the next input character:
9450 * 1) If a string was pushed back on the input, pop it;
9451 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9452 * or we are reading from a string so we can't refill the buffer,
9454 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9455 * 4) Process input up to the next newline, deleting nul characters.
9457 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9458 #define pgetc_debug(...) ((void)0)
9460 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9461 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9462 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9463 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9471 while (g_parsefile->strpush) {
9472 #if ENABLE_ASH_ALIAS
9473 if (g_parsefile->left_in_line == -1
9474 && g_parsefile->strpush->ap
9475 && g_parsefile->next_to_pgetc[-1] != ' '
9476 && g_parsefile->next_to_pgetc[-1] != '\t'
9478 pgetc_debug("preadbuffer PEOA");
9483 /* try "pgetc" now: */
9484 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9485 g_parsefile->left_in_line,
9486 g_parsefile->next_to_pgetc,
9487 g_parsefile->next_to_pgetc);
9488 if (--g_parsefile->left_in_line >= 0)
9489 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9491 /* on both branches above g_parsefile->left_in_line < 0.
9492 * "pgetc" needs refilling.
9495 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9496 * pungetc() may increment it a few times.
9497 * Assuming it won't increment it to less than -90.
9499 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9500 pgetc_debug("preadbuffer PEOF1");
9501 /* even in failure keep left_in_line and next_to_pgetc
9502 * in lock step, for correct multi-layer pungetc.
9503 * left_in_line was decremented before preadbuffer(),
9504 * must inc next_to_pgetc: */
9505 g_parsefile->next_to_pgetc++;
9509 more = g_parsefile->left_in_buffer;
9511 flush_stdout_stderr();
9515 /* don't try reading again */
9516 g_parsefile->left_in_line = -99;
9517 pgetc_debug("preadbuffer PEOF2");
9518 g_parsefile->next_to_pgetc++;
9523 /* Find out where's the end of line.
9524 * Set g_parsefile->left_in_line
9525 * and g_parsefile->left_in_buffer acordingly.
9526 * NUL chars are deleted.
9528 q = g_parsefile->next_to_pgetc;
9536 memmove(q, q + 1, more);
9540 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9546 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9547 if (g_parsefile->left_in_line < 0)
9552 g_parsefile->left_in_buffer = more;
9557 out2str(g_parsefile->next_to_pgetc);
9561 pgetc_debug("preadbuffer at %d:%p'%s'",
9562 g_parsefile->left_in_line,
9563 g_parsefile->next_to_pgetc,
9564 g_parsefile->next_to_pgetc);
9565 return signed_char2int(*g_parsefile->next_to_pgetc++);
9568 #define pgetc_as_macro() \
9569 (--g_parsefile->left_in_line >= 0 \
9570 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9577 pgetc_debug("pgetc_fast at %d:%p'%s'",
9578 g_parsefile->left_in_line,
9579 g_parsefile->next_to_pgetc,
9580 g_parsefile->next_to_pgetc);
9581 return pgetc_as_macro();
9584 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9585 #define pgetc_fast() pgetc()
9587 #define pgetc_fast() pgetc_as_macro()
9591 * Same as pgetc(), but ignores PEOA.
9593 #if ENABLE_ASH_ALIAS
9599 pgetc_debug("pgetc_fast at %d:%p'%s'",
9600 g_parsefile->left_in_line,
9601 g_parsefile->next_to_pgetc,
9602 g_parsefile->next_to_pgetc);
9604 } while (c == PEOA);
9608 #define pgetc2() pgetc()
9612 * Read a line from the script.
9615 pfgets(char *line, int len)
9621 while (--nleft > 0) {
9637 * Undo the last call to pgetc. Only one character may be pushed back.
9638 * PEOF may be pushed back.
9643 g_parsefile->left_in_line++;
9644 g_parsefile->next_to_pgetc--;
9645 pgetc_debug("pushed back to %d:%p'%s'",
9646 g_parsefile->left_in_line,
9647 g_parsefile->next_to_pgetc,
9648 g_parsefile->next_to_pgetc);
9652 * To handle the "." command, a stack of input files is used. Pushfile
9653 * adds a new entry to the stack and popfile restores the previous level.
9658 struct parsefile *pf;
9660 pf = ckzalloc(sizeof(*pf));
9661 pf->prev = g_parsefile;
9663 /*pf->strpush = NULL; - ckzalloc did it */
9664 /*pf->basestrpush.prev = NULL;*/
9671 struct parsefile *pf = g_parsefile;
9679 g_parsefile = pf->prev;
9685 * Return to top level.
9690 while (g_parsefile != &basepf)
9695 * Close the file(s) that the shell is reading commands from. Called
9696 * after a fork is done.
9702 if (g_parsefile->fd > 0) {
9703 close(g_parsefile->fd);
9704 g_parsefile->fd = 0;
9709 * Like setinputfile, but takes an open file descriptor. Call this with
9713 setinputfd(int fd, int push)
9715 close_on_exec_on(fd);
9718 g_parsefile->buf = NULL;
9720 g_parsefile->fd = fd;
9721 if (g_parsefile->buf == NULL)
9722 g_parsefile->buf = ckmalloc(IBUFSIZ);
9723 g_parsefile->left_in_buffer = 0;
9724 g_parsefile->left_in_line = 0;
9725 g_parsefile->linno = 1;
9729 * Set the input to take input from a file. If push is set, push the
9730 * old input onto the stack first.
9733 setinputfile(const char *fname, int flags)
9739 fd = open(fname, O_RDONLY);
9741 if (flags & INPUT_NOFILE_OK)
9743 ash_msg_and_raise_error("can't open '%s'", fname);
9746 fd2 = copyfd(fd, 10);
9749 ash_msg_and_raise_error("out of file descriptors");
9752 setinputfd(fd, flags & INPUT_PUSH_FILE);
9759 * Like setinputfile, but takes input from a string.
9762 setinputstring(char *string)
9766 g_parsefile->next_to_pgetc = string;
9767 g_parsefile->left_in_line = strlen(string);
9768 g_parsefile->buf = NULL;
9769 g_parsefile->linno = 1;
9774 /* ============ mail.c
9776 * Routines to check for mail.
9781 #define MAXMBOXES 10
9783 /* times of mailboxes */
9784 static time_t mailtime[MAXMBOXES];
9785 /* Set if MAIL or MAILPATH is changed. */
9786 static smallint mail_var_path_changed;
9789 * Print appropriate message(s) if mail has arrived.
9790 * If mail_var_path_changed is set,
9791 * then the value of MAIL has mail_var_path_changed,
9792 * so we just update the values.
9801 struct stackmark smark;
9804 setstackmark(&smark);
9805 mpath = mpathset() ? mpathval() : mailval();
9806 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9807 p = path_advance(&mpath, nullstr);
9812 for (q = p; *q; q++)
9818 q[-1] = '\0'; /* delete trailing '/' */
9819 if (stat(p, &statb) < 0) {
9823 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9826 pathopt ? pathopt : "you have mail"
9829 *mtp = statb.st_mtime;
9831 mail_var_path_changed = 0;
9832 popstackmark(&smark);
9835 static void FAST_FUNC
9836 changemail(const char *val UNUSED_PARAM)
9838 mail_var_path_changed = 1;
9841 #endif /* ASH_MAIL */
9844 /* ============ ??? */
9847 * Set the shell parameters.
9850 setparam(char **argv)
9856 for (nparam = 0; argv[nparam]; nparam++)
9858 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9860 *ap++ = ckstrdup(*argv++);
9863 freeparam(&shellparam);
9864 shellparam.malloced = 1;
9865 shellparam.nparam = nparam;
9866 shellparam.p = newparam;
9867 #if ENABLE_ASH_GETOPTS
9868 shellparam.optind = 1;
9869 shellparam.optoff = -1;
9874 * Process shell options. The global variable argptr contains a pointer
9875 * to the argument list; we advance it past the options.
9877 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9878 * For a non-interactive shell, an error condition encountered
9879 * by a special built-in ... shall cause the shell to write a diagnostic message
9880 * to standard error and exit as shown in the following table:
9881 * Error Special Built-In
9883 * Utility syntax error (option or operand error) Shall exit
9885 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9886 * we see that bash does not do that (set "finishes" with error code 1 instead,
9887 * and shell continues), and people rely on this behavior!
9889 * set -o barfoo 2>/dev/null
9892 * Oh well. Let's mimic that.
9895 plus_minus_o(char *name, int val)
9900 for (i = 0; i < NOPTS; i++) {
9901 if (strcmp(name, optnames(i)) == 0) {
9906 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9909 for (i = 0; i < NOPTS; i++) {
9911 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9913 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9919 setoption(int flag, int val)
9923 for (i = 0; i < NOPTS; i++) {
9924 if (optletters(i) == flag) {
9929 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9933 options(int cmdline)
9941 while ((p = *argptr) != NULL) {
9943 if (c != '-' && c != '+')
9946 val = 0; /* val = 0 if c == '+' */
9949 if (p[0] == '\0' || LONE_DASH(p)) {
9951 /* "-" means turn off -x and -v */
9954 /* "--" means reset params */
9955 else if (*argptr == NULL)
9958 break; /* "-" or "--" terminates options */
9961 /* first char was + or - */
9962 while ((c = *p++) != '\0') {
9963 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9964 if (c == 'c' && cmdline) {
9965 minusc = p; /* command is after shell args */
9966 } else if (c == 'o') {
9967 if (plus_minus_o(*argptr, val)) {
9968 /* it already printed err message */
9969 return 1; /* error */
9973 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9975 /* bash does not accept +-login, we also won't */
9976 } else if (cmdline && val && (c == '-')) { /* long options */
9977 if (strcmp(p, "login") == 0)
9989 * The shift builtin command.
9991 static int FAST_FUNC
9992 shiftcmd(int argc UNUSED_PARAM, char **argv)
9999 n = number(argv[1]);
10000 if (n > shellparam.nparam)
10001 n = 0; /* bash compat, was = shellparam.nparam; */
10003 shellparam.nparam -= n;
10004 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10005 if (shellparam.malloced)
10008 ap2 = shellparam.p;
10009 while ((*ap2++ = *ap1++) != NULL)
10011 #if ENABLE_ASH_GETOPTS
10012 shellparam.optind = 1;
10013 shellparam.optoff = -1;
10020 * POSIX requires that 'set' (but not export or readonly) output the
10021 * variables in lexicographic order - by the locale's collating order (sigh).
10022 * Maybe we could keep them in an ordered balanced binary tree
10023 * instead of hashed lists.
10024 * For now just roll 'em through qsort for printing...
10027 showvars(const char *sep_prefix, int on, int off)
10030 char **ep, **epend;
10032 ep = listvars(on, off, &epend);
10033 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10035 sep = *sep_prefix ? " " : sep_prefix;
10037 for (; ep < epend; ep++) {
10041 p = strchrnul(*ep, '=');
10044 q = single_quote(++p);
10045 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10051 * The set command builtin.
10053 static int FAST_FUNC
10054 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10059 return showvars(nullstr, 0, VUNSET);
10062 if (!options(0)) { /* if no parse error... */
10065 if (*argptr != NULL) {
10073 #if ENABLE_ASH_RANDOM_SUPPORT
10074 static void FAST_FUNC
10075 change_random(const char *value)
10079 if (value == NULL) {
10080 /* "get", generate */
10081 t = next_random(&random_gen);
10082 /* set without recursion */
10083 setvar(vrandom.text, utoa(t), VNOFUNC);
10084 vrandom.flags &= ~VNOFUNC;
10087 t = strtoul(value, NULL, 10);
10088 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10093 #if ENABLE_ASH_GETOPTS
10095 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10104 if (*param_optind < 1)
10106 optnext = optfirst + *param_optind - 1;
10108 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10111 p = optnext[-1] + *optoff;
10112 if (p == NULL || *p == '\0') {
10113 /* Current word is done, advance */
10115 if (p == NULL || *p != '-' || *++p == '\0') {
10122 if (LONE_DASH(p)) /* check for "--" */
10127 for (q = optstr; *q != c;) {
10129 if (optstr[0] == ':') {
10132 err |= setvarsafe("OPTARG", s, 0);
10134 fprintf(stderr, "Illegal option -%c\n", c);
10135 unsetvar("OPTARG");
10145 if (*p == '\0' && (p = *optnext) == NULL) {
10146 if (optstr[0] == ':') {
10149 err |= setvarsafe("OPTARG", s, 0);
10152 fprintf(stderr, "No arg for -%c option\n", c);
10153 unsetvar("OPTARG");
10161 err |= setvarsafe("OPTARG", p, 0);
10164 err |= setvarsafe("OPTARG", nullstr, 0);
10166 *optoff = p ? p - *(optnext - 1) : -1;
10167 *param_optind = optnext - optfirst + 1;
10168 fmtstr(s, sizeof(s), "%d", *param_optind);
10169 err |= setvarsafe("OPTIND", s, VNOFUNC);
10172 err |= setvarsafe(optvar, s, 0);
10176 flush_stdout_stderr();
10177 raise_exception(EXERROR);
10183 * The getopts builtin. Shellparam.optnext points to the next argument
10184 * to be processed. Shellparam.optptr points to the next character to
10185 * be processed in the current argument. If shellparam.optnext is NULL,
10186 * then it's the first time getopts has been called.
10188 static int FAST_FUNC
10189 getoptscmd(int argc, char **argv)
10194 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10196 optbase = shellparam.p;
10197 if (shellparam.optind > shellparam.nparam + 1) {
10198 shellparam.optind = 1;
10199 shellparam.optoff = -1;
10202 optbase = &argv[3];
10203 if (shellparam.optind > argc - 2) {
10204 shellparam.optind = 1;
10205 shellparam.optoff = -1;
10209 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10210 &shellparam.optoff);
10212 #endif /* ASH_GETOPTS */
10215 /* ============ Shell parser */
10218 struct heredoc *next; /* next here document in list */
10219 union node *here; /* redirection node */
10220 char *eofmark; /* string indicating end of input */
10221 smallint striptabs; /* if set, strip leading tabs */
10224 static smallint tokpushback; /* last token pushed back */
10225 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10226 static smallint quoteflag; /* set if (part of) last token was quoted */
10227 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10228 static struct heredoc *heredoclist; /* list of here documents to read */
10229 static char *wordtext; /* text of last word returned by readtoken */
10230 static struct nodelist *backquotelist;
10231 static union node *redirnode;
10232 static struct heredoc *heredoc;
10235 * Called when an unexpected token is read during the parse. The argument
10236 * is the token that is expected, or -1 if more than one type of token can
10237 * occur at this point.
10239 static void raise_error_unexpected_syntax(int) NORETURN;
10241 raise_error_unexpected_syntax(int token)
10246 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10248 sprintf(msg + l, " (expecting %s)", tokname(token));
10249 raise_error_syntax(msg);
10253 #define EOFMARKLEN 79
10255 /* parsing is heavily cross-recursive, need these forward decls */
10256 static union node *andor(void);
10257 static union node *pipeline(void);
10258 static union node *parse_command(void);
10259 static void parseheredoc(void);
10260 static char peektoken(void);
10261 static int readtoken(void);
10263 static union node *
10266 union node *n1, *n2, *n3;
10269 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10270 if (nlflag == 2 && peektoken())
10276 if (tok == TBACKGND) {
10277 if (n2->type == NPIPE) {
10278 n2->npipe.pipe_backgnd = 1;
10280 if (n2->type != NREDIR) {
10281 n3 = stzalloc(sizeof(struct nredir));
10283 /*n3->nredir.redirect = NULL; - stzalloc did it */
10286 n2->type = NBACKGND;
10292 n3 = stzalloc(sizeof(struct nbinary));
10294 n3->nbinary.ch1 = n1;
10295 n3->nbinary.ch2 = n2;
10311 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10319 pungetc(); /* push back EOF on input */
10323 raise_error_unexpected_syntax(-1);
10330 static union node *
10333 union node *n1, *n2, *n3;
10341 } else if (t == TOR) {
10347 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10349 n3 = stzalloc(sizeof(struct nbinary));
10351 n3->nbinary.ch1 = n1;
10352 n3->nbinary.ch2 = n2;
10357 static union node *
10360 union node *n1, *n2, *pipenode;
10361 struct nodelist *lp, *prev;
10365 TRACE(("pipeline: entered\n"));
10366 if (readtoken() == TNOT) {
10368 checkkwd = CHKKWD | CHKALIAS;
10371 n1 = parse_command();
10372 if (readtoken() == TPIPE) {
10373 pipenode = stzalloc(sizeof(struct npipe));
10374 pipenode->type = NPIPE;
10375 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10376 lp = stzalloc(sizeof(struct nodelist));
10377 pipenode->npipe.cmdlist = lp;
10381 lp = stzalloc(sizeof(struct nodelist));
10382 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10383 lp->n = parse_command();
10385 } while (readtoken() == TPIPE);
10391 n2 = stzalloc(sizeof(struct nnot));
10399 static union node *
10404 n = stzalloc(sizeof(struct narg));
10406 /*n->narg.next = NULL; - stzalloc did it */
10407 n->narg.text = wordtext;
10408 n->narg.backquote = backquotelist;
10413 fixredir(union node *n, const char *text, int err)
10417 TRACE(("Fix redir %s %d\n", text, err));
10419 n->ndup.vname = NULL;
10421 fd = bb_strtou(text, NULL, 10);
10422 if (!errno && fd >= 0)
10423 n->ndup.dupfd = fd;
10424 else if (LONE_DASH(text))
10425 n->ndup.dupfd = -1;
10428 raise_error_syntax("bad fd number");
10429 n->ndup.vname = makename();
10434 * Returns true if the text contains nothing to expand (no dollar signs
10438 noexpand(const char *text)
10444 while ((c = *p++) != '\0') {
10445 if (c == CTLQUOTEMARK)
10449 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10458 union node *n = redirnode;
10460 if (readtoken() != TWORD)
10461 raise_error_unexpected_syntax(-1);
10462 if (n->type == NHERE) {
10463 struct heredoc *here = heredoc;
10467 if (quoteflag == 0)
10469 TRACE(("Here document %d\n", n->type));
10470 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10471 raise_error_syntax("illegal eof marker for << redirection");
10472 rmescapes(wordtext, 0);
10473 here->eofmark = wordtext;
10475 if (heredoclist == NULL)
10476 heredoclist = here;
10478 for (p = heredoclist; p->next; p = p->next)
10482 } else if (n->type == NTOFD || n->type == NFROMFD) {
10483 fixredir(n, wordtext, 0);
10485 n->nfile.fname = makename();
10489 static union node *
10492 union node *args, **app;
10493 union node *n = NULL;
10494 union node *vars, **vpp;
10495 union node **rpp, *redir;
10497 #if ENABLE_ASH_BASH_COMPAT
10498 smallint double_brackets_flag = 0;
10508 savecheckkwd = CHKALIAS;
10511 checkkwd = savecheckkwd;
10514 #if ENABLE_ASH_BASH_COMPAT
10515 case TAND: /* "&&" */
10516 case TOR: /* "||" */
10517 if (!double_brackets_flag) {
10521 wordtext = (char *) (t == TAND ? "-a" : "-o");
10524 n = stzalloc(sizeof(struct narg));
10526 /*n->narg.next = NULL; - stzalloc did it */
10527 n->narg.text = wordtext;
10528 #if ENABLE_ASH_BASH_COMPAT
10529 if (strcmp("[[", wordtext) == 0)
10530 double_brackets_flag = 1;
10531 else if (strcmp("]]", wordtext) == 0)
10532 double_brackets_flag = 0;
10534 n->narg.backquote = backquotelist;
10535 if (savecheckkwd && isassignment(wordtext)) {
10537 vpp = &n->narg.next;
10540 app = &n->narg.next;
10545 *rpp = n = redirnode;
10546 rpp = &n->nfile.next;
10547 parsefname(); /* read name of redirection file */
10550 if (args && app == &args->narg.next
10553 struct builtincmd *bcmd;
10556 /* We have a function */
10557 if (readtoken() != TRP)
10558 raise_error_unexpected_syntax(TRP);
10559 name = n->narg.text;
10560 if (!goodname(name)
10561 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10563 raise_error_syntax("bad function name");
10566 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10567 n->narg.next = parse_command();
10580 n = stzalloc(sizeof(struct ncmd));
10582 n->ncmd.args = args;
10583 n->ncmd.assign = vars;
10584 n->ncmd.redirect = redir;
10588 static union node *
10589 parse_command(void)
10591 union node *n1, *n2;
10592 union node *ap, **app;
10593 union node *cp, **cpp;
10594 union node *redir, **rpp;
10601 switch (readtoken()) {
10603 raise_error_unexpected_syntax(-1);
10606 n1 = stzalloc(sizeof(struct nif));
10608 n1->nif.test = list(0);
10609 if (readtoken() != TTHEN)
10610 raise_error_unexpected_syntax(TTHEN);
10611 n1->nif.ifpart = list(0);
10613 while (readtoken() == TELIF) {
10614 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10615 n2 = n2->nif.elsepart;
10617 n2->nif.test = list(0);
10618 if (readtoken() != TTHEN)
10619 raise_error_unexpected_syntax(TTHEN);
10620 n2->nif.ifpart = list(0);
10622 if (lasttoken == TELSE)
10623 n2->nif.elsepart = list(0);
10625 n2->nif.elsepart = NULL;
10633 n1 = stzalloc(sizeof(struct nbinary));
10634 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10635 n1->nbinary.ch1 = list(0);
10638 TRACE(("expecting DO got %s %s\n", tokname(got),
10639 got == TWORD ? wordtext : ""));
10640 raise_error_unexpected_syntax(TDO);
10642 n1->nbinary.ch2 = list(0);
10647 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10648 raise_error_syntax("bad for loop variable");
10649 n1 = stzalloc(sizeof(struct nfor));
10651 n1->nfor.var = wordtext;
10652 checkkwd = CHKKWD | CHKALIAS;
10653 if (readtoken() == TIN) {
10655 while (readtoken() == TWORD) {
10656 n2 = stzalloc(sizeof(struct narg));
10658 /*n2->narg.next = NULL; - stzalloc did it */
10659 n2->narg.text = wordtext;
10660 n2->narg.backquote = backquotelist;
10662 app = &n2->narg.next;
10665 n1->nfor.args = ap;
10666 if (lasttoken != TNL && lasttoken != TSEMI)
10667 raise_error_unexpected_syntax(-1);
10669 n2 = stzalloc(sizeof(struct narg));
10671 /*n2->narg.next = NULL; - stzalloc did it */
10672 n2->narg.text = (char *)dolatstr;
10673 /*n2->narg.backquote = NULL;*/
10674 n1->nfor.args = n2;
10676 * Newline or semicolon here is optional (but note
10677 * that the original Bourne shell only allowed NL).
10679 if (lasttoken != TNL && lasttoken != TSEMI)
10682 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10683 if (readtoken() != TDO)
10684 raise_error_unexpected_syntax(TDO);
10685 n1->nfor.body = list(0);
10689 n1 = stzalloc(sizeof(struct ncase));
10691 if (readtoken() != TWORD)
10692 raise_error_unexpected_syntax(TWORD);
10693 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10695 /*n2->narg.next = NULL; - stzalloc did it */
10696 n2->narg.text = wordtext;
10697 n2->narg.backquote = backquotelist;
10699 checkkwd = CHKKWD | CHKALIAS;
10700 } while (readtoken() == TNL);
10701 if (lasttoken != TIN)
10702 raise_error_unexpected_syntax(TIN);
10703 cpp = &n1->ncase.cases;
10705 checkkwd = CHKNL | CHKKWD;
10707 while (t != TESAC) {
10708 if (lasttoken == TLP)
10710 *cpp = cp = stzalloc(sizeof(struct nclist));
10712 app = &cp->nclist.pattern;
10714 *app = ap = stzalloc(sizeof(struct narg));
10716 /*ap->narg.next = NULL; - stzalloc did it */
10717 ap->narg.text = wordtext;
10718 ap->narg.backquote = backquotelist;
10719 if (readtoken() != TPIPE)
10721 app = &ap->narg.next;
10724 //ap->narg.next = NULL;
10725 if (lasttoken != TRP)
10726 raise_error_unexpected_syntax(TRP);
10727 cp->nclist.body = list(2);
10729 cpp = &cp->nclist.next;
10731 checkkwd = CHKNL | CHKKWD;
10735 raise_error_unexpected_syntax(TENDCASE);
10742 n1 = stzalloc(sizeof(struct nredir));
10743 n1->type = NSUBSHELL;
10744 n1->nredir.n = list(0);
10745 /*n1->nredir.redirect = NULL; - stzalloc did it */
10755 return simplecmd();
10758 if (readtoken() != t)
10759 raise_error_unexpected_syntax(t);
10762 /* Now check for redirection which may follow command */
10763 checkkwd = CHKKWD | CHKALIAS;
10765 while (readtoken() == TREDIR) {
10766 *rpp = n2 = redirnode;
10767 rpp = &n2->nfile.next;
10773 if (n1->type != NSUBSHELL) {
10774 n2 = stzalloc(sizeof(struct nredir));
10779 n1->nredir.redirect = redir;
10784 #if ENABLE_ASH_BASH_COMPAT
10785 static int decode_dollar_squote(void)
10787 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10793 p = strchr(C_escapes, c);
10798 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10802 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10804 } else if (c == 'x') { /* \xHH */
10808 } while (isxdigit(c) && --cnt);
10810 if (cnt == 3) { /* \x but next char is "bad" */
10814 } else { /* simple seq like \\ or \t */
10819 c = bb_process_escape_sequence((void*)&p);
10820 } else { /* unrecognized "\z": print both chars unless ' or " */
10821 if (c != '\'' && c != '"') {
10823 c |= 0x100; /* "please encode \, then me" */
10831 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10832 * is not NULL, read a here document. In the latter case, eofmark is the
10833 * word which marks the end of the document and striptabs is true if
10834 * leading tabs should be stripped from the document. The argument firstc
10835 * is the first character of the input token or document.
10837 * Because C does not have internal subroutines, I have simulated them
10838 * using goto's to implement the subroutine linkage. The following macros
10839 * will run code that appears at the end of readtoken1.
10841 #define CHECKEND() {goto checkend; checkend_return:;}
10842 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10843 #define PARSESUB() {goto parsesub; parsesub_return:;}
10844 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10845 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10846 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10848 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10850 /* NB: syntax parameter fits into smallint */
10854 char line[EOFMARKLEN + 1];
10855 struct nodelist *bqlist;
10859 smallint prevsyntax; /* syntax before arithmetic */
10860 #if ENABLE_ASH_EXPAND_PRMT
10861 smallint pssyntax; /* we are expanding a prompt string */
10863 int varnest; /* levels of variables expansion */
10864 int arinest; /* levels of arithmetic expansion */
10865 int parenlevel; /* levels of parens in arithmetic */
10866 int dqvarnest; /* levels of variables expansion within double quotes */
10868 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10871 /* Avoid longjmp clobbering */
10877 (void) &parenlevel;
10880 (void) &prevsyntax;
10883 startlinno = g_parsefile->linno;
10888 #if ENABLE_ASH_EXPAND_PRMT
10889 pssyntax = (syntax == PSSYNTAX);
10893 dblquote = (syntax == DQSYNTAX);
10899 STARTSTACKSTR(out);
10901 /* For each line, until end of word */
10903 CHECKEND(); /* set c to PEOF if at end of here document */
10904 for (;;) { /* until end of line or end of word */
10905 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10906 switch (SIT(c, syntax)) {
10907 case CNL: /* '\n' */
10908 if (syntax == BASESYNTAX)
10909 goto endword; /* exit outer loop */
10911 g_parsefile->linno++;
10915 goto loop; /* continue outer loop */
10920 if (eofmark == NULL || dblquote)
10921 USTPUTC(CTLESC, out);
10922 #if ENABLE_ASH_BASH_COMPAT
10923 if (c == '\\' && bash_dollar_squote) {
10924 c = decode_dollar_squote();
10926 USTPUTC('\\', out);
10927 c = (unsigned char)c;
10933 case CBACK: /* backslash */
10936 USTPUTC(CTLESC, out);
10937 USTPUTC('\\', out);
10939 } else if (c == '\n') {
10943 #if ENABLE_ASH_EXPAND_PRMT
10944 if (c == '$' && pssyntax) {
10945 USTPUTC(CTLESC, out);
10946 USTPUTC('\\', out);
10949 if (dblquote && c != '\\'
10950 && c != '`' && c != '$'
10951 && (c != '"' || eofmark != NULL)
10953 USTPUTC(CTLESC, out);
10954 USTPUTC('\\', out);
10956 if (SIT(c, SQSYNTAX) == CCTL)
10957 USTPUTC(CTLESC, out);
10965 if (eofmark == NULL) {
10966 USTPUTC(CTLQUOTEMARK, out);
10974 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10975 if (eofmark != NULL && arinest == 0
10980 if (dqvarnest == 0) {
10981 syntax = BASESYNTAX;
10988 case CVAR: /* '$' */
10989 PARSESUB(); /* parse substitution */
10991 case CENDVAR: /* '}' */
10994 if (dqvarnest > 0) {
10997 USTPUTC(CTLENDVAR, out);
11002 #if ENABLE_SH_MATH_SUPPORT
11003 case CLP: /* '(' in arithmetic */
11007 case CRP: /* ')' in arithmetic */
11008 if (parenlevel > 0) {
11012 if (pgetc() == ')') {
11013 if (--arinest == 0) {
11014 USTPUTC(CTLENDARI, out);
11015 syntax = prevsyntax;
11016 dblquote = (syntax == DQSYNTAX);
11021 * unbalanced parens
11022 * (don't 2nd guess - no error)
11030 case CBQUOTE: /* '`' */
11034 goto endword; /* exit outer loop */
11038 if (varnest == 0) {
11039 #if ENABLE_ASH_BASH_COMPAT
11041 if (pgetc() == '>')
11042 c = 0x100 + '>'; /* flag &> */
11046 goto endword; /* exit outer loop */
11048 #if ENABLE_ASH_ALIAS
11058 #if ENABLE_SH_MATH_SUPPORT
11059 if (syntax == ARISYNTAX)
11060 raise_error_syntax("missing '))'");
11062 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11063 raise_error_syntax("unterminated quoted string");
11064 if (varnest != 0) {
11065 startlinno = g_parsefile->linno;
11067 raise_error_syntax("missing '}'");
11069 USTPUTC('\0', out);
11070 len = out - (char *)stackblock();
11071 out = stackblock();
11072 if (eofmark == NULL) {
11073 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11076 if (isdigit_str9(out)) {
11077 PARSEREDIR(); /* passed as params: out, c */
11078 lasttoken = TREDIR;
11081 /* else: non-number X seen, interpret it
11082 * as "NNNX>file" = "NNNX >file" */
11086 quoteflag = quotef;
11087 backquotelist = bqlist;
11088 grabstackblock(len);
11092 /* end of readtoken routine */
11095 * Check to see whether we are at the end of the here document. When this
11096 * is called, c is set to the first character of the next input line. If
11097 * we are at the end of the here document, this routine sets the c to PEOF.
11101 #if ENABLE_ASH_ALIAS
11107 while (c == '\t') {
11111 if (c == *eofmark) {
11112 if (pfgets(line, sizeof(line)) != NULL) {
11116 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11118 if (*p == '\n' && *q == '\0') {
11120 g_parsefile->linno++;
11121 needprompt = doprompt;
11123 pushstring(line, NULL);
11128 goto checkend_return;
11132 * Parse a redirection operator. The variable "out" points to a string
11133 * specifying the fd to be redirected. The variable "c" contains the
11134 * first character of the redirection operator.
11137 /* out is already checked to be a valid number or "" */
11138 int fd = (*out == '\0' ? -1 : atoi(out));
11141 np = stzalloc(sizeof(struct nfile));
11146 np->type = NAPPEND;
11148 np->type = NCLOBBER;
11151 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11157 #if ENABLE_ASH_BASH_COMPAT
11158 else if (c == 0x100 + '>') { /* this flags &> redirection */
11160 pgetc(); /* this is '>', no need to check */
11164 else { /* c == '<' */
11165 /*np->nfile.fd = 0; - stzalloc did it */
11169 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11170 np = stzalloc(sizeof(struct nhere));
11171 /*np->nfile.fd = 0; - stzalloc did it */
11174 heredoc = stzalloc(sizeof(struct heredoc));
11175 heredoc->here = np;
11178 heredoc->striptabs = 1;
11180 /*heredoc->striptabs = 0; - stzalloc did it */
11186 np->type = NFROMFD;
11190 np->type = NFROMTO;
11202 goto parseredir_return;
11206 * Parse a substitution. At this point, we have read the dollar sign
11207 * and nothing else.
11210 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11211 * (assuming ascii char codes, as the original implementation did) */
11212 #define is_special(c) \
11213 (((unsigned)(c) - 33 < 32) \
11214 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11220 static const char types[] ALIGN1 = "}-+?=";
11223 if (c <= PEOA_OR_PEOF
11224 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11226 #if ENABLE_ASH_BASH_COMPAT
11228 bash_dollar_squote = 1;
11233 } else if (c == '(') { /* $(command) or $((arith)) */
11234 if (pgetc() == '(') {
11235 #if ENABLE_SH_MATH_SUPPORT
11238 raise_error_syntax("you disabled math support for $((arith)) syntax");
11245 USTPUTC(CTLVAR, out);
11246 typeloc = out - (char *)stackblock();
11247 USTPUTC(VSNORMAL, out);
11248 subtype = VSNORMAL;
11256 subtype = VSLENGTH;
11260 if (c > PEOA_OR_PEOF && is_name(c)) {
11264 } while (c > PEOA_OR_PEOF && is_in_name(c));
11265 } else if (isdigit(c)) {
11269 } while (isdigit(c));
11270 } else if (is_special(c)) {
11275 raise_error_syntax("bad substitution");
11277 if (c != '}' && subtype == VSLENGTH)
11282 if (subtype == 0) {
11286 #if ENABLE_ASH_BASH_COMPAT
11287 if (c == ':' || c == '$' || isdigit(c)) {
11289 subtype = VSSUBSTR;
11296 p = strchr(types, c);
11299 subtype = p - types + VSNORMAL;
11304 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11312 #if ENABLE_ASH_BASH_COMPAT
11314 subtype = VSREPLACE;
11317 subtype++; /* VSREPLACEALL */
11326 if (dblquote || arinest)
11328 *((char *)stackblock() + typeloc) = subtype | flags;
11329 if (subtype != VSNORMAL) {
11331 if (dblquote || arinest) {
11336 goto parsesub_return;
11340 * Called to parse command substitutions. Newstyle is set if the command
11341 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11342 * list of commands (passed by reference), and savelen is the number of
11343 * characters on the top of the stack which must be preserved.
11346 struct nodelist **nlpp;
11349 char *volatile str;
11350 struct jmploc jmploc;
11351 struct jmploc *volatile savehandler;
11353 smallint saveprompt = 0;
11356 (void) &saveprompt;
11358 savepbq = parsebackquote;
11359 if (setjmp(jmploc.loc)) {
11361 parsebackquote = 0;
11362 exception_handler = savehandler;
11363 longjmp(exception_handler->loc, 1);
11367 savelen = out - (char *)stackblock();
11369 str = ckmalloc(savelen);
11370 memcpy(str, stackblock(), savelen);
11372 savehandler = exception_handler;
11373 exception_handler = &jmploc;
11376 /* We must read until the closing backquote, giving special
11377 treatment to some slashes, and then push the string and
11378 reread it as input, interpreting it normally. */
11385 STARTSTACKSTR(pout);
11398 g_parsefile->linno++;
11402 * If eating a newline, avoid putting
11403 * the newline into the new character
11404 * stream (via the STPUTC after the
11409 if (pc != '\\' && pc != '`' && pc != '$'
11410 && (!dblquote || pc != '"'))
11411 STPUTC('\\', pout);
11412 if (pc > PEOA_OR_PEOF) {
11418 #if ENABLE_ASH_ALIAS
11421 startlinno = g_parsefile->linno;
11422 raise_error_syntax("EOF in backquote substitution");
11425 g_parsefile->linno++;
11426 needprompt = doprompt;
11435 STPUTC('\0', pout);
11436 psavelen = pout - (char *)stackblock();
11437 if (psavelen > 0) {
11438 pstr = grabstackstr(pout);
11439 setinputstring(pstr);
11444 nlpp = &(*nlpp)->next;
11445 *nlpp = stzalloc(sizeof(**nlpp));
11446 /* (*nlpp)->next = NULL; - stzalloc did it */
11447 parsebackquote = oldstyle;
11450 saveprompt = doprompt;
11457 doprompt = saveprompt;
11458 else if (readtoken() != TRP)
11459 raise_error_unexpected_syntax(TRP);
11464 * Start reading from old file again, ignoring any pushed back
11465 * tokens left from the backquote parsing
11470 while (stackblocksize() <= savelen)
11472 STARTSTACKSTR(out);
11474 memcpy(out, str, savelen);
11475 STADJUST(savelen, out);
11481 parsebackquote = savepbq;
11482 exception_handler = savehandler;
11483 if (arinest || dblquote)
11484 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11486 USTPUTC(CTLBACKQ, out);
11488 goto parsebackq_oldreturn;
11489 goto parsebackq_newreturn;
11492 #if ENABLE_SH_MATH_SUPPORT
11494 * Parse an arithmetic expansion (indicate start of one and set state)
11497 if (++arinest == 1) {
11498 prevsyntax = syntax;
11499 syntax = ARISYNTAX;
11500 USTPUTC(CTLARI, out);
11507 * we collapse embedded arithmetic expansion to
11508 * parenthesis, which should be equivalent
11512 goto parsearith_return;
11516 } /* end of readtoken */
11519 * Read the next input token.
11520 * If the token is a word, we set backquotelist to the list of cmds in
11521 * backquotes. We set quoteflag to true if any part of the word was
11523 * If the token is TREDIR, then we set redirnode to a structure containing
11525 * In all cases, the variable startlinno is set to the number of the line
11526 * on which the token starts.
11528 * [Change comment: here documents and internal procedures]
11529 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11530 * word parsing code into a separate routine. In this case, readtoken
11531 * doesn't need to have any internal procedures, but parseword does.
11532 * We could also make parseoperator in essence the main routine, and
11533 * have parseword (readtoken1?) handle both words and redirection.]
11535 #define NEW_xxreadtoken
11536 #ifdef NEW_xxreadtoken
11537 /* singles must be first! */
11538 static const char xxreadtoken_chars[7] ALIGN1 = {
11539 '\n', '(', ')', /* singles */
11540 '&', '|', ';', /* doubles */
11544 #define xxreadtoken_singles 3
11545 #define xxreadtoken_doubles 3
11547 static const char xxreadtoken_tokens[] ALIGN1 = {
11548 TNL, TLP, TRP, /* only single occurrence allowed */
11549 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11550 TEOF, /* corresponds to trailing nul */
11551 TAND, TOR, TENDCASE /* if double occurrence */
11566 startlinno = g_parsefile->linno;
11567 for (;;) { /* until token or start of word found */
11569 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11573 while ((c = pgetc()) != '\n' && c != PEOF)
11576 } else if (c == '\\') {
11577 if (pgetc() != '\n') {
11579 break; /* return readtoken1(...) */
11581 startlinno = ++g_parsefile->linno;
11587 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11590 g_parsefile->linno++;
11591 needprompt = doprompt;
11594 p = strchr(xxreadtoken_chars, c);
11596 break; /* return readtoken1(...) */
11598 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11600 if (cc == c) { /* double occurrence? */
11601 p += xxreadtoken_doubles + 1;
11604 #if ENABLE_ASH_BASH_COMPAT
11605 if (c == '&' && cc == '>') /* &> */
11606 break; /* return readtoken1(...) */
11611 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11616 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11618 #else /* old xxreadtoken */
11619 #define RETURN(token) return lasttoken = token
11632 startlinno = g_parsefile->linno;
11633 for (;;) { /* until token or start of word found */
11636 case ' ': case '\t':
11637 #if ENABLE_ASH_ALIAS
11642 while ((c = pgetc()) != '\n' && c != PEOF)
11647 if (pgetc() == '\n') {
11648 startlinno = ++g_parsefile->linno;
11656 g_parsefile->linno++;
11657 needprompt = doprompt;
11662 if (pgetc() == '&')
11667 if (pgetc() == '|')
11672 if (pgetc() == ';')
11685 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11688 #endif /* old xxreadtoken */
11695 smallint alreadyseen = tokpushback;
11698 #if ENABLE_ASH_ALIAS
11707 if (checkkwd & CHKNL) {
11714 if (t != TWORD || quoteflag) {
11719 * check for keywords
11721 if (checkkwd & CHKKWD) {
11722 const char *const *pp;
11724 pp = findkwd(wordtext);
11726 lasttoken = t = pp - tokname_array;
11727 TRACE(("keyword %s recognized\n", tokname(t)));
11732 if (checkkwd & CHKALIAS) {
11733 #if ENABLE_ASH_ALIAS
11735 ap = lookupalias(wordtext, 1);
11738 pushstring(ap->val, ap);
11748 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11750 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11762 return tokname_array[t][0];
11766 * Read and parse a command. Returns NODE_EOF on end of file.
11767 * (NULL is a valid parse tree indicating a blank line.)
11769 static union node *
11770 parsecmd(int interact)
11775 doprompt = interact;
11777 setprompt(doprompt);
11789 * Input any here documents.
11794 struct heredoc *here;
11797 here = heredoclist;
11798 heredoclist = NULL;
11804 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11805 here->eofmark, here->striptabs);
11806 n = stzalloc(sizeof(struct narg));
11807 n->narg.type = NARG;
11808 /*n->narg.next = NULL; - stzalloc did it */
11809 n->narg.text = wordtext;
11810 n->narg.backquote = backquotelist;
11811 here->here->nhere.doc = n;
11818 * called by editline -- any expansions to the prompt should be added here.
11820 #if ENABLE_ASH_EXPAND_PRMT
11821 static const char *
11822 expandstr(const char *ps)
11826 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11827 * and token processing _can_ alter it (delete NULs etc). */
11828 setinputstring((char *)ps);
11829 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11832 n.narg.type = NARG;
11833 n.narg.next = NULL;
11834 n.narg.text = wordtext;
11835 n.narg.backquote = backquotelist;
11837 expandarg(&n, NULL, 0);
11838 return stackblock();
11843 * Execute a command or commands contained in a string.
11846 evalstring(char *s, int mask)
11849 struct stackmark smark;
11853 setstackmark(&smark);
11856 while ((n = parsecmd(0)) != NODE_EOF) {
11858 popstackmark(&smark);
11871 * The eval command.
11873 static int FAST_FUNC
11874 evalcmd(int argc UNUSED_PARAM, char **argv)
11883 STARTSTACKSTR(concat);
11885 concat = stack_putstr(p, concat);
11889 STPUTC(' ', concat);
11891 STPUTC('\0', concat);
11892 p = grabstackstr(concat);
11894 evalstring(p, ~SKIPEVAL);
11901 * Read and execute commands. "Top" is nonzero for the top level command
11902 * loop; it turns on prompting if the shell is interactive.
11908 struct stackmark smark;
11912 TRACE(("cmdloop(%d) called\n", top));
11916 setstackmark(&smark);
11919 showjobs(stderr, SHOW_CHANGED);
11922 if (iflag && top) {
11924 #if ENABLE_ASH_MAIL
11928 n = parsecmd(inter);
11930 if (DEBUG > 2 && debug && (n != NODE_EOF))
11933 if (n == NODE_EOF) {
11934 if (!top || numeof >= 50)
11936 if (!stoppedjobs()) {
11939 out2str("\nUse \"exit\" to leave shell.\n");
11942 } else if (nflag == 0) {
11943 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11948 popstackmark(&smark);
11953 return skip & SKIPEVAL;
11960 * Take commands from a file. To be compatible we should do a path
11961 * search for the file, which is necessary to find sub-commands.
11964 find_dot_file(char *name)
11967 const char *path = pathval();
11970 /* don't try this for absolute or relative paths */
11971 if (strchr(name, '/'))
11974 /* IIRC standards do not say whether . is to be searched.
11975 * And it is even smaller this way, making it unconditional for now:
11977 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11982 while ((fullname = path_advance(&path, name)) != NULL) {
11984 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11986 * Don't bother freeing here, since it will
11987 * be freed by the caller.
11991 if (fullname != name)
11992 stunalloc(fullname);
11995 /* not found in the PATH */
11996 ash_msg_and_raise_error("%s: not found", name);
12000 static int FAST_FUNC
12001 dotcmd(int argc, char **argv)
12003 struct strlist *sp;
12004 volatile struct shparam saveparam;
12007 for (sp = cmdenviron; sp; sp = sp->next)
12008 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12010 if (argv[1]) { /* That's what SVR2 does */
12011 char *fullname = find_dot_file(argv[1]);
12014 if (argc) { /* argc > 0, argv[0] != NULL */
12015 saveparam = shellparam;
12016 shellparam.malloced = 0;
12017 shellparam.nparam = argc;
12018 shellparam.p = argv;
12021 setinputfile(fullname, INPUT_PUSH_FILE);
12022 commandname = fullname;
12027 freeparam(&shellparam);
12028 shellparam = saveparam;
12030 status = exitstatus;
12035 static int FAST_FUNC
12036 exitcmd(int argc UNUSED_PARAM, char **argv)
12041 exitstatus = number(argv[1]);
12042 raise_exception(EXEXIT);
12047 * Read a file containing shell functions.
12050 readcmdfile(char *name)
12052 setinputfile(name, INPUT_PUSH_FILE);
12058 /* ============ find_command inplementation */
12061 * Resolve a command name. If you change this routine, you may have to
12062 * change the shellexec routine as well.
12065 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12067 struct tblentry *cmdp;
12074 struct builtincmd *bcmd;
12076 /* If name contains a slash, don't use PATH or hash table */
12077 if (strchr(name, '/') != NULL) {
12078 entry->u.index = -1;
12079 if (act & DO_ABS) {
12080 while (stat(name, &statb) < 0) {
12082 if (errno == EINTR)
12085 entry->cmdtype = CMDUNKNOWN;
12089 entry->cmdtype = CMDNORMAL;
12093 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12095 updatetbl = (path == pathval());
12098 if (strstr(path, "%builtin") != NULL)
12099 act |= DO_ALTBLTIN;
12102 /* If name is in the table, check answer will be ok */
12103 cmdp = cmdlookup(name, 0);
12104 if (cmdp != NULL) {
12107 switch (cmdp->cmdtype) {
12125 } else if (cmdp->rehash == 0)
12126 /* if not invalidated by cd, we're done */
12130 /* If %builtin not in path, check for builtin next */
12131 bcmd = find_builtin(name);
12133 if (IS_BUILTIN_REGULAR(bcmd))
12134 goto builtin_success;
12135 if (act & DO_ALTPATH) {
12136 if (!(act & DO_ALTBLTIN))
12137 goto builtin_success;
12138 } else if (builtinloc <= 0) {
12139 goto builtin_success;
12143 #if ENABLE_FEATURE_SH_STANDALONE
12145 int applet_no = find_applet_by_name(name);
12146 if (applet_no >= 0) {
12147 entry->cmdtype = CMDNORMAL;
12148 entry->u.index = -2 - applet_no;
12154 /* We have to search path. */
12155 prev = -1; /* where to start */
12156 if (cmdp && cmdp->rehash) { /* doing a rehash */
12157 if (cmdp->cmdtype == CMDBUILTIN)
12160 prev = cmdp->param.index;
12166 while ((fullname = path_advance(&path, name)) != NULL) {
12167 stunalloc(fullname);
12168 /* NB: code below will still use fullname
12169 * despite it being "unallocated" */
12172 if (prefix(pathopt, "builtin")) {
12174 goto builtin_success;
12177 if ((act & DO_NOFUNC)
12178 || !prefix(pathopt, "func")
12179 ) { /* ignore unimplemented options */
12183 /* if rehash, don't redo absolute path names */
12184 if (fullname[0] == '/' && idx <= prev) {
12187 TRACE(("searchexec \"%s\": no change\n", name));
12190 while (stat(fullname, &statb) < 0) {
12192 if (errno == EINTR)
12195 if (errno != ENOENT && errno != ENOTDIR)
12199 e = EACCES; /* if we fail, this will be the error */
12200 if (!S_ISREG(statb.st_mode))
12202 if (pathopt) { /* this is a %func directory */
12203 stalloc(strlen(fullname) + 1);
12204 /* NB: stalloc will return space pointed by fullname
12205 * (because we don't have any intervening allocations
12206 * between stunalloc above and this stalloc) */
12207 readcmdfile(fullname);
12208 cmdp = cmdlookup(name, 0);
12209 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12210 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12211 stunalloc(fullname);
12214 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12216 entry->cmdtype = CMDNORMAL;
12217 entry->u.index = idx;
12221 cmdp = cmdlookup(name, 1);
12222 cmdp->cmdtype = CMDNORMAL;
12223 cmdp->param.index = idx;
12228 /* We failed. If there was an entry for this command, delete it */
12229 if (cmdp && updatetbl)
12230 delete_cmd_entry();
12232 ash_msg("%s: %s", name, errmsg(e, "not found"));
12233 entry->cmdtype = CMDUNKNOWN;
12238 entry->cmdtype = CMDBUILTIN;
12239 entry->u.cmd = bcmd;
12243 cmdp = cmdlookup(name, 1);
12244 cmdp->cmdtype = CMDBUILTIN;
12245 cmdp->param.cmd = bcmd;
12249 entry->cmdtype = cmdp->cmdtype;
12250 entry->u = cmdp->param;
12254 /* ============ trap.c */
12257 * The trap builtin.
12259 static int FAST_FUNC
12260 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12269 for (signo = 0; signo < NSIG; signo++) {
12270 char *tr = trap_ptr[signo];
12272 /* note: bash adds "SIG", but only if invoked
12273 * as "bash". If called as "sh", or if set -o posix,
12274 * then it prints short signal names.
12275 * We are printing short names: */
12276 out1fmt("trap -- %s %s\n",
12278 get_signame(signo));
12279 /* trap_ptr != trap only if we are in special-cased `trap` code.
12280 * In this case, we will exit very soon, no need to free(). */
12281 /* if (trap_ptr != trap && tp[0]) */
12286 if (trap_ptr != trap) {
12298 signo = get_signum(*ap);
12300 ash_msg_and_raise_error("%s: bad trap", *ap);
12303 if (LONE_DASH(action))
12306 action = ckstrdup(action);
12309 trap[signo] = action;
12319 /* ============ Builtins */
12321 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12323 * Lists available builtins
12325 static int FAST_FUNC
12326 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12332 "Built-in commands:\n"
12333 "------------------\n");
12334 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12335 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12336 builtintab[i].name + 1);
12342 #if ENABLE_FEATURE_SH_STANDALONE
12344 const char *a = applet_names;
12346 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12351 a += strlen(a) + 1;
12356 return EXIT_SUCCESS;
12358 #endif /* FEATURE_SH_EXTRA_QUIET */
12361 * The export and readonly commands.
12363 static int FAST_FUNC
12364 exportcmd(int argc UNUSED_PARAM, char **argv)
12370 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12372 if (nextopt("p") != 'p') {
12377 p = strchr(name, '=');
12381 vp = *findvar(hashvar(name), name);
12387 setvar(name, p, flag);
12388 } while ((name = *++aptr) != NULL);
12392 showvars(argv[0], flag, 0);
12397 * Delete a function if it exists.
12400 unsetfunc(const char *name)
12402 struct tblentry *cmdp;
12404 cmdp = cmdlookup(name, 0);
12405 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12406 delete_cmd_entry();
12410 * The unset builtin command. We unset the function before we unset the
12411 * variable to allow a function to be unset when there is a readonly variable
12412 * with the same name.
12414 static int FAST_FUNC
12415 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12422 while ((i = nextopt("vf")) != '\0') {
12426 for (ap = argptr; *ap; ap++) {
12442 #include <sys/times.h>
12444 static const unsigned char timescmd_str[] ALIGN1 = {
12445 ' ', offsetof(struct tms, tms_utime),
12446 '\n', offsetof(struct tms, tms_stime),
12447 ' ', offsetof(struct tms, tms_cutime),
12448 '\n', offsetof(struct tms, tms_cstime),
12452 static int FAST_FUNC
12453 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12455 long clk_tck, s, t;
12456 const unsigned char *p;
12459 clk_tck = sysconf(_SC_CLK_TCK);
12464 t = *(clock_t *)(((char *) &buf) + p[1]);
12466 out1fmt("%ldm%ld.%.3lds%c",
12468 ((t - s * clk_tck) * 1000) / clk_tck,
12470 } while (*(p += 2));
12475 #if ENABLE_SH_MATH_SUPPORT
12477 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12478 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12480 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12482 static int FAST_FUNC
12483 letcmd(int argc UNUSED_PARAM, char **argv)
12489 ash_msg_and_raise_error("expression expected");
12491 i = ash_arith(*argv);
12496 #endif /* SH_MATH_SUPPORT */
12499 /* ============ miscbltin.c
12501 * Miscellaneous builtins.
12506 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12507 typedef enum __rlimit_resource rlim_t;
12511 * The read builtin. Options:
12512 * -r Do not interpret '\' specially
12513 * -s Turn off echo (tty only)
12514 * -n NCHARS Read NCHARS max
12515 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12516 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12517 * -u FD Read from given FD instead of fd 0
12518 * This uses unbuffered input, which may be avoidable in some cases.
12519 * TODO: bash also has:
12520 * -a ARRAY Read into array[0],[1],etc
12521 * -d DELIM End on DELIM char, not newline
12522 * -e Use line editing (tty only)
12524 static int FAST_FUNC
12525 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12527 static const char *const arg_REPLY[] = { "REPLY", NULL };
12540 #if ENABLE_ASH_READ_NCHARS
12541 int nchars = 0; /* if != 0, -n is in effect */
12543 struct termios tty, old_tty;
12545 #if ENABLE_ASH_READ_TIMEOUT
12546 unsigned end_ms = 0;
12547 unsigned timeout = 0;
12552 while ((i = nextopt("p:u:r"
12553 IF_ASH_READ_TIMEOUT("t:")
12554 IF_ASH_READ_NCHARS("n:s")
12558 prompt = optionarg;
12560 #if ENABLE_ASH_READ_NCHARS
12562 nchars = bb_strtou(optionarg, NULL, 10);
12563 if (nchars < 0 || errno)
12564 ash_msg_and_raise_error("invalid count");
12565 /* nchars == 0: off (bash 3.2 does this too) */
12571 #if ENABLE_ASH_READ_TIMEOUT
12573 timeout = bb_strtou(optionarg, NULL, 10);
12574 if (errno || timeout > UINT_MAX / 2048)
12575 ash_msg_and_raise_error("invalid timeout");
12577 #if 0 /* even bash have no -t N.NNN support */
12578 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12580 /* EINVAL means number is ok, but not terminated by NUL */
12581 if (*p == '.' && errno == EINVAL) {
12585 ts.tv_usec = bb_strtou(p, &p2, 10);
12587 ash_msg_and_raise_error("invalid timeout");
12589 /* normalize to usec */
12591 ash_msg_and_raise_error("invalid timeout");
12592 while (scale++ < 6)
12595 } else if (ts.tv_sec < 0 || errno) {
12596 ash_msg_and_raise_error("invalid timeout");
12598 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12599 ash_msg_and_raise_error("invalid timeout");
12608 fd = bb_strtou(optionarg, NULL, 10);
12609 if (fd < 0 || errno)
12610 ash_msg_and_raise_error("invalid file descriptor");
12616 if (prompt && isatty(fd)) {
12621 ap = (char**)arg_REPLY;
12622 ifs = bltinlookup("IFS");
12625 #if ENABLE_ASH_READ_NCHARS
12626 tcgetattr(fd, &tty);
12628 if (nchars || silent) {
12630 tty.c_lflag &= ~ICANON;
12631 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12634 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12636 /* if tcgetattr failed, tcsetattr will fail too.
12637 * Ignoring, it's harmless. */
12638 tcsetattr(fd, TCSANOW, &tty);
12645 #if ENABLE_ASH_READ_TIMEOUT
12646 if (timeout) /* NB: ensuring end_ms is nonzero */
12647 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12651 const char *is_ifs;
12653 #if ENABLE_ASH_READ_TIMEOUT
12655 struct pollfd pfd[1];
12657 pfd[0].events = POLLIN;
12658 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12659 if ((int)timeout <= 0 /* already late? */
12660 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12661 ) { /* timed out! */
12662 #if ENABLE_ASH_READ_NCHARS
12663 tcsetattr(fd, TCSANOW, &old_tty);
12669 if (nonblock_safe_read(fd, &c, 1) != 1) {
12681 if (!rflag && c == '\\') {
12687 /* $IFS splitting */
12688 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12689 is_ifs = strchr(ifs, c);
12690 if (startword && is_ifs) {
12693 /* it is a non-space ifs char */
12695 if (startword == 1) /* first one? */
12696 continue; /* yes, it is not next word yet */
12699 if (ap[1] != NULL && is_ifs) {
12702 beg = stackblock();
12703 setvar(*ap, beg, 0);
12705 /* can we skip one non-space ifs char? (2: yes) */
12706 startword = isspace(c) ? 2 : 1;
12713 /* end of do {} while: */
12714 #if ENABLE_ASH_READ_NCHARS
12720 #if ENABLE_ASH_READ_NCHARS
12721 tcsetattr(fd, TCSANOW, &old_tty);
12725 /* Remove trailing space ifs chars */
12726 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12728 setvar(*ap, stackblock(), 0);
12729 while (*++ap != NULL)
12730 setvar(*ap, nullstr, 0);
12734 static int FAST_FUNC
12735 umaskcmd(int argc UNUSED_PARAM, char **argv)
12737 static const char permuser[3] ALIGN1 = "ugo";
12738 static const char permmode[3] ALIGN1 = "rwx";
12739 static const short permmask[] ALIGN2 = {
12740 S_IRUSR, S_IWUSR, S_IXUSR,
12741 S_IRGRP, S_IWGRP, S_IXGRP,
12742 S_IROTH, S_IWOTH, S_IXOTH
12745 /* TODO: use bb_parse_mode() instead */
12750 int symbolic_mode = 0;
12752 while (nextopt("S") != '\0') {
12763 if (symbolic_mode) {
12767 for (i = 0; i < 3; i++) {
12770 *p++ = permuser[i];
12772 for (j = 0; j < 3; j++) {
12773 if ((mask & permmask[3 * i + j]) == 0) {
12774 *p++ = permmode[j];
12782 out1fmt("%.4o\n", mask);
12785 if (isdigit((unsigned char) *ap)) {
12788 if (*ap >= '8' || *ap < '0')
12789 ash_msg_and_raise_error(msg_illnum, argv[1]);
12790 mask = (mask << 3) + (*ap - '0');
12791 } while (*++ap != '\0');
12794 mask = ~mask & 0777;
12795 if (!bb_parse_mode(ap, &mask)) {
12796 ash_msg_and_raise_error("illegal mode: %s", ap);
12798 umask(~mask & 0777);
12807 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12808 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12809 * ash by J.T. Conklin.
12814 uint8_t cmd; /* RLIMIT_xxx fit into it */
12815 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12819 static const struct limits limits_tbl[] = {
12821 { RLIMIT_CPU, 0, 't' },
12823 #ifdef RLIMIT_FSIZE
12824 { RLIMIT_FSIZE, 9, 'f' },
12827 { RLIMIT_DATA, 10, 'd' },
12829 #ifdef RLIMIT_STACK
12830 { RLIMIT_STACK, 10, 's' },
12833 { RLIMIT_CORE, 9, 'c' },
12836 { RLIMIT_RSS, 10, 'm' },
12838 #ifdef RLIMIT_MEMLOCK
12839 { RLIMIT_MEMLOCK, 10, 'l' },
12841 #ifdef RLIMIT_NPROC
12842 { RLIMIT_NPROC, 0, 'p' },
12844 #ifdef RLIMIT_NOFILE
12845 { RLIMIT_NOFILE, 0, 'n' },
12848 { RLIMIT_AS, 10, 'v' },
12850 #ifdef RLIMIT_LOCKS
12851 { RLIMIT_LOCKS, 0, 'w' },
12854 static const char limits_name[] =
12856 "time(seconds)" "\0"
12858 #ifdef RLIMIT_FSIZE
12859 "file(blocks)" "\0"
12864 #ifdef RLIMIT_STACK
12868 "coredump(blocks)" "\0"
12873 #ifdef RLIMIT_MEMLOCK
12874 "locked memory(kb)" "\0"
12876 #ifdef RLIMIT_NPROC
12879 #ifdef RLIMIT_NOFILE
12885 #ifdef RLIMIT_LOCKS
12890 enum limtype { SOFT = 0x1, HARD = 0x2 };
12893 printlim(enum limtype how, const struct rlimit *limit,
12894 const struct limits *l)
12898 val = limit->rlim_max;
12900 val = limit->rlim_cur;
12902 if (val == RLIM_INFINITY)
12903 out1fmt("unlimited\n");
12905 val >>= l->factor_shift;
12906 out1fmt("%lld\n", (long long) val);
12910 static int FAST_FUNC
12911 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12914 enum limtype how = SOFT | HARD;
12915 const struct limits *l;
12918 struct rlimit limit;
12921 while ((optc = nextopt("HSa"
12925 #ifdef RLIMIT_FSIZE
12931 #ifdef RLIMIT_STACK
12940 #ifdef RLIMIT_MEMLOCK
12943 #ifdef RLIMIT_NPROC
12946 #ifdef RLIMIT_NOFILE
12952 #ifdef RLIMIT_LOCKS
12970 for (l = limits_tbl; l->option != what; l++)
12973 set = *argptr ? 1 : 0;
12978 if (all || argptr[1])
12979 ash_msg_and_raise_error("too many arguments");
12980 if (strncmp(p, "unlimited\n", 9) == 0)
12981 val = RLIM_INFINITY;
12983 if (sizeof(val) == sizeof(int))
12984 val = bb_strtou(p, NULL, 10);
12985 else if (sizeof(val) == sizeof(long))
12986 val = bb_strtoul(p, NULL, 10);
12988 val = bb_strtoull(p, NULL, 10);
12990 ash_msg_and_raise_error("bad number");
12991 val <<= l->factor_shift;
12995 const char *lname = limits_name;
12996 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12997 getrlimit(l->cmd, &limit);
12998 out1fmt("%-20s ", lname);
12999 lname += strlen(lname) + 1;
13000 printlim(how, &limit, l);
13005 getrlimit(l->cmd, &limit);
13008 limit.rlim_max = val;
13010 limit.rlim_cur = val;
13011 if (setrlimit(l->cmd, &limit) < 0)
13012 ash_msg_and_raise_error("error setting limit (%m)");
13014 printlim(how, &limit, l);
13019 /* ============ main() and helpers */
13022 * Called to exit the shell.
13024 static void exitshell(void) NORETURN;
13032 status = exitstatus;
13033 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13034 if (setjmp(loc.loc)) {
13035 if (exception_type == EXEXIT)
13036 /* dash bug: it just does _exit(exitstatus) here
13037 * but we have to do setjobctl(0) first!
13038 * (bug is still not fixed in dash-0.5.3 - if you run dash
13039 * under Midnight Commander, on exit from dash MC is backgrounded) */
13040 status = exitstatus;
13043 exception_handler = &loc;
13050 flush_stdout_stderr();
13060 /* from input.c: */
13061 basepf.next_to_pgetc = basepf.buf = basebuf;
13064 signal(SIGCHLD, SIG_DFL);
13070 struct stat st1, st2;
13073 for (envp = environ; envp && *envp; envp++) {
13074 if (strchr(*envp, '=')) {
13075 setvareq(*envp, VEXPORT|VTEXTFIXED);
13079 setvar("PPID", utoa(getppid()), 0);
13081 p = lookupvar("PWD");
13083 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13084 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13091 * Process the shell command line arguments.
13094 procargs(char **argv)
13097 const char *xminusc;
13102 /* if (xargv[0]) - mmm, this is always true! */
13104 for (i = 0; i < NOPTS; i++)
13108 /* it already printed err message */
13109 raise_exception(EXERROR);
13113 if (*xargv == NULL) {
13115 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13118 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13122 for (i = 0; i < NOPTS; i++)
13123 if (optlist[i] == 2)
13128 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13133 } else if (!sflag) {
13134 setinputfile(*xargv, 0);
13137 commandname = arg0;
13140 shellparam.p = xargv;
13141 #if ENABLE_ASH_GETOPTS
13142 shellparam.optind = 1;
13143 shellparam.optoff = -1;
13145 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13147 shellparam.nparam++;
13154 * Read /etc/profile or .profile.
13157 read_profile(const char *name)
13161 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13170 * This routine is called when an error or an interrupt occurs in an
13171 * interactive shell and control is returned to the main command loop.
13179 /* from input.c: */
13180 g_parsefile->left_in_buffer = 0;
13181 g_parsefile->left_in_line = 0; /* clear input buffer */
13183 /* from parser.c: */
13186 /* from redir.c: */
13187 clearredir(/*drop:*/ 0);
13191 static short profile_buf[16384];
13192 extern int etext();
13196 * Main routine. We initialize things, parse the arguments, execute
13197 * profiles if we're a login shell, and then call cmdloop to execute
13198 * commands. The setjmp call sets up the location to jump to when an
13199 * exception occurs. When an exception occurs the variable "state"
13200 * is used to figure out how far we had gotten.
13202 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13203 int ash_main(int argc UNUSED_PARAM, char **argv)
13205 const char *shinit;
13206 volatile smallint state;
13207 struct jmploc jmploc;
13208 struct stackmark smark;
13210 /* Initialize global data */
13214 #if ENABLE_ASH_ALIAS
13220 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13223 #if ENABLE_FEATURE_EDITING
13224 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13227 if (setjmp(jmploc.loc)) {
13233 e = exception_type;
13237 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13240 outcslow('\n', stderr);
13242 popstackmark(&smark);
13243 FORCE_INT_ON; /* enable interrupts */
13252 exception_handler = &jmploc;
13255 TRACE(("Shell args: "));
13256 trace_puts_args(argv);
13258 rootpid = getpid();
13261 setstackmark(&smark);
13264 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13266 const char *hp = lookupvar("HISTFILE");
13269 hp = lookupvar("HOME");
13271 char *defhp = concat_path_file(hp, ".ash_history");
13272 setvar("HISTFILE", defhp, 0);
13278 if (/* argv[0] && */ argv[0][0] == '-')
13282 read_profile("/etc/profile");
13285 read_profile(".profile");
13291 getuid() == geteuid() && getgid() == getegid() &&
13295 shinit = lookupvar("ENV");
13296 if (shinit != NULL && *shinit != '\0') {
13297 read_profile(shinit);
13303 /* evalstring pushes parsefile stack.
13304 * Ensure we don't falsely claim that 0 (stdin)
13305 * is one of stacked source fds.
13306 * Testcase: ash -c 'exec 1>&0' must not complain. */
13308 g_parsefile->fd = -1;
13309 evalstring(minusc, 0);
13312 if (sflag || minusc == NULL) {
13313 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13315 const char *hp = lookupvar("HISTFILE");
13317 line_input_state->hist_file = hp;
13320 state4: /* XXX ??? - why isn't this before the "if" statement */
13328 extern void _mcleanup(void);
13338 * Copyright (c) 1989, 1991, 1993, 1994
13339 * The Regents of the University of California. All rights reserved.
13341 * This code is derived from software contributed to Berkeley by
13342 * Kenneth Almquist.
13344 * Redistribution and use in source and binary forms, with or without
13345 * modification, are permitted provided that the following conditions
13347 * 1. Redistributions of source code must retain the above copyright
13348 * notice, this list of conditions and the following disclaimer.
13349 * 2. Redistributions in binary form must reproduce the above copyright
13350 * notice, this list of conditions and the following disclaimer in the
13351 * documentation and/or other materials provided with the distribution.
13352 * 3. Neither the name of the University nor the names of its contributors
13353 * may be used to endorse or promote products derived from this software
13354 * without specific prior written permission.
13356 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13357 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13358 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13359 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13360 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13361 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13362 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13363 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13364 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13365 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF