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 static int isdigit_str9(const char *str)
265 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
266 while (--maxlen && isdigit(*str))
268 return (*str == '\0');
272 /* ============ Interrupts / exceptions */
274 * These macros allow the user to suspend the handling of interrupt signals
275 * over a period of time. This is similar to SIGHOLD or to sigblock, but
276 * much more efficient and portable. (But hacking the kernel is so much
277 * more fun than worrying about efficiency and portability. :-))
279 #define INT_OFF do { \
285 * Called to raise an exception. Since C doesn't include exceptions, we
286 * just do a longjmp to the exception handler. The type of exception is
287 * stored in the global variable "exception_type".
289 static void raise_exception(int) NORETURN;
291 raise_exception(int e)
294 if (exception_handler == NULL)
299 longjmp(exception_handler->loc, 1);
302 #define raise_exception(e) do { \
303 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
304 raise_exception(e); \
309 * Called from trap.c when a SIGINT is received. (If the user specifies
310 * that SIGINT is to be trapped or ignored using the trap builtin, then
311 * this routine is not called.) Suppressint is nonzero when interrupts
312 * are held using the INT_OFF macro. (The test for iflag is just
313 * defensive programming.)
315 static void raise_interrupt(void) NORETURN;
317 raise_interrupt(void)
322 /* Signal is not automatically unmasked after it is raised,
323 * do it ourself - unmask all signals */
324 sigprocmask_allsigs(SIG_UNBLOCK);
325 /* pending_sig = 0; - now done in onsig() */
328 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
329 if (!(rootshell && iflag)) {
330 /* Kill ourself with SIGINT */
331 signal(SIGINT, SIG_DFL);
336 raise_exception(ex_type);
340 #define raise_interrupt() do { \
341 TRACE(("raising interrupt on line %d\n", __LINE__)); \
346 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
350 if (--suppress_int == 0 && pending_int) {
354 #define INT_ON int_on()
355 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
363 #define FORCE_INT_ON force_int_on()
365 #define SAVE_INT(v) ((v) = suppress_int)
367 #define RESTORE_INT(v) do { \
369 suppress_int = (v); \
370 if (suppress_int == 0 && pending_int) \
375 /* ============ Stdout/stderr output */
378 outstr(const char *p, FILE *file)
386 flush_stdout_stderr(void)
394 outcslow(int c, FILE *dest)
402 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
404 out1fmt(const char *fmt, ...)
411 r = vprintf(fmt, ap);
417 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
419 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
426 ret = vsnprintf(outbuf, length, fmt, ap);
433 out1str(const char *p)
439 out2str(const char *p)
442 flush_stdout_stderr();
446 /* ============ Parser structures */
448 /* control characters in argument strings */
449 #define CTLESC ((unsigned char)'\201') /* escape next character */
450 #define CTLVAR ((unsigned char)'\202') /* variable defn */
451 #define CTLENDVAR ((unsigned char)'\203')
452 #define CTLBACKQ ((unsigned char)'\204')
453 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
454 /* CTLBACKQ | CTLQUOTE == '\205' */
455 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
456 #define CTLENDARI ((unsigned char)'\207')
457 #define CTLQUOTEMARK ((unsigned char)'\210')
459 /* variable substitution byte (follows CTLVAR) */
460 #define VSTYPE 0x0f /* type of variable substitution */
461 #define VSNUL 0x10 /* colon--treat the empty string as unset */
462 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
464 /* values of VSTYPE field */
465 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
466 #define VSMINUS 0x2 /* ${var-text} */
467 #define VSPLUS 0x3 /* ${var+text} */
468 #define VSQUESTION 0x4 /* ${var?message} */
469 #define VSASSIGN 0x5 /* ${var=text} */
470 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
471 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
472 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
473 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
474 #define VSLENGTH 0xa /* ${#var} */
475 #if ENABLE_ASH_BASH_COMPAT
476 #define VSSUBSTR 0xc /* ${var:position:length} */
477 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
478 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
481 static const char dolatstr[] ALIGN1 = {
482 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
502 #if ENABLE_ASH_BASH_COMPAT
519 smallint type; /* Nxxxx */
522 union node *redirect;
527 smallint pipe_backgnd;
528 struct nodelist *cmdlist;
534 union node *redirect;
547 union node *elsepart;
574 struct nodelist *backquote;
577 /* nfile and ndup layout must match!
578 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
579 * that it is actually NTO2 (>&file), and change its type.
596 char *_unused_expfname;
615 struct nredir nredir;
616 struct nbinary nbinary;
620 struct nclist nclist;
629 * NODE_EOF is returned by parsecmd when it encounters an end of file.
630 * It must be distinct from NULL.
632 #define NODE_EOF ((union node *) -1L)
635 struct nodelist *next;
648 freefunc(struct funcnode *f)
650 if (f && --f->count < 0)
655 /* ============ Debugging output */
659 static FILE *tracefile;
662 trace_printf(const char *fmt, ...)
669 fprintf(tracefile, "%u ", (int) time(NULL));
671 fprintf(tracefile, "[%u] ", (int) getpid());
673 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
675 vfprintf(tracefile, fmt, va);
680 trace_vprintf(const char *fmt, va_list va)
685 fprintf(tracefile, "%u ", (int) time(NULL));
687 fprintf(tracefile, "[%u] ", (int) getpid());
689 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
690 vfprintf(tracefile, fmt, va);
694 trace_puts(const char *s)
702 trace_puts_quoted(char *s)
709 putc('"', tracefile);
710 for (p = s; *p; p++) {
711 switch ((unsigned char)*p) {
712 case '\n': c = 'n'; goto backslash;
713 case '\t': c = 't'; goto backslash;
714 case '\r': c = 'r'; goto backslash;
715 case '\"': c = '\"'; goto backslash;
716 case '\\': c = '\\'; goto backslash;
717 case CTLESC: c = 'e'; goto backslash;
718 case CTLVAR: c = 'v'; goto backslash;
719 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
720 case CTLBACKQ: c = 'q'; goto backslash;
721 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
723 putc('\\', tracefile);
727 if (*p >= ' ' && *p <= '~')
730 putc('\\', tracefile);
731 putc((*p >> 6) & 03, tracefile);
732 putc((*p >> 3) & 07, tracefile);
733 putc(*p & 07, tracefile);
738 putc('"', tracefile);
742 trace_puts_args(char **ap)
749 trace_puts_quoted(*ap);
751 putc('\n', tracefile);
754 putc(' ', tracefile);
769 /* leave open because libedit might be using it */
772 strcpy(s, "./trace");
774 if (!freopen(s, "a", tracefile)) {
775 fprintf(stderr, "Can't re-open %s\n", s);
780 tracefile = fopen(s, "a");
781 if (tracefile == NULL) {
782 fprintf(stderr, "Can't open %s\n", s);
788 flags = fcntl(fileno(tracefile), F_GETFL);
790 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
792 setlinebuf(tracefile);
793 fputs("\nTracing started.\n", tracefile);
797 indent(int amount, char *pfx, FILE *fp)
801 for (i = 0; i < amount; i++) {
802 if (pfx && i == amount - 1)
808 /* little circular references here... */
809 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
812 sharg(union node *arg, FILE *fp)
815 struct nodelist *bqlist;
816 unsigned char subtype;
818 if (arg->type != NARG) {
819 out1fmt("<node type %d>\n", arg->type);
822 bqlist = arg->narg.backquote;
823 for (p = arg->narg.text; *p; p++) {
824 switch ((unsigned char)*p) {
832 if (subtype == VSLENGTH)
841 switch (subtype & VSTYPE) {
874 out1fmt("<subtype %d>", subtype);
881 case CTLBACKQ|CTLQUOTE:
884 shtree(bqlist->n, -1, NULL, fp);
895 shcmd(union node *cmd, FILE *fp)
903 for (np = cmd->ncmd.args; np; np = np->narg.next) {
909 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
913 switch (np->nfile.type) {
914 case NTO: s = ">>"+1; dftfd = 1; break;
915 case NCLOBBER: s = ">|"; dftfd = 1; break;
916 case NAPPEND: s = ">>"; dftfd = 1; break;
917 #if ENABLE_ASH_BASH_COMPAT
920 case NTOFD: s = ">&"; dftfd = 1; break;
921 case NFROM: s = "<"; break;
922 case NFROMFD: s = "<&"; break;
923 case NFROMTO: s = "<>"; break;
924 default: s = "*error*"; break;
926 if (np->nfile.fd != dftfd)
927 fprintf(fp, "%d", np->nfile.fd);
929 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
930 fprintf(fp, "%d", np->ndup.dupfd);
932 sharg(np->nfile.fname, fp);
939 shtree(union node *n, int ind, char *pfx, FILE *fp)
947 indent(ind, pfx, fp);
964 shtree(n->nbinary.ch1, ind, NULL, fp);
967 shtree(n->nbinary.ch2, ind, NULL, fp);
975 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
976 shtree(lp->n, 0, NULL, fp);
980 if (n->npipe.pipe_backgnd)
986 fprintf(fp, "<node type %d>", n->type);
994 showtree(union node *n)
996 trace_puts("showtree called\n");
997 shtree(n, 1, NULL, stderr);
1003 /* ============ Parser data */
1006 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1009 struct strlist *next;
1016 struct strpush *prev; /* preceding string on stack */
1018 int prev_left_in_line;
1019 #if ENABLE_ASH_ALIAS
1020 struct alias *ap; /* if push was associated with an alias */
1022 char *string; /* remember the string since it may change */
1026 struct parsefile *prev; /* preceding file on stack */
1027 int linno; /* current line */
1028 int fd; /* file descriptor (or -1 if string) */
1029 int left_in_line; /* number of chars left in this line */
1030 int left_in_buffer; /* number of chars left in this buffer past the line */
1031 char *next_to_pgetc; /* next char in buffer */
1032 char *buf; /* input buffer */
1033 struct strpush *strpush; /* for pushing strings at this level */
1034 struct strpush basestrpush; /* so pushing one is fast */
1037 static struct parsefile basepf; /* top level input file */
1038 static struct parsefile *g_parsefile = &basepf; /* current input file */
1039 static int startlinno; /* line # where last token started */
1040 static char *commandname; /* currently executing command */
1041 static struct strlist *cmdenviron; /* environment for builtin command */
1042 static uint8_t exitstatus; /* exit status of last command */
1045 /* ============ Message printing */
1048 ash_vmsg(const char *msg, va_list ap)
1050 fprintf(stderr, "%s: ", arg0);
1052 if (strcmp(arg0, commandname))
1053 fprintf(stderr, "%s: ", commandname);
1054 if (!iflag || g_parsefile->fd)
1055 fprintf(stderr, "line %d: ", startlinno);
1057 vfprintf(stderr, msg, ap);
1058 outcslow('\n', stderr);
1062 * Exverror is called to raise the error exception. If the second argument
1063 * is not NULL then error prints an error message using printf style
1064 * formatting. It then raises the error exception.
1066 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1068 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1072 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1074 TRACE(("\") pid=%d\n", getpid()));
1076 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1081 flush_stdout_stderr();
1082 raise_exception(cond);
1086 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1088 ash_msg_and_raise_error(const char *msg, ...)
1093 ash_vmsg_and_raise(EXERROR, msg, ap);
1098 static void raise_error_syntax(const char *) NORETURN;
1100 raise_error_syntax(const char *msg)
1102 ash_msg_and_raise_error("syntax error: %s", msg);
1106 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1108 ash_msg_and_raise(int cond, const char *msg, ...)
1113 ash_vmsg_and_raise(cond, msg, ap);
1119 * error/warning routines for external builtins
1122 ash_msg(const char *fmt, ...)
1132 * Return a string describing an error. The returned string may be a
1133 * pointer to a static buffer that will be overwritten on the next call.
1134 * Action describes the operation that got the error.
1137 errmsg(int e, const char *em)
1139 if (e == ENOENT || e == ENOTDIR) {
1146 /* ============ Memory allocation */
1149 /* I consider these wrappers nearly useless:
1150 * ok, they return you to nearest exception handler, but
1151 * how much memory do you leak in the process, making
1152 * memory starvation worse?
1155 ckrealloc(void * p, size_t nbytes)
1157 p = realloc(p, nbytes);
1159 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1164 ckmalloc(size_t nbytes)
1166 return ckrealloc(NULL, nbytes);
1170 ckzalloc(size_t nbytes)
1172 return memset(ckmalloc(nbytes), 0, nbytes);
1176 ckstrdup(const char *s)
1178 char *p = strdup(s);
1180 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1184 /* Using bbox equivalents. They exit if out of memory */
1185 # define ckrealloc xrealloc
1186 # define ckmalloc xmalloc
1187 # define ckzalloc xzalloc
1188 # define ckstrdup xstrdup
1192 * It appears that grabstackstr() will barf with such alignments
1193 * because stalloc() will return a string allocated in a new stackblock.
1195 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1197 /* Most machines require the value returned from malloc to be aligned
1198 * in some way. The following macro will get this right
1199 * on many machines. */
1200 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1201 /* Minimum size of a block */
1202 MINSIZE = SHELL_ALIGN(504),
1205 struct stack_block {
1206 struct stack_block *prev;
1207 char space[MINSIZE];
1211 struct stack_block *stackp;
1214 struct stackmark *marknext;
1218 struct globals_memstack {
1219 struct stack_block *g_stackp; // = &stackbase;
1220 struct stackmark *markp;
1221 char *g_stacknxt; // = stackbase.space;
1222 char *sstrend; // = stackbase.space + MINSIZE;
1223 size_t g_stacknleft; // = MINSIZE;
1224 int herefd; // = -1;
1225 struct stack_block stackbase;
1227 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1228 #define G_memstack (*ash_ptr_to_globals_memstack)
1229 #define g_stackp (G_memstack.g_stackp )
1230 #define markp (G_memstack.markp )
1231 #define g_stacknxt (G_memstack.g_stacknxt )
1232 #define sstrend (G_memstack.sstrend )
1233 #define g_stacknleft (G_memstack.g_stacknleft)
1234 #define herefd (G_memstack.herefd )
1235 #define stackbase (G_memstack.stackbase )
1236 #define INIT_G_memstack() do { \
1237 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1239 g_stackp = &stackbase; \
1240 g_stacknxt = stackbase.space; \
1241 g_stacknleft = MINSIZE; \
1242 sstrend = stackbase.space + MINSIZE; \
1247 #define stackblock() ((void *)g_stacknxt)
1248 #define stackblocksize() g_stacknleft
1251 * Parse trees for commands are allocated in lifo order, so we use a stack
1252 * to make this more efficient, and also to avoid all sorts of exception
1253 * handling code to handle interrupts in the middle of a parse.
1255 * The size 504 was chosen because the Ultrix malloc handles that size
1259 stalloc(size_t nbytes)
1264 aligned = SHELL_ALIGN(nbytes);
1265 if (aligned > g_stacknleft) {
1268 struct stack_block *sp;
1270 blocksize = aligned;
1271 if (blocksize < MINSIZE)
1272 blocksize = MINSIZE;
1273 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1274 if (len < blocksize)
1275 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1278 sp->prev = g_stackp;
1279 g_stacknxt = sp->space;
1280 g_stacknleft = blocksize;
1281 sstrend = g_stacknxt + blocksize;
1286 g_stacknxt += aligned;
1287 g_stacknleft -= aligned;
1292 stzalloc(size_t nbytes)
1294 return memset(stalloc(nbytes), 0, nbytes);
1301 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1302 write(STDERR_FILENO, "stunalloc\n", 10);
1306 g_stacknleft += g_stacknxt - (char *)p;
1311 * Like strdup but works with the ash stack.
1314 ststrdup(const char *p)
1316 size_t len = strlen(p) + 1;
1317 return memcpy(stalloc(len), p, len);
1321 setstackmark(struct stackmark *mark)
1323 mark->stackp = g_stackp;
1324 mark->stacknxt = g_stacknxt;
1325 mark->stacknleft = g_stacknleft;
1326 mark->marknext = markp;
1331 popstackmark(struct stackmark *mark)
1333 struct stack_block *sp;
1339 markp = mark->marknext;
1340 while (g_stackp != mark->stackp) {
1342 g_stackp = sp->prev;
1345 g_stacknxt = mark->stacknxt;
1346 g_stacknleft = mark->stacknleft;
1347 sstrend = mark->stacknxt + mark->stacknleft;
1352 * When the parser reads in a string, it wants to stick the string on the
1353 * stack and only adjust the stack pointer when it knows how big the
1354 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1355 * of space on top of the stack and stackblocklen returns the length of
1356 * this block. Growstackblock will grow this space by at least one byte,
1357 * possibly moving it (like realloc). Grabstackblock actually allocates the
1358 * part of the block that has been used.
1361 growstackblock(void)
1365 newlen = g_stacknleft * 2;
1366 if (newlen < g_stacknleft)
1367 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1371 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1372 struct stack_block *oldstackp;
1373 struct stackmark *xmark;
1374 struct stack_block *sp;
1375 struct stack_block *prevstackp;
1379 oldstackp = g_stackp;
1381 prevstackp = sp->prev;
1382 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1383 sp = ckrealloc(sp, grosslen);
1384 sp->prev = prevstackp;
1386 g_stacknxt = sp->space;
1387 g_stacknleft = newlen;
1388 sstrend = sp->space + newlen;
1391 * Stack marks pointing to the start of the old block
1392 * must be relocated to point to the new block
1395 while (xmark != NULL && xmark->stackp == oldstackp) {
1396 xmark->stackp = g_stackp;
1397 xmark->stacknxt = g_stacknxt;
1398 xmark->stacknleft = g_stacknleft;
1399 xmark = xmark->marknext;
1403 char *oldspace = g_stacknxt;
1404 size_t oldlen = g_stacknleft;
1405 char *p = stalloc(newlen);
1407 /* free the space we just allocated */
1408 g_stacknxt = memcpy(p, oldspace, oldlen);
1409 g_stacknleft += newlen;
1414 grabstackblock(size_t len)
1416 len = SHELL_ALIGN(len);
1418 g_stacknleft -= len;
1422 * The following routines are somewhat easier to use than the above.
1423 * The user declares a variable of type STACKSTR, which may be declared
1424 * to be a register. The macro STARTSTACKSTR initializes things. Then
1425 * the user uses the macro STPUTC to add characters to the string. In
1426 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1427 * grown as necessary. When the user is done, she can just leave the
1428 * string there and refer to it using stackblock(). Or she can allocate
1429 * the space for it using grabstackstr(). If it is necessary to allow
1430 * someone else to use the stack temporarily and then continue to grow
1431 * the string, the user should use grabstack to allocate the space, and
1432 * then call ungrabstr(p) to return to the previous mode of operation.
1434 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1435 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1436 * is space for at least one character.
1441 size_t len = stackblocksize();
1442 if (herefd >= 0 && len >= 1024) {
1443 full_write(herefd, stackblock(), len);
1444 return stackblock();
1447 return (char *)stackblock() + len;
1451 * Called from CHECKSTRSPACE.
1454 makestrspace(size_t newlen, char *p)
1456 size_t len = p - g_stacknxt;
1457 size_t size = stackblocksize();
1462 size = stackblocksize();
1464 if (nleft >= newlen)
1468 return (char *)stackblock() + len;
1472 stack_nputstr(const char *s, size_t n, char *p)
1474 p = makestrspace(n, p);
1475 p = (char *)memcpy(p, s, n) + n;
1480 stack_putstr(const char *s, char *p)
1482 return stack_nputstr(s, strlen(s), p);
1486 _STPUTC(int c, char *p)
1494 #define STARTSTACKSTR(p) ((p) = stackblock())
1495 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1496 #define CHECKSTRSPACE(n, p) do { \
1499 size_t m = sstrend - q; \
1501 (p) = makestrspace(l, q); \
1503 #define USTPUTC(c, p) (*(p)++ = (c))
1504 #define STACKSTRNUL(p) do { \
1505 if ((p) == sstrend) \
1506 (p) = growstackstr(); \
1509 #define STUNPUTC(p) (--(p))
1510 #define STTOPC(p) ((p)[-1])
1511 #define STADJUST(amount, p) ((p) += (amount))
1513 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1514 #define ungrabstackstr(s, p) stunalloc(s)
1515 #define stackstrend() ((void *)sstrend)
1518 /* ============ String helpers */
1521 * prefix -- see if pfx is a prefix of string.
1524 prefix(const char *string, const char *pfx)
1527 if (*pfx++ != *string++)
1530 return (char *) string;
1534 * Check for a valid number. This should be elsewhere.
1537 is_number(const char *p)
1542 } while (*++p != '\0');
1547 * Convert a string of digits to an integer, printing an error message on
1551 number(const char *s)
1554 ash_msg_and_raise_error(msg_illnum, s);
1559 * Produce a possibly single quoted string suitable as input to the shell.
1560 * The return string is allocated on the stack.
1563 single_quote(const char *s)
1573 len = strchrnul(s, '\'') - s;
1575 q = p = makestrspace(len + 3, p);
1578 q = (char *)memcpy(q, s, len) + len;
1587 do len++; while (*++s == '\'');
1589 q = p = makestrspace(len + 3, p);
1592 q = (char *)memcpy(q, s - len, len) + len;
1600 return stackblock();
1604 /* ============ nextopt */
1606 static char **argptr; /* argument list for builtin commands */
1607 static char *optionarg; /* set by nextopt (like getopt) */
1608 static char *optptr; /* used by nextopt */
1611 * XXX - should get rid of. Have all builtins use getopt(3).
1612 * The library getopt must have the BSD extension static variable
1613 * "optreset", otherwise it can't be used within the shell safely.
1615 * Standard option processing (a la getopt) for builtin routines.
1616 * The only argument that is passed to nextopt is the option string;
1617 * the other arguments are unnecessary. It returns the character,
1618 * or '\0' on end of input.
1621 nextopt(const char *optstring)
1628 if (p == NULL || *p == '\0') {
1629 /* We ate entire "-param", take next one */
1635 if (*++p == '\0') /* just "-" ? */
1638 if (LONE_DASH(p)) /* "--" ? */
1640 /* p => next "-param" */
1642 /* p => some option char in the middle of a "-param" */
1644 for (q = optstring; *q != c;) {
1646 ash_msg_and_raise_error("illegal option -%c", c);
1654 ash_msg_and_raise_error("no arg for -%c option", c);
1664 /* ============ Shell variables */
1667 * The parsefile structure pointed to by the global variable parsefile
1668 * contains information about the current file being read.
1671 int nparam; /* # of positional parameters (without $0) */
1672 #if ENABLE_ASH_GETOPTS
1673 int optind; /* next parameter to be processed by getopts */
1674 int optoff; /* used by getopts */
1676 unsigned char malloced; /* if parameter list dynamically allocated */
1677 char **p; /* parameter list */
1681 * Free the list of positional parameters.
1684 freeparam(volatile struct shparam *param)
1686 if (param->malloced) {
1688 ap = ap1 = param->p;
1695 #if ENABLE_ASH_GETOPTS
1696 static void FAST_FUNC getoptsreset(const char *value);
1700 struct var *next; /* next entry in hash list */
1701 int flags; /* flags are defined above */
1702 const char *text; /* name=value */
1703 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1704 /* the variable gets set/unset */
1708 struct localvar *next; /* next local variable in list */
1709 struct var *vp; /* the variable that was made local */
1710 int flags; /* saved flags */
1711 const char *text; /* saved text */
1715 #define VEXPORT 0x01 /* variable is exported */
1716 #define VREADONLY 0x02 /* variable cannot be modified */
1717 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1718 #define VTEXTFIXED 0x08 /* text is statically allocated */
1719 #define VSTACK 0x10 /* text is allocated on the stack */
1720 #define VUNSET 0x20 /* the variable is not set */
1721 #define VNOFUNC 0x40 /* don't call the callback function */
1722 #define VNOSET 0x80 /* do not set variable - just readonly test */
1723 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1724 #if ENABLE_ASH_RANDOM_SUPPORT
1725 # define VDYNAMIC 0x200 /* dynamic variable */
1731 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1732 #define defifs (defifsvar + 4)
1734 static const char defifs[] ALIGN1 = " \t\n";
1738 /* Need to be before varinit_data[] */
1739 #if ENABLE_LOCALE_SUPPORT
1740 static void FAST_FUNC
1741 change_lc_all(const char *value)
1743 if (value && *value != '\0')
1744 setlocale(LC_ALL, value);
1746 static void FAST_FUNC
1747 change_lc_ctype(const char *value)
1749 if (value && *value != '\0')
1750 setlocale(LC_CTYPE, value);
1754 static void chkmail(void);
1755 static void changemail(const char *) FAST_FUNC;
1757 static void changepath(const char *) FAST_FUNC;
1758 #if ENABLE_ASH_RANDOM_SUPPORT
1759 static void change_random(const char *) FAST_FUNC;
1762 static const struct {
1765 void (*func)(const char *) FAST_FUNC;
1766 } varinit_data[] = {
1768 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1770 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1773 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1774 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1776 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1777 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1778 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1779 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1780 #if ENABLE_ASH_GETOPTS
1781 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1783 #if ENABLE_ASH_RANDOM_SUPPORT
1784 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1786 #if ENABLE_LOCALE_SUPPORT
1787 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1788 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1790 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1797 struct globals_var {
1798 struct shparam shellparam; /* $@ current positional parameters */
1799 struct redirtab *redirlist;
1801 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1802 struct var *vartab[VTABSIZE];
1803 struct var varinit[ARRAY_SIZE(varinit_data)];
1805 extern struct globals_var *const ash_ptr_to_globals_var;
1806 #define G_var (*ash_ptr_to_globals_var)
1807 #define shellparam (G_var.shellparam )
1808 //#define redirlist (G_var.redirlist )
1809 #define g_nullredirs (G_var.g_nullredirs )
1810 #define preverrout_fd (G_var.preverrout_fd)
1811 #define vartab (G_var.vartab )
1812 #define varinit (G_var.varinit )
1813 #define INIT_G_var() do { \
1815 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1817 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1818 varinit[i].flags = varinit_data[i].flags; \
1819 varinit[i].text = varinit_data[i].text; \
1820 varinit[i].func = varinit_data[i].func; \
1824 #define vifs varinit[0]
1826 # define vmail (&vifs)[1]
1827 # define vmpath (&vmail)[1]
1828 # define vpath (&vmpath)[1]
1830 # define vpath (&vifs)[1]
1832 #define vps1 (&vpath)[1]
1833 #define vps2 (&vps1)[1]
1834 #define vps4 (&vps2)[1]
1835 #if ENABLE_ASH_GETOPTS
1836 # define voptind (&vps4)[1]
1837 # if ENABLE_ASH_RANDOM_SUPPORT
1838 # define vrandom (&voptind)[1]
1841 # if ENABLE_ASH_RANDOM_SUPPORT
1842 # define vrandom (&vps4)[1]
1847 * The following macros access the values of the above variables.
1848 * They have to skip over the name. They return the null string
1849 * for unset variables.
1851 #define ifsval() (vifs.text + 4)
1852 #define ifsset() ((vifs.flags & VUNSET) == 0)
1854 # define mailval() (vmail.text + 5)
1855 # define mpathval() (vmpath.text + 9)
1856 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1858 #define pathval() (vpath.text + 5)
1859 #define ps1val() (vps1.text + 4)
1860 #define ps2val() (vps2.text + 4)
1861 #define ps4val() (vps4.text + 4)
1862 #if ENABLE_ASH_GETOPTS
1863 # define optindval() (voptind.text + 7)
1867 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1868 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1870 #if ENABLE_ASH_GETOPTS
1871 static void FAST_FUNC
1872 getoptsreset(const char *value)
1874 shellparam.optind = number(value);
1875 shellparam.optoff = -1;
1880 * Return of a legal variable name (a letter or underscore followed by zero or
1881 * more letters, underscores, and digits).
1884 endofname(const char *name)
1892 if (!is_in_name(*p))
1899 * Compares two strings up to the first = or '\0'. The first
1900 * string must be terminated by '='; the second may be terminated by
1901 * either '=' or '\0'.
1904 varcmp(const char *p, const char *q)
1908 while ((c = *p) == (d = *q)) {
1923 varequal(const char *a, const char *b)
1925 return !varcmp(a, b);
1929 * Find the appropriate entry in the hash table from the name.
1931 static struct var **
1932 hashvar(const char *p)
1936 hashval = ((unsigned char) *p) << 4;
1937 while (*p && *p != '=')
1938 hashval += (unsigned char) *p++;
1939 return &vartab[hashval % VTABSIZE];
1943 vpcmp(const void *a, const void *b)
1945 return varcmp(*(const char **)a, *(const char **)b);
1949 * This routine initializes the builtin variables.
1959 * PS1 depends on uid
1961 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1962 vps1.text = "PS1=\\w \\$ ";
1965 vps1.text = "PS1=# ";
1968 end = vp + ARRAY_SIZE(varinit);
1970 vpp = hashvar(vp->text);
1973 } while (++vp < end);
1976 static struct var **
1977 findvar(struct var **vpp, const char *name)
1979 for (; *vpp; vpp = &(*vpp)->next) {
1980 if (varequal((*vpp)->text, name)) {
1988 * Find the value of a variable. Returns NULL if not set.
1991 lookupvar(const char *name)
1995 v = *findvar(hashvar(name), name);
1997 #if ENABLE_ASH_RANDOM_SUPPORT
1999 * Dynamic variables are implemented roughly the same way they are
2000 * in bash. Namely, they're "special" so long as they aren't unset.
2001 * As soon as they're unset, they're no longer dynamic, and dynamic
2002 * lookup will no longer happen at that point. -- PFM.
2004 if ((v->flags & VDYNAMIC))
2007 if (!(v->flags & VUNSET))
2008 return strchrnul(v->text, '=') + 1;
2014 * Search the environment of a builtin command.
2017 bltinlookup(const char *name)
2021 for (sp = cmdenviron; sp; sp = sp->next) {
2022 if (varequal(sp->text, name))
2023 return strchrnul(sp->text, '=') + 1;
2025 return lookupvar(name);
2029 * Same as setvar except that the variable and value are passed in
2030 * the first argument as name=value. Since the first argument will
2031 * be actually stored in the table, it should not be a string that
2033 * Called with interrupts off.
2036 setvareq(char *s, int flags)
2038 struct var *vp, **vpp;
2041 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2042 vp = *findvar(vpp, s);
2044 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 if (flags & VNOSAVE)
2050 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2056 if (vp->func && (flags & VNOFUNC) == 0)
2057 (*vp->func)(strchrnul(s, '=') + 1);
2059 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2060 free((char*)vp->text);
2062 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 vp = ckzalloc(sizeof(*vp));
2069 /*vp->func = NULL; - ckzalloc did it */
2072 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2079 * Set the value of a variable. The flags argument is ored with the
2080 * flags of the variable. If val is NULL, the variable is unset.
2083 setvar(const char *name, const char *val, int flags)
2090 q = endofname(name);
2091 p = strchrnul(q, '=');
2093 if (!namelen || p != q)
2094 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2099 vallen = strlen(val);
2102 nameeq = ckmalloc(namelen + vallen + 2);
2103 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2106 p = (char *)memcpy(p, val, vallen) + vallen;
2109 setvareq(nameeq, flags | VNOSAVE);
2113 #if ENABLE_ASH_GETOPTS
2115 * Safe version of setvar, returns 1 on success 0 on failure.
2118 setvarsafe(const char *name, const char *val, int flags)
2121 volatile int saveint;
2122 struct jmploc *volatile savehandler = exception_handler;
2123 struct jmploc jmploc;
2126 if (setjmp(jmploc.loc))
2129 exception_handler = &jmploc;
2130 setvar(name, val, flags);
2133 exception_handler = savehandler;
2134 RESTORE_INT(saveint);
2140 * Unset the specified variable.
2143 unsetvar(const char *s)
2149 vpp = findvar(hashvar(s), s);
2153 int flags = vp->flags;
2156 if (flags & VREADONLY)
2158 #if ENABLE_ASH_RANDOM_SUPPORT
2159 vp->flags &= ~VDYNAMIC;
2163 if ((flags & VSTRFIXED) == 0) {
2165 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2166 free((char*)vp->text);
2172 vp->flags &= ~VEXPORT;
2182 * Process a linked list of variable assignments.
2185 listsetvar(struct strlist *list_set_var, int flags)
2187 struct strlist *lp = list_set_var;
2193 setvareq(lp->text, flags);
2200 * Generate a list of variables satisfying the given conditions.
2203 listvars(int on, int off, char ***end)
2214 for (vp = *vpp; vp; vp = vp->next) {
2215 if ((vp->flags & mask) == on) {
2216 if (ep == stackstrend())
2217 ep = growstackstr();
2218 *ep++ = (char *) vp->text;
2221 } while (++vpp < vartab + VTABSIZE);
2222 if (ep == stackstrend())
2223 ep = growstackstr();
2227 return grabstackstr(ep);
2231 /* ============ Path search helper
2233 * The variable path (passed by reference) should be set to the start
2234 * of the path before the first call; path_advance will update
2235 * this value as it proceeds. Successive calls to path_advance will return
2236 * the possible path expansions in sequence. If an option (indicated by
2237 * a percent sign) appears in the path entry then the global variable
2238 * pathopt will be set to point to it; otherwise pathopt will be set to
2241 static const char *pathopt; /* set by path_advance */
2244 path_advance(const char **path, const char *name)
2254 for (p = start; *p && *p != ':' && *p != '%'; p++)
2256 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2257 while (stackblocksize() < len)
2261 memcpy(q, start, p - start);
2269 while (*p && *p != ':')
2276 return stalloc(len);
2280 /* ============ Prompt */
2282 static smallint doprompt; /* if set, prompt the user */
2283 static smallint needprompt; /* true if interactive and at start of line */
2285 #if ENABLE_FEATURE_EDITING
2286 static line_input_t *line_input_state;
2287 static const char *cmdedit_prompt;
2289 putprompt(const char *s)
2291 if (ENABLE_ASH_EXPAND_PRMT) {
2292 free((char*)cmdedit_prompt);
2293 cmdedit_prompt = ckstrdup(s);
2300 putprompt(const char *s)
2306 #if ENABLE_ASH_EXPAND_PRMT
2307 /* expandstr() needs parsing machinery, so it is far away ahead... */
2308 static const char *expandstr(const char *ps);
2310 #define expandstr(s) s
2314 setprompt(int whichprompt)
2317 #if ENABLE_ASH_EXPAND_PRMT
2318 struct stackmark smark;
2323 switch (whichprompt) {
2333 #if ENABLE_ASH_EXPAND_PRMT
2334 setstackmark(&smark);
2335 stalloc(stackblocksize());
2337 putprompt(expandstr(prompt));
2338 #if ENABLE_ASH_EXPAND_PRMT
2339 popstackmark(&smark);
2344 /* ============ The cd and pwd commands */
2346 #define CD_PHYSICAL 1
2356 while ((i = nextopt("LP")) != '\0') {
2358 flags ^= CD_PHYSICAL;
2367 * Update curdir (the name of the current directory) in response to a
2371 updatepwd(const char *dir)
2378 cdcomppath = ststrdup(dir);
2381 if (curdir == nullstr)
2383 new = stack_putstr(curdir, new);
2385 new = makestrspace(strlen(dir) + 2, new);
2386 lim = (char *)stackblock() + 1;
2390 if (new > lim && *lim == '/')
2395 if (dir[1] == '/' && dir[2] != '/') {
2401 p = strtok(cdcomppath, "/");
2405 if (p[1] == '.' && p[2] == '\0') {
2417 new = stack_putstr(p, new);
2425 return stackblock();
2429 * Find out what the current directory is. If we already know the current
2430 * directory, this routine returns immediately.
2435 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2436 return dir ? dir : nullstr;
2440 setpwd(const char *val, int setold)
2444 oldcur = dir = curdir;
2447 setvar("OLDPWD", oldcur, VEXPORT);
2450 if (physdir != nullstr) {
2451 if (physdir != oldcur)
2455 if (oldcur == val || !val) {
2461 dir = ckstrdup(val);
2462 if (oldcur != dir && oldcur != nullstr) {
2467 setvar("PWD", dir, VEXPORT);
2470 static void hashcd(void);
2473 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2474 * know that the current directory has changed.
2477 docd(const char *dest, int flags)
2479 const char *dir = 0;
2482 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2485 if (!(flags & CD_PHYSICAL)) {
2486 dir = updatepwd(dest);
2500 static int FAST_FUNC
2501 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2513 dest = bltinlookup(homestr);
2514 else if (LONE_DASH(dest)) {
2515 dest = bltinlookup("OLDPWD");
2537 path = bltinlookup("CDPATH");
2546 p = path_advance(&path, dest);
2547 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2551 if (!docd(p, flags))
2556 ash_msg_and_raise_error("can't cd to %s", dest);
2559 if (flags & CD_PRINT)
2560 out1fmt(snlfmt, curdir);
2564 static int FAST_FUNC
2565 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2568 const char *dir = curdir;
2572 if (physdir == nullstr)
2576 out1fmt(snlfmt, dir);
2581 /* ============ ... */
2584 #define IBUFSIZ COMMON_BUFSIZE
2585 /* buffer for top level input file */
2586 #define basebuf bb_common_bufsiz1
2588 /* Syntax classes */
2589 #define CWORD 0 /* character is nothing special */
2590 #define CNL 1 /* newline character */
2591 #define CBACK 2 /* a backslash character */
2592 #define CSQUOTE 3 /* single quote */
2593 #define CDQUOTE 4 /* double quote */
2594 #define CENDQUOTE 5 /* a terminating quote */
2595 #define CBQUOTE 6 /* backwards single quote */
2596 #define CVAR 7 /* a dollar sign */
2597 #define CENDVAR 8 /* a '}' character */
2598 #define CLP 9 /* a left paren in arithmetic */
2599 #define CRP 10 /* a right paren in arithmetic */
2600 #define CENDFILE 11 /* end of file */
2601 #define CCTL 12 /* like CWORD, except it must be escaped */
2602 #define CSPCL 13 /* these terminate a word */
2603 #define CIGN 14 /* character should be ignored */
2605 #if ENABLE_ASH_ALIAS
2612 /* number syntax index */
2613 #define BASESYNTAX 0 /* not in quotes */
2614 #define DQSYNTAX 1 /* in double quotes */
2615 #define SQSYNTAX 2 /* in single quotes */
2616 #define ARISYNTAX 3 /* in arithmetic */
2617 #define PSSYNTAX 4 /* prompt */
2619 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2620 # define USE_SIT_FUNCTION
2623 #if ENABLE_SH_MATH_SUPPORT
2624 static const uint8_t S_I_T[][4] = {
2625 # if ENABLE_ASH_ALIAS
2626 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2628 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2629 { CNL, CNL, CNL, CNL }, /* 2, \n */
2630 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2631 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2632 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2633 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2634 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2635 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2636 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2637 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2638 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2639 # ifndef USE_SIT_FUNCTION
2640 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2641 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2642 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2646 static const uint8_t S_I_T[][3] = {
2647 # if ENABLE_ASH_ALIAS
2648 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2650 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2651 { CNL, CNL, CNL }, /* 2, \n */
2652 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2653 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2654 { CVAR, CVAR, CWORD }, /* 5, $ */
2655 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2656 { CSPCL, CWORD, CWORD }, /* 7, ( */
2657 { CSPCL, CWORD, CWORD }, /* 8, ) */
2658 { CBACK, CBACK, CCTL }, /* 9, \ */
2659 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2660 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2661 # ifndef USE_SIT_FUNCTION
2662 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2663 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2664 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2667 #endif /* SH_MATH_SUPPORT */
2669 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2670 * caller must ensure proper cast on it if c is *char_ptr!
2673 #ifdef USE_SIT_FUNCTION
2676 SIT(int c, int syntax)
2678 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2679 # if ENABLE_ASH_ALIAS
2680 static const uint8_t syntax_index_table[] ALIGN1 = {
2681 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2682 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2683 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2687 static const uint8_t syntax_index_table[] ALIGN1 = {
2688 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2689 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2690 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2697 if (c == PEOF) { /* 2^8+2 */
2700 # if ENABLE_ASH_ALIAS
2701 if (c == PEOA) { /* 2^8+1 */
2706 if ((unsigned char)c >= CTLESC
2707 && (unsigned char)c <= CTLQUOTEMARK
2711 s = strchrnul(spec_symbls, c);
2715 indx = syntax_index_table[s - spec_symbls];
2717 return S_I_T[indx][syntax];
2720 #else /* !USE_SIT_FUNCTION */
2722 # if ENABLE_ASH_ALIAS
2723 # define CSPCL_CIGN_CIGN_CIGN 0
2724 # define CSPCL_CWORD_CWORD_CWORD 1
2725 # define CNL_CNL_CNL_CNL 2
2726 # define CWORD_CCTL_CCTL_CWORD 3
2727 # define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2728 # define CVAR_CVAR_CWORD_CVAR 5
2729 # define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2730 # define CSPCL_CWORD_CWORD_CLP 7
2731 # define CSPCL_CWORD_CWORD_CRP 8
2732 # define CBACK_CBACK_CCTL_CBACK 9
2733 # define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2734 # define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2735 # define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2736 # define CWORD_CWORD_CWORD_CWORD 13
2737 # define CCTL_CCTL_CCTL_CCTL 14
2739 # define CSPCL_CWORD_CWORD_CWORD 0
2740 # define CNL_CNL_CNL_CNL 1
2741 # define CWORD_CCTL_CCTL_CWORD 2
2742 # define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2743 # define CVAR_CVAR_CWORD_CVAR 4
2744 # define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2745 # define CSPCL_CWORD_CWORD_CLP 6
2746 # define CSPCL_CWORD_CWORD_CRP 7
2747 # define CBACK_CBACK_CCTL_CBACK 8
2748 # define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2749 # define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2750 # define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2751 # define CWORD_CWORD_CWORD_CWORD 12
2752 # define CCTL_CCTL_CCTL_CCTL 13
2755 static const uint8_t syntax_index_table[258] = {
2756 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2757 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2768 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2792 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2794 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2796 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2797 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2798 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2799 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2800 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2802 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2803 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2804 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2805 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2816 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2817 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2818 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2820 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2849 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2850 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2851 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2854 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2856 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2857 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2858 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2859 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2860 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2861 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2862 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2863 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2864 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2865 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2866 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2867 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2868 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2869 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2870 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2871 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2872 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2873 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2875 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2878 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2882 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2883 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2884 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2885 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2887 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2888 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2889 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2890 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2891 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2892 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2893 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2894 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3013 # if ENABLE_ASH_ALIAS
3014 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3016 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3019 # define SIT(c, syntax) (S_I_T[syntax_index_table[c]][syntax])
3021 #endif /* USE_SIT_FUNCTION */
3024 /* ============ Alias handling */
3026 #if ENABLE_ASH_ALIAS
3028 #define ALIASINUSE 1
3039 static struct alias **atab; // [ATABSIZE];
3040 #define INIT_G_alias() do { \
3041 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3045 static struct alias **
3046 __lookupalias(const char *name) {
3047 unsigned int hashval;
3054 ch = (unsigned char)*p;
3058 ch = (unsigned char)*++p;
3060 app = &atab[hashval % ATABSIZE];
3062 for (; *app; app = &(*app)->next) {
3063 if (strcmp(name, (*app)->name) == 0) {
3071 static struct alias *
3072 lookupalias(const char *name, int check)
3074 struct alias *ap = *__lookupalias(name);
3076 if (check && ap && (ap->flag & ALIASINUSE))
3081 static struct alias *
3082 freealias(struct alias *ap)
3086 if (ap->flag & ALIASINUSE) {
3087 ap->flag |= ALIASDEAD;
3099 setalias(const char *name, const char *val)
3101 struct alias *ap, **app;
3103 app = __lookupalias(name);
3107 if (!(ap->flag & ALIASINUSE)) {
3110 ap->val = ckstrdup(val);
3111 ap->flag &= ~ALIASDEAD;
3114 ap = ckzalloc(sizeof(struct alias));
3115 ap->name = ckstrdup(name);
3116 ap->val = ckstrdup(val);
3117 /*ap->flag = 0; - ckzalloc did it */
3118 /*ap->next = NULL;*/
3125 unalias(const char *name)
3129 app = __lookupalias(name);
3133 *app = freealias(*app);
3144 struct alias *ap, **app;
3148 for (i = 0; i < ATABSIZE; i++) {
3150 for (ap = *app; ap; ap = *app) {
3151 *app = freealias(*app);
3161 printalias(const struct alias *ap)
3163 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3167 * TODO - sort output
3169 static int FAST_FUNC
3170 aliascmd(int argc UNUSED_PARAM, char **argv)
3179 for (i = 0; i < ATABSIZE; i++) {
3180 for (ap = atab[i]; ap; ap = ap->next) {
3186 while ((n = *++argv) != NULL) {
3187 v = strchr(n+1, '=');
3188 if (v == NULL) { /* n+1: funny ksh stuff */
3189 ap = *__lookupalias(n);
3191 fprintf(stderr, "%s: %s not found\n", "alias", n);
3204 static int FAST_FUNC
3205 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3209 while ((i = nextopt("a")) != '\0') {
3215 for (i = 0; *argptr; argptr++) {
3216 if (unalias(*argptr)) {
3217 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3225 #endif /* ASH_ALIAS */
3228 /* ============ jobs.c */
3230 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3233 #define FORK_NOJOB 2
3235 /* mode flags for showjob(s) */
3236 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3237 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3238 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3241 * A job structure contains information about a job. A job is either a
3242 * single process or a set of processes contained in a pipeline. In the
3243 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3247 pid_t pid; /* process id */
3248 int status; /* last process status from wait() */
3249 char *cmd; /* text of command being run */
3253 struct procstat ps0; /* status of process */
3254 struct procstat *ps; /* status or processes when more than one */
3256 int stopstatus; /* status of a stopped job */
3259 nprocs: 16, /* number of processes */
3261 #define JOBRUNNING 0 /* at least one proc running */
3262 #define JOBSTOPPED 1 /* all procs are stopped */
3263 #define JOBDONE 2 /* all procs are completed */
3265 sigint: 1, /* job was killed by SIGINT */
3266 jobctl: 1, /* job running under job control */
3268 waited: 1, /* true if this entry has been waited for */
3269 used: 1, /* true if this entry is in used */
3270 changed: 1; /* true if status has changed */
3271 struct job *prev_job; /* previous job */
3274 static struct job *makejob(/*union node *,*/ int);
3275 static int forkshell(struct job *, union node *, int);
3276 static int waitforjob(struct job *);
3279 enum { doing_jobctl = 0 };
3280 #define setjobctl(on) do {} while (0)
3282 static smallint doing_jobctl; //references:8
3283 static void setjobctl(int);
3290 ignoresig(int signo)
3292 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3293 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3294 /* No, need to do it */
3295 signal(signo, SIG_IGN);
3297 sigmode[signo - 1] = S_HARD_IGN;
3301 * Signal handler. Only one usage site - in setsignal()
3306 gotsig[signo - 1] = 1;
3308 if (signo == SIGINT && !trap[SIGINT]) {
3309 if (!suppress_int) {
3311 raise_interrupt(); /* does not return */
3315 pending_sig = signo;
3320 * Set the signal handler for the specified signal. The routine figures
3321 * out what it should be set to.
3324 setsignal(int signo)
3327 char cur_act, new_act;
3328 struct sigaction act;
3332 if (t != NULL) { /* trap for this sig is set */
3334 if (t[0] == '\0') /* trap is "": ignore this sig */
3338 if (rootshell && new_act == S_DFL) {
3341 if (iflag || minusc || sflag == 0)
3350 * "In all cases, bash ignores SIGQUIT. Non-builtin
3351 * commands run by bash have signal handlers
3352 * set to the values inherited by the shell
3353 * from its parent". */
3369 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3370 //whereas we have to restore it to what shell got on entry
3371 //from the parent. See comment above
3373 t = &sigmode[signo - 1];
3376 /* current setting is not yet known */
3377 if (sigaction(signo, NULL, &act)) {
3378 /* pretend it worked; maybe we should give a warning,
3379 * but other shells don't. We don't alter sigmode,
3380 * so we retry every time.
3381 * btw, in Linux it never fails. --vda */
3384 if (act.sa_handler == SIG_IGN) {
3385 cur_act = S_HARD_IGN;
3387 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3389 cur_act = S_IGN; /* don't hard ignore these */
3393 if (cur_act == S_HARD_IGN || cur_act == new_act)
3396 act.sa_handler = SIG_DFL;
3399 act.sa_handler = onsig;
3400 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3401 sigfillset(&act.sa_mask); /* ditto */
3404 act.sa_handler = SIG_IGN;
3407 sigaction_set(signo, &act);
3412 /* mode flags for set_curjob */
3413 #define CUR_DELETE 2
3414 #define CUR_RUNNING 1
3415 #define CUR_STOPPED 0
3417 /* mode flags for dowait */
3418 #define DOWAIT_NONBLOCK WNOHANG
3419 #define DOWAIT_BLOCK 0
3422 /* pgrp of shell on invocation */
3423 static int initialpgrp; //references:2
3424 static int ttyfd = -1; //5
3427 static struct job *jobtab; //5
3429 static unsigned njobs; //4
3431 static struct job *curjob; //lots
3432 /* number of presumed living untracked jobs */
3433 static int jobless; //4
3436 set_curjob(struct job *jp, unsigned mode)
3439 struct job **jpp, **curp;
3441 /* first remove from list */
3442 jpp = curp = &curjob;
3447 jpp = &jp1->prev_job;
3449 *jpp = jp1->prev_job;
3451 /* Then re-insert in correct position */
3459 /* job being deleted */
3462 /* newly created job or backgrounded job,
3463 put after all stopped jobs. */
3467 if (!jp1 || jp1->state != JOBSTOPPED)
3470 jpp = &jp1->prev_job;
3476 /* newly stopped job - becomes curjob */
3477 jp->prev_job = *jpp;
3485 jobno(const struct job *jp)
3487 return jp - jobtab + 1;
3492 * Convert a job name to a job structure.
3495 #define getjob(name, getctl) getjob(name)
3498 getjob(const char *name, int getctl)
3502 const char *err_msg = "%s: no such job";
3506 char *(*match)(const char *, const char *);
3521 if (c == '+' || c == '%') {
3523 err_msg = "No current job";
3529 err_msg = "No previous job";
3540 jp = jobtab + num - 1;
3555 if (match(jp->ps[0].cmd, p)) {
3559 err_msg = "%s: ambiguous";
3569 err_msg = "job %s not created under job control";
3570 if (getctl && jp->jobctl == 0)
3575 ash_msg_and_raise_error(err_msg, name);
3579 * Mark a job structure as unused.
3582 freejob(struct job *jp)
3584 struct procstat *ps;
3588 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3589 if (ps->cmd != nullstr)
3592 if (jp->ps != &jp->ps0)
3595 set_curjob(jp, CUR_DELETE);
3601 xtcsetpgrp(int fd, pid_t pgrp)
3603 if (tcsetpgrp(fd, pgrp))
3604 ash_msg_and_raise_error("can't set tty process group (%m)");
3608 * Turn job control on and off.
3610 * Note: This code assumes that the third arg to ioctl is a character
3611 * pointer, which is true on Berkeley systems but not System V. Since
3612 * System V doesn't have job control yet, this isn't a problem now.
3614 * Called with interrupts off.
3622 if (on == doing_jobctl || rootshell == 0)
3626 ofd = fd = open(_PATH_TTY, O_RDWR);
3628 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3629 * That sometimes helps to acquire controlling tty.
3630 * Obviously, a workaround for bugs when someone
3631 * failed to provide a controlling tty to bash! :) */
3637 fd = fcntl(fd, F_DUPFD, 10);
3642 /* fd is a tty at this point */
3643 close_on_exec_on(fd);
3644 do { /* while we are in the background */
3645 pgrp = tcgetpgrp(fd);
3648 ash_msg("can't access tty; job control turned off");
3652 if (pgrp == getpgrp())
3663 xtcsetpgrp(fd, pgrp);
3665 /* turning job control off */
3668 /* was xtcsetpgrp, but this can make exiting ash
3669 * loop forever if pty is already deleted */
3670 tcsetpgrp(fd, pgrp);
3684 static int FAST_FUNC
3685 killcmd(int argc, char **argv)
3688 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3690 if (argv[i][0] == '%') {
3691 struct job *jp = getjob(argv[i], 0);
3692 unsigned pid = jp->ps[0].pid;
3693 /* Enough space for ' -NNN<nul>' */
3694 argv[i] = alloca(sizeof(int)*3 + 3);
3695 /* kill_main has matching code to expect
3696 * leading space. Needed to not confuse
3697 * negative pids with "kill -SIGNAL_NO" syntax */
3698 sprintf(argv[i], " -%u", pid);
3700 } while (argv[++i]);
3702 return kill_main(argc, argv);
3706 showpipe(struct job *jp, FILE *out)
3708 struct procstat *sp;
3709 struct procstat *spend;
3711 spend = jp->ps + jp->nprocs;
3712 for (sp = jp->ps + 1; sp < spend; sp++)
3713 fprintf(out, " | %s", sp->cmd);
3714 outcslow('\n', out);
3715 flush_stdout_stderr();
3720 restartjob(struct job *jp, int mode)
3722 struct procstat *ps;
3728 if (jp->state == JOBDONE)
3730 jp->state = JOBRUNNING;
3732 if (mode == FORK_FG)
3733 xtcsetpgrp(ttyfd, pgid);
3734 killpg(pgid, SIGCONT);
3738 if (WIFSTOPPED(ps->status)) {
3744 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3749 static int FAST_FUNC
3750 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3757 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3762 jp = getjob(*argv, 1);
3763 if (mode == FORK_BG) {
3764 set_curjob(jp, CUR_RUNNING);
3765 fprintf(out, "[%d] ", jobno(jp));
3767 outstr(jp->ps->cmd, out);
3769 retval = restartjob(jp, mode);
3770 } while (*argv && *++argv);
3776 sprint_status(char *s, int status, int sigonly)
3782 if (!WIFEXITED(status)) {
3784 if (WIFSTOPPED(status))
3785 st = WSTOPSIG(status);
3788 st = WTERMSIG(status);
3790 if (st == SIGINT || st == SIGPIPE)
3793 if (WIFSTOPPED(status))
3798 col = fmtstr(s, 32, strsignal(st));
3799 if (WCOREDUMP(status)) {
3800 col += fmtstr(s + col, 16, " (core dumped)");
3802 } else if (!sigonly) {
3803 st = WEXITSTATUS(status);
3805 col = fmtstr(s, 16, "Done(%d)", st);
3807 col = fmtstr(s, 16, "Done");
3814 dowait(int wait_flags, struct job *job)
3819 struct job *thisjob;
3822 TRACE(("dowait(0x%x) called\n", wait_flags));
3824 /* Do a wait system call. If job control is compiled in, we accept
3825 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3826 * NB: _not_ safe_waitpid, we need to detect EINTR */
3827 pid = waitpid(-1, &status,
3828 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3829 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3830 pid, status, errno, strerror(errno)));
3836 for (jp = curjob; jp; jp = jp->prev_job) {
3837 struct procstat *sp;
3838 struct procstat *spend;
3839 if (jp->state == JOBDONE)
3842 spend = jp->ps + jp->nprocs;
3845 if (sp->pid == pid) {
3846 TRACE(("Job %d: changing status of proc %d "
3847 "from 0x%x to 0x%x\n",
3848 jobno(jp), pid, sp->status, status));
3849 sp->status = status;
3852 if (sp->status == -1)
3855 if (state == JOBRUNNING)
3857 if (WIFSTOPPED(sp->status)) {
3858 jp->stopstatus = sp->status;
3862 } while (++sp < spend);
3867 if (!WIFSTOPPED(status))
3873 if (state != JOBRUNNING) {
3874 thisjob->changed = 1;
3876 if (thisjob->state != state) {
3877 TRACE(("Job %d: changing state from %d to %d\n",
3878 jobno(thisjob), thisjob->state, state));
3879 thisjob->state = state;
3881 if (state == JOBSTOPPED) {
3882 set_curjob(thisjob, CUR_STOPPED);
3891 if (thisjob && thisjob == job) {
3895 len = sprint_status(s, status, 1);
3906 blocking_wait_with_raise_on_sig(struct job *job)
3908 pid_t pid = dowait(DOWAIT_BLOCK, job);
3909 if (pid <= 0 && pending_sig)
3910 raise_exception(EXSIG);
3916 showjob(FILE *out, struct job *jp, int mode)
3918 struct procstat *ps;
3919 struct procstat *psend;
3926 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3927 /* just output process (group) id of pipeline */
3928 fprintf(out, "%d\n", ps->pid);
3932 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3937 else if (curjob && jp == curjob->prev_job)
3940 if (mode & SHOW_PIDS)
3941 col += fmtstr(s + col, 16, "%d ", ps->pid);
3943 psend = ps + jp->nprocs;
3945 if (jp->state == JOBRUNNING) {
3946 strcpy(s + col, "Running");
3947 col += sizeof("Running") - 1;
3949 int status = psend[-1].status;
3950 if (jp->state == JOBSTOPPED)
3951 status = jp->stopstatus;
3952 col += sprint_status(s + col, status, 0);
3954 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3956 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3957 * or prints several "PID | <cmdN>" lines,
3958 * depending on SHOW_PIDS bit.
3959 * We do not print status of individual processes
3960 * between PID and <cmdN>. bash does it, but not very well:
3961 * first line shows overall job status, not process status,
3962 * making it impossible to know 1st process status.
3966 /* for each process */
3969 if (mode & SHOW_PIDS)
3970 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3972 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3975 fprintf(out, "%s", ps->cmd);
3979 outcslow('\n', out);
3983 if (jp->state == JOBDONE) {
3984 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3990 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3991 * statuses have changed since the last call to showjobs.
3994 showjobs(FILE *out, int mode)
3998 TRACE(("showjobs(0x%x) called\n", mode));
4000 /* Handle all finished jobs */
4001 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4004 for (jp = curjob; jp; jp = jp->prev_job) {
4005 if (!(mode & SHOW_CHANGED) || jp->changed) {
4006 showjob(out, jp, mode);
4011 static int FAST_FUNC
4012 jobscmd(int argc UNUSED_PARAM, char **argv)
4017 while ((m = nextopt("lp")) != '\0') {
4021 mode |= SHOW_ONLY_PGID;
4027 showjob(stdout, getjob(*argv, 0), mode);
4030 showjobs(stdout, mode);
4037 getstatus(struct job *job)
4042 status = job->ps[job->nprocs - 1].status;
4043 retval = WEXITSTATUS(status);
4044 if (!WIFEXITED(status)) {
4046 retval = WSTOPSIG(status);
4047 if (!WIFSTOPPED(status))
4050 /* XXX: limits number of signals */
4051 retval = WTERMSIG(status);
4053 if (retval == SIGINT)
4059 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4060 jobno(job), job->nprocs, status, retval));
4064 static int FAST_FUNC
4065 waitcmd(int argc UNUSED_PARAM, char **argv)
4072 raise_exception(EXSIG);
4079 /* wait for all jobs */
4083 if (!jp) /* no running procs */
4085 if (jp->state == JOBRUNNING)
4091 * "When bash is waiting for an asynchronous command via
4092 * the wait builtin, the reception of a signal for which a trap
4093 * has been set will cause the wait builtin to return immediately
4094 * with an exit status greater than 128, immediately after which
4095 * the trap is executed."
4096 * Do we do it that way? */
4097 blocking_wait_with_raise_on_sig(NULL);
4103 if (**argv != '%') {
4104 pid_t pid = number(*argv);
4109 if (job->ps[job->nprocs - 1].pid == pid)
4111 job = job->prev_job;
4114 job = getjob(*argv, 0);
4115 /* loop until process terminated or stopped */
4116 while (job->state == JOBRUNNING)
4117 blocking_wait_with_raise_on_sig(NULL);
4119 retval = getstatus(job);
4132 struct job *jp, *jq;
4134 len = njobs * sizeof(*jp);
4136 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4138 offset = (char *)jp - (char *)jq;
4140 /* Relocate pointers */
4143 jq = (struct job *)((char *)jq + l);
4147 #define joff(p) ((struct job *)((char *)(p) + l))
4148 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4149 if (joff(jp)->ps == &jq->ps0)
4150 jmove(joff(jp)->ps);
4151 if (joff(jp)->prev_job)
4152 jmove(joff(jp)->prev_job);
4162 jp = (struct job *)((char *)jp + len);
4166 } while (--jq >= jp);
4171 * Return a new job structure.
4172 * Called with interrupts off.
4175 makejob(/*union node *node,*/ int nprocs)
4180 for (i = njobs, jp = jobtab; ; jp++) {
4187 if (jp->state != JOBDONE || !jp->waited)
4196 memset(jp, 0, sizeof(*jp));
4198 /* jp->jobctl is a bitfield.
4199 * "jp->jobctl |= jobctl" likely to give awful code */
4203 jp->prev_job = curjob;
4208 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4210 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4217 * Return a string identifying a command (to be printed by the
4220 static char *cmdnextc;
4223 cmdputs(const char *s)
4225 static const char vstype[VSTYPE + 1][3] = {
4226 "", "}", "-", "+", "?", "=",
4227 "%", "%%", "#", "##"
4228 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4231 const char *p, *str;
4235 unsigned char subtype = 0;
4238 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4240 while ((c = *p++) != 0) {
4248 if ((subtype & VSTYPE) == VSLENGTH)
4252 if (!(subtype & VSQUOTE) == !(quoted & 1))
4258 str = "\"}" + !(quoted & 1);
4265 case CTLBACKQ+CTLQUOTE:
4268 #if ENABLE_SH_MATH_SUPPORT
4283 if ((subtype & VSTYPE) != VSNORMAL)
4285 str = vstype[subtype & VSTYPE];
4286 if (subtype & VSNUL)
4295 /* These can only happen inside quotes */
4308 while ((c = *str++) != '\0') {
4313 USTPUTC('"', nextc);
4319 /* cmdtxt() and cmdlist() call each other */
4320 static void cmdtxt(union node *n);
4323 cmdlist(union node *np, int sep)
4325 for (; np; np = np->narg.next) {
4329 if (sep && np->narg.next)
4335 cmdtxt(union node *n)
4338 struct nodelist *lp;
4349 lp = n->npipe.cmdlist;
4367 cmdtxt(n->nbinary.ch1);
4383 cmdtxt(n->nif.test);
4385 if (n->nif.elsepart) {
4386 cmdtxt(n->nif.ifpart);
4388 n = n->nif.elsepart;
4406 cmdtxt(n->nbinary.ch1);
4416 cmdputs(n->nfor.var);
4418 cmdlist(n->nfor.args, 1);
4423 cmdputs(n->narg.text);
4427 cmdlist(n->ncmd.args, 1);
4428 cmdlist(n->ncmd.redirect, 0);
4441 cmdputs(n->ncase.expr->narg.text);
4443 for (np = n->ncase.cases; np; np = np->nclist.next) {
4444 cmdtxt(np->nclist.pattern);
4446 cmdtxt(np->nclist.body);
4460 #if ENABLE_ASH_BASH_COMPAT
4475 cmdputs(utoa(n->nfile.fd));
4477 if (n->type == NTOFD || n->type == NFROMFD) {
4478 cmdputs(utoa(n->ndup.dupfd));
4487 commandtext(union node *n)
4491 STARTSTACKSTR(cmdnextc);
4493 name = stackblock();
4494 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4495 name, cmdnextc, cmdnextc));
4496 return ckstrdup(name);
4501 * Fork off a subshell. If we are doing job control, give the subshell its
4502 * own process group. Jp is a job structure that the job is to be added to.
4503 * N is the command that will be evaluated by the child. Both jp and n may
4504 * be NULL. The mode parameter can be one of the following:
4505 * FORK_FG - Fork off a foreground process.
4506 * FORK_BG - Fork off a background process.
4507 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4508 * process group even if job control is on.
4510 * When job control is turned off, background processes have their standard
4511 * input redirected to /dev/null (except for the second and later processes
4514 * Called with interrupts off.
4517 * Clear traps on a fork.
4524 for (tp = trap; tp < &trap[NSIG]; tp++) {
4525 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4527 if (trap_ptr == trap)
4529 /* else: it "belongs" to trap_ptr vector, don't free */
4531 if ((tp - trap) != 0)
4532 setsignal(tp - trap);
4538 /* Lives far away from here, needed for forkchild */
4539 static void closescript(void);
4541 /* Called after fork(), in child */
4542 static NOINLINE void
4543 forkchild(struct job *jp, union node *n, int mode)
4547 TRACE(("Child shell %d\n", getpid()));
4551 /* man bash: "Non-builtin commands run by bash have signal handlers
4552 * set to the values inherited by the shell from its parent".
4553 * Do we do it correctly? */
4557 if (mode == FORK_NOJOB /* is it `xxx` ? */
4558 && n && n->type == NCMD /* is it single cmd? */
4559 /* && n->ncmd.args->type == NARG - always true? */
4560 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4561 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4562 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4564 TRACE(("Trap hack\n"));
4565 /* Awful hack for `trap` or $(trap).
4567 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4568 * contains an example where "trap" is executed in a subshell:
4570 * save_traps=$(trap)
4572 * eval "$save_traps"
4574 * Standard does not say that "trap" in subshell shall print
4575 * parent shell's traps. It only says that its output
4576 * must have suitable form, but then, in the above example
4577 * (which is not supposed to be normative), it implies that.
4579 * bash (and probably other shell) does implement it
4580 * (traps are reset to defaults, but "trap" still shows them),
4581 * but as a result, "trap" logic is hopelessly messed up:
4584 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4585 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4586 * # true | trap <--- trap is in subshell - no output (ditto)
4587 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4588 * trap -- 'echo Ho' SIGWINCH
4589 * # echo `(trap)` <--- in subshell in subshell - output
4590 * trap -- 'echo Ho' SIGWINCH
4591 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4592 * trap -- 'echo Ho' SIGWINCH
4594 * The rules when to forget and when to not forget traps
4595 * get really complex and nonsensical.
4597 * Our solution: ONLY bare $(trap) or `trap` is special.
4599 /* Save trap handler strings for trap builtin to print */
4600 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4601 /* Fall through into clearing traps */
4605 /* do job control only in root shell */
4607 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4610 if (jp->nprocs == 0)
4613 pgrp = jp->ps[0].pid;
4614 /* this can fail because we are doing it in the parent also */
4616 if (mode == FORK_FG)
4617 xtcsetpgrp(ttyfd, pgrp);
4622 if (mode == FORK_BG) {
4623 /* man bash: "When job control is not in effect,
4624 * asynchronous commands ignore SIGINT and SIGQUIT" */
4627 if (jp->nprocs == 0) {
4629 if (open(bb_dev_null, O_RDONLY) != 0)
4630 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4634 if (iflag) { /* why if iflag only? */
4639 * "In all cases, bash ignores SIGQUIT. Non-builtin
4640 * commands run by bash have signal handlers
4641 * set to the values inherited by the shell
4643 * Take care of the second rule: */
4647 if (n && n->type == NCMD
4648 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4650 TRACE(("Job hack\n"));
4651 /* "jobs": we do not want to clear job list for it,
4652 * instead we remove only _its_ own_ job from job list.
4653 * This makes "jobs .... | cat" more useful.
4659 for (jp = curjob; jp; jp = jp->prev_job)
4664 /* Called after fork(), in parent */
4666 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4669 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4671 TRACE(("In parent shell: child = %d\n", pid));
4673 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4679 if (mode != FORK_NOJOB && jp->jobctl) {
4682 if (jp->nprocs == 0)
4685 pgrp = jp->ps[0].pid;
4686 /* This can fail because we are doing it in the child also */
4690 if (mode == FORK_BG) {
4691 backgndpid = pid; /* set $! */
4692 set_curjob(jp, CUR_RUNNING);
4695 struct procstat *ps = &jp->ps[jp->nprocs++];
4700 if (doing_jobctl && n)
4701 ps->cmd = commandtext(n);
4707 forkshell(struct job *jp, union node *n, int mode)
4711 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4714 TRACE(("Fork failed, errno=%d", errno));
4717 ash_msg_and_raise_error("can't fork");
4720 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4721 forkchild(jp, n, mode);
4723 forkparent(jp, n, mode, pid);
4729 * Wait for job to finish.
4731 * Under job control we have the problem that while a child process
4732 * is running interrupts generated by the user are sent to the child
4733 * but not to the shell. This means that an infinite loop started by
4734 * an interactive user may be hard to kill. With job control turned off,
4735 * an interactive user may place an interactive program inside a loop.
4736 * If the interactive program catches interrupts, the user doesn't want
4737 * these interrupts to also abort the loop. The approach we take here
4738 * is to have the shell ignore interrupt signals while waiting for a
4739 * foreground process to terminate, and then send itself an interrupt
4740 * signal if the child process was terminated by an interrupt signal.
4741 * Unfortunately, some programs want to do a bit of cleanup and then
4742 * exit on interrupt; unless these processes terminate themselves by
4743 * sending a signal to themselves (instead of calling exit) they will
4744 * confuse this approach.
4746 * Called with interrupts off.
4749 waitforjob(struct job *jp)
4753 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4756 while (jp->state == JOBRUNNING) {
4757 /* In non-interactive shells, we _can_ get
4758 * a keyboard signal here and be EINTRed,
4759 * but we just loop back, waiting for command to complete.
4762 * "If bash is waiting for a command to complete and receives
4763 * a signal for which a trap has been set, the trap
4764 * will not be executed until the command completes."
4766 * Reality is that even if trap is not set, bash
4767 * will not act on the signal until command completes.
4768 * Try this. sleep5intoff.c:
4769 * #include <signal.h>
4770 * #include <unistd.h>
4773 * sigemptyset(&set);
4774 * sigaddset(&set, SIGINT);
4775 * sigaddset(&set, SIGQUIT);
4776 * sigprocmask(SIG_BLOCK, &set, NULL);
4780 * $ bash -c './sleep5intoff; echo hi'
4781 * ^C^C^C^C <--- pressing ^C once a second
4783 * $ bash -c './sleep5intoff; echo hi'
4784 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4787 dowait(DOWAIT_BLOCK, jp);
4794 xtcsetpgrp(ttyfd, rootpid);
4796 * This is truly gross.
4797 * If we're doing job control, then we did a TIOCSPGRP which
4798 * caused us (the shell) to no longer be in the controlling
4799 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4800 * intuit from the subprocess exit status whether a SIGINT
4801 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4803 if (jp->sigint) /* TODO: do the same with all signals */
4804 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4806 if (jp->state == JOBDONE)
4813 * return 1 if there are stopped jobs, otherwise 0
4825 if (jp && jp->state == JOBSTOPPED) {
4826 out2str("You have stopped jobs.\n");
4835 /* ============ redir.c
4837 * Code for dealing with input/output redirection.
4840 #define EMPTY -2 /* marks an unused slot in redirtab */
4841 #define CLOSED -3 /* marks a slot of previously-closed fd */
4844 * Open a file in noclobber mode.
4845 * The code was copied from bash.
4848 noclobberopen(const char *fname)
4851 struct stat finfo, finfo2;
4854 * If the file exists and is a regular file, return an error
4857 r = stat(fname, &finfo);
4858 if (r == 0 && S_ISREG(finfo.st_mode)) {
4864 * If the file was not present (r != 0), make sure we open it
4865 * exclusively so that if it is created before we open it, our open
4866 * will fail. Make sure that we do not truncate an existing file.
4867 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4868 * file was not a regular file, we leave O_EXCL off.
4871 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4872 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4874 /* If the open failed, return the file descriptor right away. */
4879 * OK, the open succeeded, but the file may have been changed from a
4880 * non-regular file to a regular file between the stat and the open.
4881 * We are assuming that the O_EXCL open handles the case where FILENAME
4882 * did not exist and is symlinked to an existing file between the stat
4887 * If we can open it and fstat the file descriptor, and neither check
4888 * revealed that it was a regular file, and the file has not been
4889 * replaced, return the file descriptor.
4891 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4892 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4895 /* The file has been replaced. badness. */
4902 * Handle here documents. Normally we fork off a process to write the
4903 * data to a pipe. If the document is short, we can stuff the data in
4904 * the pipe without forking.
4906 /* openhere needs this forward reference */
4907 static void expandhere(union node *arg, int fd);
4909 openhere(union node *redir)
4915 ash_msg_and_raise_error("pipe call failed");
4916 if (redir->type == NHERE) {
4917 len = strlen(redir->nhere.doc->narg.text);
4918 if (len <= PIPE_BUF) {
4919 full_write(pip[1], redir->nhere.doc->narg.text, len);
4923 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4926 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4927 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4928 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4929 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4930 signal(SIGPIPE, SIG_DFL);
4931 if (redir->type == NHERE)
4932 full_write(pip[1], redir->nhere.doc->narg.text, len);
4934 expandhere(redir->nhere.doc, pip[1]);
4935 _exit(EXIT_SUCCESS);
4943 openredirect(union node *redir)
4948 switch (redir->nfile.type) {
4950 fname = redir->nfile.expfname;
4951 f = open(fname, O_RDONLY);
4956 fname = redir->nfile.expfname;
4957 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4962 #if ENABLE_ASH_BASH_COMPAT
4965 /* Take care of noclobber mode. */
4967 fname = redir->nfile.expfname;
4968 f = noclobberopen(fname);
4975 fname = redir->nfile.expfname;
4976 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4981 fname = redir->nfile.expfname;
4982 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4990 /* Fall through to eliminate warning. */
4991 /* Our single caller does this itself */
4998 f = openhere(redir);
5004 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5006 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5010 * Copy a file descriptor to be >= to. Returns -1
5011 * if the source file descriptor is closed, EMPTY if there are no unused
5012 * file descriptors left.
5014 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5015 * old code was doing close(to) prior to copyfd() to achieve the same */
5017 COPYFD_EXACT = (int)~(INT_MAX),
5018 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5021 copyfd(int from, int to)
5025 if (to & COPYFD_EXACT) {
5026 to &= ~COPYFD_EXACT;
5028 newfd = dup2(from, to);
5030 newfd = fcntl(from, F_DUPFD, to);
5033 if (errno == EMFILE)
5035 /* Happens when source fd is not open: try "echo >&99" */
5036 ash_msg_and_raise_error("%d: %m", from);
5041 /* Struct def and variable are moved down to the first usage site */
5046 struct redirtab *next;
5049 struct two_fd_t two_fd[];
5051 #define redirlist (G_var.redirlist)
5053 static int need_to_remember(struct redirtab *rp, int fd)
5057 if (!rp) /* remembering was not requested */
5060 for (i = 0; i < rp->pair_count; i++) {
5061 if (rp->two_fd[i].orig == fd) {
5062 /* already remembered */
5069 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5070 static int is_hidden_fd(struct redirtab *rp, int fd)
5073 struct parsefile *pf;
5086 fd |= COPYFD_RESTORE;
5087 for (i = 0; i < rp->pair_count; i++) {
5088 if (rp->two_fd[i].copy == fd) {
5096 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5097 * old file descriptors are stashed away so that the redirection can be
5098 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5099 * standard output, and the standard error if it becomes a duplicate of
5100 * stdout, is saved in memory.
5102 /* flags passed to redirect */
5103 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5104 #define REDIR_SAVEFD2 03 /* set preverrout */
5106 redirect(union node *redir, int flags)
5108 struct redirtab *sv;
5113 int copied_fd2 = -1;
5123 if (flags & REDIR_PUSH) {
5124 union node *tmp = redir;
5127 #if ENABLE_ASH_BASH_COMPAT
5128 if (redir->nfile.type == NTO2)
5131 tmp = tmp->nfile.next;
5133 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5134 sv->next = redirlist;
5135 sv->pair_count = sv_pos;
5137 sv->nullredirs = g_nullredirs - 1;
5139 while (sv_pos > 0) {
5141 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5146 fd = redir->nfile.fd;
5147 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5148 int right_fd = redir->ndup.dupfd;
5149 /* redirect from/to same file descriptor? */
5152 /* echo >&10 and 10 is a fd opened to the sh script? */
5153 if (is_hidden_fd(sv, right_fd)) {
5154 errno = EBADF; /* as if it is closed */
5155 ash_msg_and_raise_error("%d: %m", right_fd);
5159 newfd = openredirect(redir); /* always >= 0 */
5161 /* Descriptor wasn't open before redirect.
5162 * Mark it for close in the future */
5163 if (need_to_remember(sv, fd)) {
5164 goto remember_to_close;
5169 #if ENABLE_ASH_BASH_COMPAT
5172 if (need_to_remember(sv, fd)) {
5173 /* Copy old descriptor */
5174 i = fcntl(fd, F_DUPFD, 10);
5175 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5176 * are closed in popredir() in the child, preventing them from leaking
5177 * into child. (popredir() also cleans up the mess in case of failures)
5182 /* Strange error (e.g. "too many files" EMFILE?) */
5186 ash_msg_and_raise_error("%d: %m", fd);
5189 /* EBADF: it is not open - good, remember to close it */
5192 } else { /* fd is open, save its copy */
5193 /* "exec fd>&-" should not close fds
5194 * which point to script file(s).
5195 * Force them to be restored afterwards */
5196 if (is_hidden_fd(sv, fd))
5197 i |= COPYFD_RESTORE;
5201 sv->two_fd[sv_pos].orig = fd;
5202 sv->two_fd[sv_pos].copy = i;
5206 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5207 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5208 /* Don't want to trigger debugging */
5212 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5214 } else if (fd != newfd) { /* move newfd to fd */
5215 copyfd(newfd, fd | COPYFD_EXACT);
5216 #if ENABLE_ASH_BASH_COMPAT
5217 if (!(redir->nfile.type == NTO2 && fd == 2))
5221 #if ENABLE_ASH_BASH_COMPAT
5222 if (redir->nfile.type == NTO2 && fd == 1) {
5223 /* We already redirected it to fd 1, now copy it to 2 */
5229 } while ((redir = redir->nfile.next) != NULL);
5232 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5233 preverrout_fd = copied_fd2;
5237 * Undo the effects of the last redirection.
5240 popredir(int drop, int restore)
5242 struct redirtab *rp;
5245 if (--g_nullredirs >= 0)
5249 for (i = 0; i < rp->pair_count; i++) {
5250 int fd = rp->two_fd[i].orig;
5251 int copy = rp->two_fd[i].copy;
5252 if (copy == CLOSED) {
5257 if (copy != EMPTY) {
5258 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5259 copy &= ~COPYFD_RESTORE;
5261 copyfd(copy, fd | COPYFD_EXACT);
5263 close(copy & ~COPYFD_RESTORE);
5266 redirlist = rp->next;
5267 g_nullredirs = rp->nullredirs;
5273 * Undo all redirections. Called on error or interrupt.
5277 * Discard all saved file descriptors.
5280 clearredir(int drop)
5286 popredir(drop, /*restore:*/ 0);
5291 redirectsafe(union node *redir, int flags)
5294 volatile int saveint;
5295 struct jmploc *volatile savehandler = exception_handler;
5296 struct jmploc jmploc;
5299 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5300 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5302 exception_handler = &jmploc;
5303 redirect(redir, flags);
5305 exception_handler = savehandler;
5306 if (err && exception_type != EXERROR)
5307 longjmp(exception_handler->loc, 1);
5308 RESTORE_INT(saveint);
5313 /* ============ Routines to expand arguments to commands
5315 * We have to deal with backquotes, shell variables, and file metacharacters.
5318 #if ENABLE_SH_MATH_SUPPORT
5320 ash_arith(const char *s)
5322 arith_eval_hooks_t math_hooks;
5326 math_hooks.lookupvar = lookupvar;
5327 math_hooks.setvar = setvar;
5328 math_hooks.endofname = endofname;
5331 result = arith(s, &errcode, &math_hooks);
5334 ash_msg_and_raise_error("exponent less than 0");
5336 ash_msg_and_raise_error("divide by zero");
5338 ash_msg_and_raise_error("expression recursion loop detected");
5339 raise_error_syntax(s);
5350 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5351 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5352 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5353 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5354 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5355 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5356 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5357 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5358 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5362 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5363 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5364 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5365 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5366 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5369 * Structure specifying which parts of the string should be searched
5370 * for IFS characters.
5373 struct ifsregion *next; /* next region in list */
5374 int begoff; /* offset of start of region */
5375 int endoff; /* offset of end of region */
5376 int nulonly; /* search for nul bytes only */
5380 struct strlist *list;
5381 struct strlist **lastp;
5384 /* output of current string */
5385 static char *expdest;
5386 /* list of back quote expressions */
5387 static struct nodelist *argbackq;
5388 /* first struct in list of ifs regions */
5389 static struct ifsregion ifsfirst;
5390 /* last struct in list */
5391 static struct ifsregion *ifslastp;
5392 /* holds expanded arg list */
5393 static struct arglist exparg;
5403 expdest = makestrspace(32, expdest);
5404 len = fmtstr(expdest, 32, arith_t_fmt, num);
5405 STADJUST(len, expdest);
5410 esclen(const char *start, const char *p)
5414 while (p > start && (unsigned char)*--p == CTLESC) {
5421 * Remove any CTLESC characters from a string.
5424 rmescapes(char *str, int flag)
5426 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5430 unsigned protect_against_glob;
5433 p = strpbrk(str, qchars);
5439 if (flag & RMESCAPE_ALLOC) {
5440 size_t len = p - str;
5441 size_t fulllen = len + strlen(p) + 1;
5443 if (flag & RMESCAPE_GROW) {
5444 r = makestrspace(fulllen, expdest);
5445 } else if (flag & RMESCAPE_HEAP) {
5446 r = ckmalloc(fulllen);
5448 r = stalloc(fulllen);
5452 q = (char *)memcpy(q, str, len) + len;
5456 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5457 globbing = flag & RMESCAPE_GLOB;
5458 protect_against_glob = globbing;
5460 if ((unsigned char)*p == CTLQUOTEMARK) {
5461 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5462 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5463 // Note: both inquotes and protect_against_glob only affect whether
5464 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5465 inquotes = ~inquotes;
5467 protect_against_glob = globbing;
5471 /* naked back slash */
5472 protect_against_glob = 0;
5475 if ((unsigned char)*p == CTLESC) {
5477 if (protect_against_glob && inquotes && *p != '/') {
5481 protect_against_glob = globbing;
5486 if (flag & RMESCAPE_GROW) {
5488 STADJUST(q - r + 1, expdest);
5492 #define pmatch(a, b) !fnmatch((a), (b), 0)
5495 * Prepare a pattern for a expmeta (internal glob(3)) call.
5497 * Returns an stalloced string.
5500 preglob(const char *pattern, int quoted, int flag)
5502 flag |= RMESCAPE_GLOB;
5504 flag |= RMESCAPE_QUOTED;
5506 return rmescapes((char *)pattern, flag);
5510 * Put a string on the stack.
5513 memtodest(const char *p, size_t len, int syntax, int quotes)
5517 q = makestrspace(quotes ? len * 2 : len, q);
5520 unsigned char c = *p++;
5524 int n = SIT(c, syntax);
5525 if (n == CCTL || n == CBACK)
5535 strtodest(const char *p, int syntax, int quotes)
5537 memtodest(p, strlen(p), syntax, quotes);
5541 * Record the fact that we have to scan this region of the
5542 * string for IFS characters.
5545 recordregion(int start, int end, int nulonly)
5547 struct ifsregion *ifsp;
5549 if (ifslastp == NULL) {
5553 ifsp = ckzalloc(sizeof(*ifsp));
5554 /*ifsp->next = NULL; - ckzalloc did it */
5555 ifslastp->next = ifsp;
5559 ifslastp->begoff = start;
5560 ifslastp->endoff = end;
5561 ifslastp->nulonly = nulonly;
5565 removerecordregions(int endoff)
5567 if (ifslastp == NULL)
5570 if (ifsfirst.endoff > endoff) {
5571 while (ifsfirst.next != NULL) {
5572 struct ifsregion *ifsp;
5574 ifsp = ifsfirst.next->next;
5575 free(ifsfirst.next);
5576 ifsfirst.next = ifsp;
5579 if (ifsfirst.begoff > endoff)
5582 ifslastp = &ifsfirst;
5583 ifsfirst.endoff = endoff;
5588 ifslastp = &ifsfirst;
5589 while (ifslastp->next && ifslastp->next->begoff < endoff)
5590 ifslastp=ifslastp->next;
5591 while (ifslastp->next != NULL) {
5592 struct ifsregion *ifsp;
5594 ifsp = ifslastp->next->next;
5595 free(ifslastp->next);
5596 ifslastp->next = ifsp;
5599 if (ifslastp->endoff > endoff)
5600 ifslastp->endoff = endoff;
5604 exptilde(char *startp, char *p, int flags)
5610 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5615 while ((c = *++p) != '\0') {
5622 if (flags & EXP_VARTILDE)
5632 if (*name == '\0') {
5633 home = lookupvar(homestr);
5635 pw = getpwnam(name);
5640 if (!home || !*home)
5643 startloc = expdest - (char *)stackblock();
5644 strtodest(home, SQSYNTAX, quotes);
5645 recordregion(startloc, expdest - (char *)stackblock(), 0);
5653 * Execute a command inside back quotes. If it's a builtin command, we
5654 * want to save its output in a block obtained from malloc. Otherwise
5655 * we fork off a subprocess and get the output of the command via a pipe.
5656 * Should be called with interrupts off.
5658 struct backcmd { /* result of evalbackcmd */
5659 int fd; /* file descriptor to read from */
5660 int nleft; /* number of chars in buffer */
5661 char *buf; /* buffer */
5662 struct job *jp; /* job structure for command */
5665 /* These forward decls are needed to use "eval" code for backticks handling: */
5666 static uint8_t back_exitstatus; /* exit status of backquoted command */
5667 #define EV_EXIT 01 /* exit after evaluating tree */
5668 static void evaltree(union node *, int);
5670 static void FAST_FUNC
5671 evalbackcmd(union node *n, struct backcmd *result)
5682 saveherefd = herefd;
5690 ash_msg_and_raise_error("pipe call failed");
5691 jp = makejob(/*n,*/ 1);
5692 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5697 copyfd(pip[1], 1 | COPYFD_EXACT);
5701 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5705 result->fd = pip[0];
5708 herefd = saveherefd;
5710 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5711 result->fd, result->buf, result->nleft, result->jp));
5715 * Expand stuff in backwards quotes.
5718 expbackq(union node *cmd, int quoted, int quotes)
5726 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5727 struct stackmark smark;
5730 setstackmark(&smark);
5732 startloc = dest - (char *)stackblock();
5734 evalbackcmd(cmd, &in);
5735 popstackmark(&smark);
5742 memtodest(p, i, syntax, quotes);
5746 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5747 TRACE(("expbackq: read returns %d\n", i));
5756 back_exitstatus = waitforjob(in.jp);
5760 /* Eat all trailing newlines */
5762 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5767 recordregion(startloc, dest - (char *)stackblock(), 0);
5768 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5769 (dest - (char *)stackblock()) - startloc,
5770 (dest - (char *)stackblock()) - startloc,
5771 stackblock() + startloc));
5774 #if ENABLE_SH_MATH_SUPPORT
5776 * Expand arithmetic expression. Backup to start of expression,
5777 * evaluate, place result in (backed up) result, adjust string position.
5790 * This routine is slightly over-complicated for
5791 * efficiency. Next we scan backwards looking for the
5792 * start of arithmetic.
5794 start = stackblock();
5801 while ((unsigned char)*p != CTLARI) {
5805 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5810 esc = esclen(start, p);
5820 removerecordregions(begoff);
5827 rmescapes(p + 2, 0);
5829 len = cvtnum(ash_arith(p + 2));
5832 recordregion(begoff, begoff + len, 0);
5836 /* argstr needs it */
5837 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5840 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5841 * characters to allow for further processing. Otherwise treat
5842 * $@ like $* since no splitting will be performed.
5844 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5845 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5846 * for correct expansion of "B=$A" word.
5849 argstr(char *p, int flags, struct strlist *var_str_list)
5851 static const char spclchars[] ALIGN1 = {
5859 CTLBACKQ | CTLQUOTE,
5860 #if ENABLE_SH_MATH_SUPPORT
5865 const char *reject = spclchars;
5866 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5867 int breakall = flags & EXP_WORD;
5872 if (!(flags & EXP_VARTILDE)) {
5874 } else if (flags & EXP_VARTILDE2) {
5879 if (flags & EXP_TILDE) {
5882 flags &= ~EXP_TILDE;
5885 if (*q == CTLESC && (flags & EXP_QWORD))
5888 p = exptilde(p, q, flags);
5891 startloc = expdest - (char *)stackblock();
5895 length += strcspn(p + length, reject);
5899 #if ENABLE_SH_MATH_SUPPORT
5903 /* c == '=' || c == ':' || c == CTLENDARI */
5909 expdest = stack_nputstr(p, length, expdest);
5910 newloc = expdest - (char *)stackblock();
5911 if (breakall && !inquotes && newloc > startloc) {
5912 recordregion(startloc, newloc, 0);
5923 if (flags & EXP_VARTILDE2) {
5927 flags |= EXP_VARTILDE2;
5932 * sort of a hack - expand tildes in variable
5933 * assignments (after the first '=' and after ':'s).
5942 case CTLENDVAR: /* ??? */
5945 /* "$@" syntax adherence hack */
5947 && memcmp(p, dolatstr, 4) == 0
5948 && ( p[4] == CTLQUOTEMARK
5949 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5952 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5955 inquotes = !inquotes;
5968 p = evalvar(p, flags, var_str_list);
5972 case CTLBACKQ|CTLQUOTE:
5973 expbackq(argbackq->n, c, quotes);
5974 argbackq = argbackq->next;
5976 #if ENABLE_SH_MATH_SUPPORT
5989 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5992 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5993 // as part of a larger change when he added support for ${var/a/b}.
5994 // However, it broke # and % operators:
5998 //echo ${var#ab} abcdcd abcdcd
5999 //echo ${var##ab} abcdcd abcdcd
6000 //echo ${var#a*b} abcdcd ababcdcd (!)
6001 //echo ${var##a*b} cdcd cdcd
6002 //echo ${var#?} babcdcd ababcdcd (!)
6003 //echo ${var##?} babcdcd babcdcd
6004 //echo ${var#*} ababcdcd babcdcd (!)
6006 //echo ${var%cd} ababcd ababcd
6007 //echo ${var%%cd} ababcd abab (!)
6008 //echo ${var%c*d} ababcd ababcd
6009 //echo ${var%%c*d} abab ababcdcd (!)
6010 //echo ${var%?} ababcdc ababcdc
6011 //echo ${var%%?} ababcdc ababcdcd (!)
6012 //echo ${var%*} ababcdcd ababcdcd
6015 // Commenting it back out helped. Remove it completely if it really
6018 char *loc, *loc2; //, *full;
6024 int match; // = strlen(str);
6025 const char *s = loc2;
6032 match = pmatch(str, s); // this line was deleted
6034 // // chop off end if its '*'
6035 // full = strrchr(str, '*');
6036 // if (full && full != str)
6039 // // If str starts with '*' replace with s.
6040 // if ((*str == '*') && strlen(s) >= match) {
6041 // full = xstrdup(s);
6042 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6044 // full = xstrndup(str, match);
6045 // match = strncmp(s, full, strlen(full));
6049 if (match) // if (!match)
6051 if (quotes && (unsigned char)*loc == CTLESC)
6060 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6067 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6070 const char *s = loc2;
6075 match = pmatch(str, s);
6082 esc = esclen(startp, loc);
6093 static void varunset(const char *, const char *, const char *, int) NORETURN;
6095 varunset(const char *end, const char *var, const char *umsg, int varflags)
6101 msg = "parameter not set";
6103 if ((unsigned char)*end == CTLENDVAR) {
6104 if (varflags & VSNUL)
6110 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6113 #if ENABLE_ASH_BASH_COMPAT
6115 parse_sub_pattern(char *arg, int inquotes)
6117 char *idx, *repl = NULL;
6126 /* Only the first '/' seen is our separator */
6133 if (!inquotes && c == '\\' && arg[1] == '\\')
6134 arg++; /* skip both \\, not just first one */
6141 #endif /* ENABLE_ASH_BASH_COMPAT */
6144 subevalvar(char *p, char *str, int strloc, int subtype,
6145 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6147 struct nodelist *saveargbackq = argbackq;
6150 char *rmesc, *rmescend;
6151 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6152 IF_ASH_BASH_COMPAT(char null = '\0';)
6153 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6154 int saveherefd = herefd;
6155 int amount, workloc, resetloc;
6157 char *(*scan)(char*, char*, char*, char*, int, int);
6160 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6162 STPUTC('\0', expdest);
6163 herefd = saveherefd;
6164 argbackq = saveargbackq;
6165 startp = (char *)stackblock() + startloc;
6169 setvar(str, startp, 0);
6170 amount = startp - expdest;
6171 STADJUST(amount, expdest);
6174 #if ENABLE_ASH_BASH_COMPAT
6176 loc = str = stackblock() + strloc;
6177 /* Read POS in ${var:POS:LEN} */
6178 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6179 len = str - startp - 1;
6181 /* *loc != '\0', guaranteed by parser */
6185 /* Adjust the length by the number of escapes */
6186 for (ptr = startp; ptr < (str - 1); ptr++) {
6187 if ((unsigned char)*ptr == CTLESC) {
6195 if (*loc++ == ':') {
6199 /* Skip POS in ${var:POS:LEN} */
6201 while (*loc && *loc != ':') {
6203 * bash complains on: var=qwe; echo ${var:1a:123}
6205 ash_msg_and_raise_error(msg_illnum, str);
6209 if (*loc++ == ':') {
6213 if (pos >= orig_len) {
6217 if (len > (orig_len - pos))
6218 len = orig_len - pos;
6220 for (str = startp; pos; str++, pos--) {
6221 if (quotes && (unsigned char)*str == CTLESC)
6224 for (loc = startp; len; len--) {
6225 if (quotes && (unsigned char)*str == CTLESC)
6230 amount = loc - expdest;
6231 STADJUST(amount, expdest);
6236 varunset(p, str, startp, varflags);
6239 resetloc = expdest - (char *)stackblock();
6241 /* We'll comeback here if we grow the stack while handling
6242 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6243 * stack will need rebasing, and we'll need to remove our work
6246 IF_ASH_BASH_COMPAT(restart:)
6248 amount = expdest - ((char *)stackblock() + resetloc);
6249 STADJUST(-amount, expdest);
6250 startp = (char *)stackblock() + startloc;
6253 rmescend = (char *)stackblock() + strloc;
6255 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6256 if (rmesc != startp) {
6258 startp = (char *)stackblock() + startloc;
6262 str = (char *)stackblock() + strloc;
6263 preglob(str, varflags & VSQUOTE, 0);
6264 workloc = expdest - (char *)stackblock();
6266 #if ENABLE_ASH_BASH_COMPAT
6267 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6268 char *idx, *end, *restart_detect;
6271 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6276 /* If there's no pattern to match, return the expansion unmolested */
6284 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6286 /* No match, advance */
6287 restart_detect = stackblock();
6288 STPUTC(*idx, expdest);
6289 if (quotes && (unsigned char)*idx == CTLESC) {
6292 STPUTC(*idx, expdest);
6294 if (stackblock() != restart_detect)
6302 if (subtype == VSREPLACEALL) {
6304 if (quotes && (unsigned char)*idx == CTLESC)
6313 for (loc = repl; *loc; loc++) {
6314 restart_detect = stackblock();
6315 STPUTC(*loc, expdest);
6316 if (stackblock() != restart_detect)
6321 if (subtype == VSREPLACE) {
6323 restart_detect = stackblock();
6324 STPUTC(*idx, expdest);
6325 if (stackblock() != restart_detect)
6334 /* We've put the replaced text into a buffer at workloc, now
6335 * move it to the right place and adjust the stack.
6337 startp = stackblock() + startloc;
6338 STPUTC('\0', expdest);
6339 memmove(startp, stackblock() + workloc, len);
6340 startp[len++] = '\0';
6341 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6342 STADJUST(-amount, expdest);
6345 #endif /* ENABLE_ASH_BASH_COMPAT */
6347 subtype -= VSTRIMRIGHT;
6349 if (subtype < 0 || subtype > 7)
6352 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6353 zero = subtype >> 1;
6354 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6355 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6357 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6360 memmove(startp, loc, str - loc);
6361 loc = startp + (str - loc) - 1;
6364 amount = loc - expdest;
6365 STADJUST(amount, expdest);
6371 * Add the value of a specialized variable to the stack string.
6372 * name parameter (examples):
6373 * ash -c 'echo $1' name:'1='
6374 * ash -c 'echo $qwe' name:'qwe='
6375 * ash -c 'echo $$' name:'$='
6376 * ash -c 'echo ${$}' name:'$='
6377 * ash -c 'echo ${$##q}' name:'$=q'
6378 * ash -c 'echo ${#$}' name:'$='
6379 * note: examples with bad shell syntax:
6380 * ash -c 'echo ${#$1}' name:'$=1'
6381 * ash -c 'echo ${#1#}' name:'1=#'
6383 static NOINLINE ssize_t
6384 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6394 int quoted = varflags & VSQUOTE;
6395 int subtype = varflags & VSTYPE;
6396 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6398 if (quoted && (flags & EXP_FULL))
6399 sep = 1 << CHAR_BIT;
6401 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6410 num = shellparam.nparam;
6418 goto check_1char_name;
6420 expdest = makestrspace(NOPTS, expdest);
6421 for (i = NOPTS - 1; i >= 0; i--) {
6423 USTPUTC(optletters(i), expdest);
6429 /* handles cases similar to ${#$1} */
6430 if (name[2] != '\0')
6431 raise_error_syntax("bad substitution");
6439 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6440 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6446 while ((p = *ap++) != NULL) {
6449 partlen = strlen(p);
6452 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6453 memtodest(p, partlen, syntax, quotes);
6459 if (subtype == VSPLUS || subtype == VSLENGTH) {
6480 num = atoi(name); /* number(name) fails on ${N#str} etc */
6481 if (num < 0 || num > shellparam.nparam)
6483 p = num ? shellparam.p[num - 1] : arg0;
6486 /* NB: name has form "VAR=..." */
6488 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6489 * which should be considered before we check variables. */
6491 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6495 str = var_str_list->text;
6496 eq = strchr(str, '=');
6497 if (!eq) /* stop at first non-assignment */
6500 if (name_len == (unsigned)(eq - str)
6501 && strncmp(str, name, name_len) == 0) {
6503 /* goto value; - WRONG! */
6504 /* think "A=1 A=2 B=$A" */
6506 var_str_list = var_str_list->next;
6507 } while (var_str_list);
6511 p = lookupvar(name);
6517 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6518 memtodest(p, len, syntax, quotes);
6522 if (subtype == VSPLUS || subtype == VSLENGTH)
6523 STADJUST(-len, expdest);
6528 * Expand a variable, and return a pointer to the next character in the
6532 evalvar(char *p, int flags, struct strlist *var_str_list)
6543 varflags = (unsigned char) *p++;
6544 subtype = varflags & VSTYPE;
6545 quoted = varflags & VSQUOTE;
6547 easy = (!quoted || (*var == '@' && shellparam.nparam));
6548 startloc = expdest - (char *)stackblock();
6549 p = strchr(p, '=') + 1;
6552 varlen = varvalue(var, varflags, flags, var_str_list);
6553 if (varflags & VSNUL)
6556 if (subtype == VSPLUS) {
6557 varlen = -1 - varlen;
6561 if (subtype == VSMINUS) {
6565 p, flags | EXP_TILDE |
6566 (quoted ? EXP_QWORD : EXP_WORD),
6576 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6578 if (subevalvar(p, var, /* strloc: */ 0,
6579 subtype, startloc, varflags,
6585 * Remove any recorded regions beyond
6588 removerecordregions(startloc);
6598 if (varlen < 0 && uflag)
6599 varunset(p, var, 0, 0);
6601 if (subtype == VSLENGTH) {
6602 cvtnum(varlen > 0 ? varlen : 0);
6606 if (subtype == VSNORMAL) {
6617 case VSTRIMRIGHTMAX:
6618 #if ENABLE_ASH_BASH_COMPAT
6631 * Terminate the string and start recording the pattern
6634 STPUTC('\0', expdest);
6635 patloc = expdest - (char *)stackblock();
6636 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6638 //TODO: | EXP_REDIR too? All other such places do it too
6639 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6642 int amount = expdest - (
6643 (char *)stackblock() + patloc - 1
6645 STADJUST(-amount, expdest);
6647 /* Remove any recorded regions beyond start of variable */
6648 removerecordregions(startloc);
6650 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6654 if (subtype != VSNORMAL) { /* skip to end of alternative */
6657 unsigned char c = *p++;
6660 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6662 argbackq = argbackq->next;
6663 } else if (c == CTLVAR) {
6664 if ((*p++ & VSTYPE) != VSNORMAL)
6666 } else if (c == CTLENDVAR) {
6676 * Break the argument string into pieces based upon IFS and add the
6677 * strings to the argument list. The regions of the string to be
6678 * searched for IFS characters have been stored by recordregion.
6681 ifsbreakup(char *string, struct arglist *arglist)
6683 struct ifsregion *ifsp;
6688 const char *ifs, *realifs;
6693 if (ifslastp != NULL) {
6696 realifs = ifsset() ? ifsval() : defifs;
6699 p = string + ifsp->begoff;
6700 nulonly = ifsp->nulonly;
6701 ifs = nulonly ? nullstr : realifs;
6703 while (p < string + ifsp->endoff) {
6705 if ((unsigned char)*p == CTLESC)
6707 if (!strchr(ifs, *p)) {
6712 ifsspc = (strchr(defifs, *p) != NULL);
6713 /* Ignore IFS whitespace at start */
6714 if (q == start && ifsspc) {
6720 sp = stzalloc(sizeof(*sp));
6722 *arglist->lastp = sp;
6723 arglist->lastp = &sp->next;
6727 if (p >= string + ifsp->endoff) {
6731 if ((unsigned char)*p == CTLESC)
6733 if (strchr(ifs, *p) == NULL) {
6737 if (strchr(defifs, *p) == NULL) {
6752 } while (ifsp != NULL);
6761 sp = stzalloc(sizeof(*sp));
6763 *arglist->lastp = sp;
6764 arglist->lastp = &sp->next;
6770 struct ifsregion *p;
6775 struct ifsregion *ifsp;
6781 ifsfirst.next = NULL;
6786 * Add a file name to the list.
6789 addfname(const char *name)
6793 sp = stzalloc(sizeof(*sp));
6794 sp->text = ststrdup(name);
6796 exparg.lastp = &sp->next;
6799 static char *expdir;
6802 * Do metacharacter (i.e. *, ?, [...]) expansion.
6805 expmeta(char *enddir, char *name)
6820 for (p = name; *p; p++) {
6821 if (*p == '*' || *p == '?')
6823 else if (*p == '[') {
6830 if (*q == '/' || *q == '\0')
6837 } else if (*p == '\\')
6839 else if (*p == '/') {
6846 if (metaflag == 0) { /* we've reached the end of the file name */
6847 if (enddir != expdir)
6855 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6866 } while (p < start);
6868 if (enddir == expdir) {
6870 } else if (enddir == expdir + 1 && *expdir == '/') {
6879 if (enddir != expdir)
6881 if (*endname == 0) {
6893 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6894 if (dp->d_name[0] == '.' && !matchdot)
6896 if (pmatch(start, dp->d_name)) {
6898 strcpy(enddir, dp->d_name);
6901 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6904 expmeta(p, endname);
6913 static struct strlist *
6914 msort(struct strlist *list, int len)
6916 struct strlist *p, *q = NULL;
6917 struct strlist **lpp;
6925 for (n = half; --n >= 0;) {
6929 q->next = NULL; /* terminate first half of list */
6930 q = msort(list, half); /* sort first half of list */
6931 p = msort(p, len - half); /* sort second half */
6934 #if ENABLE_LOCALE_SUPPORT
6935 if (strcoll(p->text, q->text) < 0)
6937 if (strcmp(p->text, q->text) < 0)
6961 * Sort the results of file name expansion. It calculates the number of
6962 * strings to sort and then calls msort (short for merge sort) to do the
6965 static struct strlist *
6966 expsort(struct strlist *str)
6972 for (sp = str; sp; sp = sp->next)
6974 return msort(str, len);
6978 expandmeta(struct strlist *str /*, int flag*/)
6980 static const char metachars[] ALIGN1 = {
6983 /* TODO - EXP_REDIR */
6986 struct strlist **savelastp;
6992 if (!strpbrk(str->text, metachars))
6994 savelastp = exparg.lastp;
6997 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6999 int i = strlen(str->text);
7000 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7008 if (exparg.lastp == savelastp) {
7013 *exparg.lastp = str;
7014 rmescapes(str->text, 0);
7015 exparg.lastp = &str->next;
7017 *exparg.lastp = NULL;
7018 *savelastp = sp = expsort(*savelastp);
7019 while (sp->next != NULL)
7021 exparg.lastp = &sp->next;
7028 * Perform variable substitution and command substitution on an argument,
7029 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7030 * perform splitting and file name expansion. When arglist is NULL, perform
7031 * here document expansion.
7034 expandarg(union node *arg, struct arglist *arglist, int flag)
7039 argbackq = arg->narg.backquote;
7040 STARTSTACKSTR(expdest);
7041 ifsfirst.next = NULL;
7043 argstr(arg->narg.text, flag,
7044 /* var_str_list: */ arglist ? arglist->list : NULL);
7045 p = _STPUTC('\0', expdest);
7047 if (arglist == NULL) {
7048 return; /* here document expanded */
7050 p = grabstackstr(p);
7051 exparg.lastp = &exparg.list;
7055 if (flag & EXP_FULL) {
7056 ifsbreakup(p, &exparg);
7057 *exparg.lastp = NULL;
7058 exparg.lastp = &exparg.list;
7059 expandmeta(exparg.list /*, flag*/);
7061 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7063 sp = stzalloc(sizeof(*sp));
7066 exparg.lastp = &sp->next;
7070 *exparg.lastp = NULL;
7072 *arglist->lastp = exparg.list;
7073 arglist->lastp = exparg.lastp;
7078 * Expand shell variables and backquotes inside a here document.
7081 expandhere(union node *arg, int fd)
7084 expandarg(arg, (struct arglist *)NULL, 0);
7085 full_write(fd, stackblock(), expdest - (char *)stackblock());
7089 * Returns true if the pattern matches the string.
7092 patmatch(char *pattern, const char *string)
7094 return pmatch(preglob(pattern, 0, 0), string);
7098 * See if a pattern matches in a case statement.
7101 casematch(union node *pattern, char *val)
7103 struct stackmark smark;
7106 setstackmark(&smark);
7107 argbackq = pattern->narg.backquote;
7108 STARTSTACKSTR(expdest);
7110 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7111 /* var_str_list: */ NULL);
7112 STACKSTRNUL(expdest);
7113 result = patmatch(stackblock(), val);
7114 popstackmark(&smark);
7119 /* ============ find_command */
7123 int (*builtin)(int, char **) FAST_FUNC;
7124 /* unsigned flags; */
7126 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7127 /* "regular" builtins always take precedence over commands,
7128 * regardless of PATH=....%builtin... position */
7129 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7130 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7133 smallint cmdtype; /* CMDxxx */
7136 /* index >= 0 for commands without path (slashes) */
7137 /* (TODO: what exactly does the value mean? PATH position?) */
7138 /* index == -1 for commands with slashes */
7139 /* index == (-2 - applet_no) for NOFORK applets */
7140 const struct builtincmd *cmd;
7141 struct funcnode *func;
7144 /* values of cmdtype */
7145 #define CMDUNKNOWN -1 /* no entry in table for command */
7146 #define CMDNORMAL 0 /* command is an executable program */
7147 #define CMDFUNCTION 1 /* command is a shell function */
7148 #define CMDBUILTIN 2 /* command is a shell builtin */
7150 /* action to find_command() */
7151 #define DO_ERR 0x01 /* prints errors */
7152 #define DO_ABS 0x02 /* checks absolute paths */
7153 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7154 #define DO_ALTPATH 0x08 /* using alternate path */
7155 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7157 static void find_command(char *, struct cmdentry *, int, const char *);
7160 /* ============ Hashing commands */
7163 * When commands are first encountered, they are entered in a hash table.
7164 * This ensures that a full path search will not have to be done for them
7165 * on each invocation.
7167 * We should investigate converting to a linear search, even though that
7168 * would make the command name "hash" a misnomer.
7172 struct tblentry *next; /* next entry in hash chain */
7173 union param param; /* definition of builtin function */
7174 smallint cmdtype; /* CMDxxx */
7175 char rehash; /* if set, cd done since entry created */
7176 char cmdname[1]; /* name of command */
7179 static struct tblentry **cmdtable;
7180 #define INIT_G_cmdtable() do { \
7181 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7184 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7188 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7192 #if ENABLE_FEATURE_SH_STANDALONE
7193 if (applet_no >= 0) {
7194 if (APPLET_IS_NOEXEC(applet_no)) {
7197 run_applet_no_and_exit(applet_no, argv);
7199 /* re-exec ourselves with the new arguments */
7200 execve(bb_busybox_exec_path, argv, envp);
7201 /* If they called chroot or otherwise made the binary no longer
7202 * executable, fall through */
7209 execve(cmd, argv, envp);
7210 } while (errno == EINTR);
7212 execve(cmd, argv, envp);
7218 if (errno == ENOEXEC) {
7222 for (ap = argv; *ap; ap++)
7224 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7226 ap[0] = cmd = (char *)DEFAULT_SHELL;
7229 while ((*ap++ = *argv++) != NULL)
7238 * Exec a program. Never returns. If you change this routine, you may
7239 * have to change the find_command routine as well.
7241 static void shellexec(char **, const char *, int) NORETURN;
7243 shellexec(char **argv, const char *path, int idx)
7249 #if ENABLE_FEATURE_SH_STANDALONE
7253 clearredir(/*drop:*/ 1);
7254 envp = listvars(VEXPORT, VUNSET, 0);
7255 if (strchr(argv[0], '/') != NULL
7256 #if ENABLE_FEATURE_SH_STANDALONE
7257 || (applet_no = find_applet_by_name(argv[0])) >= 0
7260 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7264 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7265 if (--idx < 0 && pathopt == NULL) {
7266 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7267 if (errno != ENOENT && errno != ENOTDIR)
7274 /* Map to POSIX errors */
7286 exitstatus = exerrno;
7287 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7288 argv[0], e, suppress_int));
7289 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7294 printentry(struct tblentry *cmdp)
7300 idx = cmdp->param.index;
7303 name = path_advance(&path, cmdp->cmdname);
7305 } while (--idx >= 0);
7306 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7310 * Clear out command entries. The argument specifies the first entry in
7311 * PATH which has changed.
7314 clearcmdentry(int firstchange)
7316 struct tblentry **tblp;
7317 struct tblentry **pp;
7318 struct tblentry *cmdp;
7321 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7323 while ((cmdp = *pp) != NULL) {
7324 if ((cmdp->cmdtype == CMDNORMAL &&
7325 cmdp->param.index >= firstchange)
7326 || (cmdp->cmdtype == CMDBUILTIN &&
7327 builtinloc >= firstchange)
7340 * Locate a command in the command hash table. If "add" is nonzero,
7341 * add the command to the table if it is not already present. The
7342 * variable "lastcmdentry" is set to point to the address of the link
7343 * pointing to the entry, so that delete_cmd_entry can delete the
7346 * Interrupts must be off if called with add != 0.
7348 static struct tblentry **lastcmdentry;
7350 static struct tblentry *
7351 cmdlookup(const char *name, int add)
7353 unsigned int hashval;
7355 struct tblentry *cmdp;
7356 struct tblentry **pp;
7359 hashval = (unsigned char)*p << 4;
7361 hashval += (unsigned char)*p++;
7363 pp = &cmdtable[hashval % CMDTABLESIZE];
7364 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7365 if (strcmp(cmdp->cmdname, name) == 0)
7369 if (add && cmdp == NULL) {
7370 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7372 /* + 1 - already done because
7373 * tblentry::cmdname is char[1] */);
7374 /*cmdp->next = NULL; - ckzalloc did it */
7375 cmdp->cmdtype = CMDUNKNOWN;
7376 strcpy(cmdp->cmdname, name);
7383 * Delete the command entry returned on the last lookup.
7386 delete_cmd_entry(void)
7388 struct tblentry *cmdp;
7391 cmdp = *lastcmdentry;
7392 *lastcmdentry = cmdp->next;
7393 if (cmdp->cmdtype == CMDFUNCTION)
7394 freefunc(cmdp->param.func);
7400 * Add a new command entry, replacing any existing command entry for
7401 * the same name - except special builtins.
7404 addcmdentry(char *name, struct cmdentry *entry)
7406 struct tblentry *cmdp;
7408 cmdp = cmdlookup(name, 1);
7409 if (cmdp->cmdtype == CMDFUNCTION) {
7410 freefunc(cmdp->param.func);
7412 cmdp->cmdtype = entry->cmdtype;
7413 cmdp->param = entry->u;
7417 static int FAST_FUNC
7418 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7420 struct tblentry **pp;
7421 struct tblentry *cmdp;
7423 struct cmdentry entry;
7426 if (nextopt("r") != '\0') {
7431 if (*argptr == NULL) {
7432 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7433 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7434 if (cmdp->cmdtype == CMDNORMAL)
7442 while ((name = *argptr) != NULL) {
7443 cmdp = cmdlookup(name, 0);
7445 && (cmdp->cmdtype == CMDNORMAL
7446 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7450 find_command(name, &entry, DO_ERR, pathval());
7451 if (entry.cmdtype == CMDUNKNOWN)
7459 * Called when a cd is done. Marks all commands so the next time they
7460 * are executed they will be rehashed.
7465 struct tblentry **pp;
7466 struct tblentry *cmdp;
7468 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7469 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7470 if (cmdp->cmdtype == CMDNORMAL
7471 || (cmdp->cmdtype == CMDBUILTIN
7472 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7482 * Fix command hash table when PATH changed.
7483 * Called before PATH is changed. The argument is the new value of PATH;
7484 * pathval() still returns the old value at this point.
7485 * Called with interrupts off.
7487 static void FAST_FUNC
7488 changepath(const char *new)
7496 firstchange = 9999; /* assume no change */
7502 if ((*old == '\0' && *new == ':')
7503 || (*old == ':' && *new == '\0'))
7505 old = new; /* ignore subsequent differences */
7509 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7515 if (builtinloc < 0 && idx_bltin >= 0)
7516 builtinloc = idx_bltin; /* zap builtins */
7517 if (builtinloc >= 0 && idx_bltin < 0)
7519 clearcmdentry(firstchange);
7520 builtinloc = idx_bltin;
7535 #define TENDBQUOTE 12
7552 typedef smallint token_id_t;
7554 /* first char is indicating which tokens mark the end of a list */
7555 static const char *const tokname_array[] = {
7569 #define KWDOFFSET 13
7570 /* the following are keywords */
7592 static char buf[16];
7595 //if (tok < TSEMI) return tokname_array[tok] + 1;
7596 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7601 sprintf(buf + (tok >= TSEMI), "%s%c",
7602 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7606 /* Wrapper around strcmp for qsort/bsearch/... */
7608 pstrcmp(const void *a, const void *b)
7610 return strcmp((char*) a, (*(char**) b) + 1);
7613 static const char *const *
7614 findkwd(const char *s)
7616 return bsearch(s, tokname_array + KWDOFFSET,
7617 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7618 sizeof(tokname_array[0]), pstrcmp);
7622 * Locate and print what a word is...
7625 describe_command(char *command, int describe_command_verbose)
7627 struct cmdentry entry;
7628 struct tblentry *cmdp;
7629 #if ENABLE_ASH_ALIAS
7630 const struct alias *ap;
7632 const char *path = pathval();
7634 if (describe_command_verbose) {
7638 /* First look at the keywords */
7639 if (findkwd(command)) {
7640 out1str(describe_command_verbose ? " is a shell keyword" : command);
7644 #if ENABLE_ASH_ALIAS
7645 /* Then look at the aliases */
7646 ap = lookupalias(command, 0);
7648 if (!describe_command_verbose) {
7653 out1fmt(" is an alias for %s", ap->val);
7657 /* Then check if it is a tracked alias */
7658 cmdp = cmdlookup(command, 0);
7660 entry.cmdtype = cmdp->cmdtype;
7661 entry.u = cmdp->param;
7663 /* Finally use brute force */
7664 find_command(command, &entry, DO_ABS, path);
7667 switch (entry.cmdtype) {
7669 int j = entry.u.index;
7675 p = path_advance(&path, command);
7679 if (describe_command_verbose) {
7681 (cmdp ? " a tracked alias for" : nullstr), p
7690 if (describe_command_verbose) {
7691 out1str(" is a shell function");
7698 if (describe_command_verbose) {
7699 out1fmt(" is a %sshell builtin",
7700 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7701 "special " : nullstr
7709 if (describe_command_verbose) {
7710 out1str(": not found\n");
7715 outstr("\n", stdout);
7719 static int FAST_FUNC
7720 typecmd(int argc UNUSED_PARAM, char **argv)
7726 /* type -p ... ? (we don't bother checking for 'p') */
7727 if (argv[1] && argv[1][0] == '-') {
7732 err |= describe_command(argv[i++], verbose);
7737 #if ENABLE_ASH_CMDCMD
7738 static int FAST_FUNC
7739 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7747 while ((c = nextopt("pvV")) != '\0')
7749 verify |= VERIFY_VERBOSE;
7751 verify |= VERIFY_BRIEF;
7756 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7757 if (verify && (*argptr != NULL)) {
7758 return describe_command(*argptr, verify - VERIFY_BRIEF);
7766 /* ============ eval.c */
7768 static int funcblocksize; /* size of structures in function */
7769 static int funcstringsize; /* size of strings in node */
7770 static void *funcblock; /* block to allocate function from */
7771 static char *funcstring; /* block to allocate strings from */
7773 /* flags in argument to evaltree */
7774 #define EV_EXIT 01 /* exit after evaluating tree */
7775 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7776 #define EV_BACKCMD 04 /* command executing within back quotes */
7778 static const uint8_t nodesize[N_NUMBER] = {
7779 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7780 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7781 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7782 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7783 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7784 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7785 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7786 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7787 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7788 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7789 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7790 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7791 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7792 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7793 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7794 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7795 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7796 #if ENABLE_ASH_BASH_COMPAT
7797 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7799 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7800 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7801 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7802 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7803 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7804 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7805 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7806 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7807 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7810 static void calcsize(union node *n);
7813 sizenodelist(struct nodelist *lp)
7816 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7823 calcsize(union node *n)
7827 funcblocksize += nodesize[n->type];
7830 calcsize(n->ncmd.redirect);
7831 calcsize(n->ncmd.args);
7832 calcsize(n->ncmd.assign);
7835 sizenodelist(n->npipe.cmdlist);
7840 calcsize(n->nredir.redirect);
7841 calcsize(n->nredir.n);
7848 calcsize(n->nbinary.ch2);
7849 calcsize(n->nbinary.ch1);
7852 calcsize(n->nif.elsepart);
7853 calcsize(n->nif.ifpart);
7854 calcsize(n->nif.test);
7857 funcstringsize += strlen(n->nfor.var) + 1;
7858 calcsize(n->nfor.body);
7859 calcsize(n->nfor.args);
7862 calcsize(n->ncase.cases);
7863 calcsize(n->ncase.expr);
7866 calcsize(n->nclist.body);
7867 calcsize(n->nclist.pattern);
7868 calcsize(n->nclist.next);
7872 sizenodelist(n->narg.backquote);
7873 funcstringsize += strlen(n->narg.text) + 1;
7874 calcsize(n->narg.next);
7877 #if ENABLE_ASH_BASH_COMPAT
7884 calcsize(n->nfile.fname);
7885 calcsize(n->nfile.next);
7889 calcsize(n->ndup.vname);
7890 calcsize(n->ndup.next);
7894 calcsize(n->nhere.doc);
7895 calcsize(n->nhere.next);
7898 calcsize(n->nnot.com);
7904 nodeckstrdup(char *s)
7906 char *rtn = funcstring;
7908 strcpy(funcstring, s);
7909 funcstring += strlen(s) + 1;
7913 static union node *copynode(union node *);
7915 static struct nodelist *
7916 copynodelist(struct nodelist *lp)
7918 struct nodelist *start;
7919 struct nodelist **lpp;
7924 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7925 (*lpp)->n = copynode(lp->n);
7927 lpp = &(*lpp)->next;
7934 copynode(union node *n)
7941 funcblock = (char *) funcblock + nodesize[n->type];
7945 new->ncmd.redirect = copynode(n->ncmd.redirect);
7946 new->ncmd.args = copynode(n->ncmd.args);
7947 new->ncmd.assign = copynode(n->ncmd.assign);
7950 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7951 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7956 new->nredir.redirect = copynode(n->nredir.redirect);
7957 new->nredir.n = copynode(n->nredir.n);
7964 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7965 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7968 new->nif.elsepart = copynode(n->nif.elsepart);
7969 new->nif.ifpart = copynode(n->nif.ifpart);
7970 new->nif.test = copynode(n->nif.test);
7973 new->nfor.var = nodeckstrdup(n->nfor.var);
7974 new->nfor.body = copynode(n->nfor.body);
7975 new->nfor.args = copynode(n->nfor.args);
7978 new->ncase.cases = copynode(n->ncase.cases);
7979 new->ncase.expr = copynode(n->ncase.expr);
7982 new->nclist.body = copynode(n->nclist.body);
7983 new->nclist.pattern = copynode(n->nclist.pattern);
7984 new->nclist.next = copynode(n->nclist.next);
7988 new->narg.backquote = copynodelist(n->narg.backquote);
7989 new->narg.text = nodeckstrdup(n->narg.text);
7990 new->narg.next = copynode(n->narg.next);
7993 #if ENABLE_ASH_BASH_COMPAT
8000 new->nfile.fname = copynode(n->nfile.fname);
8001 new->nfile.fd = n->nfile.fd;
8002 new->nfile.next = copynode(n->nfile.next);
8006 new->ndup.vname = copynode(n->ndup.vname);
8007 new->ndup.dupfd = n->ndup.dupfd;
8008 new->ndup.fd = n->ndup.fd;
8009 new->ndup.next = copynode(n->ndup.next);
8013 new->nhere.doc = copynode(n->nhere.doc);
8014 new->nhere.fd = n->nhere.fd;
8015 new->nhere.next = copynode(n->nhere.next);
8018 new->nnot.com = copynode(n->nnot.com);
8021 new->type = n->type;
8026 * Make a copy of a parse tree.
8028 static struct funcnode *
8029 copyfunc(union node *n)
8034 funcblocksize = offsetof(struct funcnode, n);
8037 blocksize = funcblocksize;
8038 f = ckmalloc(blocksize + funcstringsize);
8039 funcblock = (char *) f + offsetof(struct funcnode, n);
8040 funcstring = (char *) f + blocksize;
8047 * Define a shell function.
8050 defun(char *name, union node *func)
8052 struct cmdentry entry;
8055 entry.cmdtype = CMDFUNCTION;
8056 entry.u.func = copyfunc(func);
8057 addcmdentry(name, &entry);
8061 /* Reasons for skipping commands (see comment on breakcmd routine) */
8062 #define SKIPBREAK (1 << 0)
8063 #define SKIPCONT (1 << 1)
8064 #define SKIPFUNC (1 << 2)
8065 #define SKIPFILE (1 << 3)
8066 #define SKIPEVAL (1 << 4)
8067 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8068 static int skipcount; /* number of levels to skip */
8069 static int funcnest; /* depth of function calls */
8070 static int loopnest; /* current loop nesting level */
8072 /* Forward decl way out to parsing code - dotrap needs it */
8073 static int evalstring(char *s, int mask);
8075 /* Called to execute a trap.
8076 * Single callsite - at the end of evaltree().
8077 * If we return non-zero, exaltree raises EXEXIT exception.
8079 * Perhaps we should avoid entering new trap handlers
8080 * while we are executing a trap handler. [is it a TODO?]
8089 savestatus = exitstatus;
8093 TRACE(("dotrap entered\n"));
8094 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8101 /* non-trapped SIGINT is handled separately by raise_interrupt,
8102 * don't upset it by resetting gotsig[SIGINT-1] */
8103 if (sig == SIGINT && !t)
8106 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8110 want_exexit = evalstring(t, SKIPEVAL);
8111 exitstatus = savestatus;
8113 TRACE(("dotrap returns %d\n", want_exexit));
8118 TRACE(("dotrap returns 0\n"));
8122 /* forward declarations - evaluation is fairly recursive business... */
8123 static void evalloop(union node *, int);
8124 static void evalfor(union node *, int);
8125 static void evalcase(union node *, int);
8126 static void evalsubshell(union node *, int);
8127 static void expredir(union node *);
8128 static void evalpipe(union node *, int);
8129 static void evalcommand(union node *, int);
8130 static int evalbltin(const struct builtincmd *, int, char **);
8131 static void prehash(union node *);
8134 * Evaluate a parse tree. The value is left in the global variable
8138 evaltree(union node *n, int flags)
8140 struct jmploc *volatile savehandler = exception_handler;
8141 struct jmploc jmploc;
8143 void (*evalfn)(union node *, int);
8147 SAVE_INT(int_level);
8150 TRACE(("evaltree(NULL) called\n"));
8153 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8155 exception_handler = &jmploc;
8157 int err = setjmp(jmploc.loc);
8159 /* if it was a signal, check for trap handlers */
8160 if (exception_type == EXSIG) {
8161 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8162 exception_type, err));
8165 /* continue on the way out */
8166 TRACE(("exception %d in evaltree, propagating err=%d\n",
8167 exception_type, err));
8168 exception_handler = savehandler;
8169 longjmp(exception_handler->loc, err);
8176 out1fmt("Node type = %d\n", n->type);
8181 evaltree(n->nnot.com, EV_TESTED);
8182 status = !exitstatus;
8185 expredir(n->nredir.redirect);
8186 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8188 evaltree(n->nredir.n, flags & EV_TESTED);
8189 status = exitstatus;
8191 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8194 evalfn = evalcommand;
8196 if (eflag && !(flags & EV_TESTED))
8208 evalfn = evalsubshell;
8221 #error NAND + 1 != NOR
8223 #if NOR + 1 != NSEMI
8224 #error NOR + 1 != NSEMI
8226 unsigned is_or = n->type - NAND;
8229 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8231 if (!exitstatus == is_or)
8244 evaltree(n->nif.test, EV_TESTED);
8247 if (exitstatus == 0) {
8251 if (n->nif.elsepart) {
8252 n = n->nif.elsepart;
8257 defun(n->narg.text, n->narg.next);
8261 exitstatus = status;
8266 exception_handler = savehandler;
8268 if (checkexit & exitstatus)
8269 evalskip |= SKIPEVAL;
8270 else if (pending_sig && dotrap())
8273 if (flags & EV_EXIT) {
8275 raise_exception(EXEXIT);
8278 RESTORE_INT(int_level);
8279 TRACE(("leaving evaltree (no interrupts)\n"));
8282 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8285 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8288 evalloop(union node *n, int flags)
8298 evaltree(n->nbinary.ch1, EV_TESTED);
8301 if (evalskip == SKIPCONT && --skipcount <= 0) {
8305 if (evalskip == SKIPBREAK && --skipcount <= 0)
8310 if (n->type != NWHILE)
8314 evaltree(n->nbinary.ch2, flags);
8315 status = exitstatus;
8320 exitstatus = status;
8324 evalfor(union node *n, int flags)
8326 struct arglist arglist;
8329 struct stackmark smark;
8331 setstackmark(&smark);
8332 arglist.list = NULL;
8333 arglist.lastp = &arglist.list;
8334 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8335 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8340 *arglist.lastp = NULL;
8345 for (sp = arglist.list; sp; sp = sp->next) {
8346 setvar(n->nfor.var, sp->text, 0);
8347 evaltree(n->nfor.body, flags);
8349 if (evalskip == SKIPCONT && --skipcount <= 0) {
8353 if (evalskip == SKIPBREAK && --skipcount <= 0)
8360 popstackmark(&smark);
8364 evalcase(union node *n, int flags)
8368 struct arglist arglist;
8369 struct stackmark smark;
8371 setstackmark(&smark);
8372 arglist.list = NULL;
8373 arglist.lastp = &arglist.list;
8374 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8376 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8377 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8378 if (casematch(patp, arglist.list->text)) {
8379 if (evalskip == 0) {
8380 evaltree(cp->nclist.body, flags);
8387 popstackmark(&smark);
8391 * Kick off a subshell to evaluate a tree.
8394 evalsubshell(union node *n, int flags)
8397 int backgnd = (n->type == NBACKGND);
8400 expredir(n->nredir.redirect);
8401 if (!backgnd && flags & EV_EXIT && !trap[0])
8404 jp = makejob(/*n,*/ 1);
8405 if (forkshell(jp, n, backgnd) == 0) {
8409 flags &=~ EV_TESTED;
8411 redirect(n->nredir.redirect, 0);
8412 evaltreenr(n->nredir.n, flags);
8417 status = waitforjob(jp);
8418 exitstatus = status;
8423 * Compute the names of the files in a redirection list.
8425 static void fixredir(union node *, const char *, int);
8427 expredir(union node *n)
8431 for (redir = n; redir; redir = redir->nfile.next) {
8435 fn.lastp = &fn.list;
8436 switch (redir->type) {
8440 #if ENABLE_ASH_BASH_COMPAT
8445 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8446 #if ENABLE_ASH_BASH_COMPAT
8449 redir->nfile.expfname = fn.list->text;
8452 case NTOFD: /* >& */
8453 if (redir->ndup.vname) {
8454 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8455 if (fn.list == NULL)
8456 ash_msg_and_raise_error("redir error");
8457 #if ENABLE_ASH_BASH_COMPAT
8458 //FIXME: we used expandarg with different args!
8459 if (!isdigit_str9(fn.list->text)) {
8460 /* >&file, not >&fd */
8461 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8462 ash_msg_and_raise_error("redir error");
8464 goto store_expfname;
8467 fixredir(redir, fn.list->text, 1);
8475 * Evaluate a pipeline. All the processes in the pipeline are children
8476 * of the process creating the pipeline. (This differs from some versions
8477 * of the shell, which make the last process in a pipeline the parent
8481 evalpipe(union node *n, int flags)
8484 struct nodelist *lp;
8489 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8491 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8495 jp = makejob(/*n,*/ pipelen);
8497 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8501 if (pipe(pip) < 0) {
8503 ash_msg_and_raise_error("pipe call failed");
8506 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8519 evaltreenr(lp->n, flags);
8525 /* Don't want to trigger debugging */
8529 if (n->npipe.pipe_backgnd == 0) {
8530 exitstatus = waitforjob(jp);
8531 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8537 * Controls whether the shell is interactive or not.
8540 setinteractive(int on)
8542 static smallint is_interactive;
8544 if (++on == is_interactive)
8546 is_interactive = on;
8550 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8551 if (is_interactive > 1) {
8552 /* Looks like they want an interactive shell */
8553 static smallint did_banner;
8556 /* note: ash and hush share this string */
8557 out1fmt("\n\n%s %s\n"
8558 "Enter 'help' for a list of built-in commands."
8561 "built-in shell (ash)"
8575 setinteractive(iflag);
8577 #if ENABLE_FEATURE_EDITING_VI
8579 line_input_state->flags |= VI_MODE;
8581 line_input_state->flags &= ~VI_MODE;
8583 viflag = 0; /* forcibly keep the option off */
8587 static struct localvar *localvars;
8590 * Called after a function returns.
8591 * Interrupts must be off.
8596 struct localvar *lvp;
8599 while ((lvp = localvars) != NULL) {
8600 localvars = lvp->next;
8602 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8603 if (vp == NULL) { /* $- saved */
8604 memcpy(optlist, lvp->text, sizeof(optlist));
8605 free((char*)lvp->text);
8607 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8611 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8612 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8613 free((char*)vp->text);
8614 vp->flags = lvp->flags;
8615 vp->text = lvp->text;
8622 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8624 volatile struct shparam saveparam;
8625 struct localvar *volatile savelocalvars;
8626 struct jmploc *volatile savehandler;
8627 struct jmploc jmploc;
8630 saveparam = shellparam;
8631 savelocalvars = localvars;
8632 e = setjmp(jmploc.loc);
8637 savehandler = exception_handler;
8638 exception_handler = &jmploc;
8640 shellparam.malloced = 0;
8644 shellparam.nparam = argc - 1;
8645 shellparam.p = argv + 1;
8646 #if ENABLE_ASH_GETOPTS
8647 shellparam.optind = 1;
8648 shellparam.optoff = -1;
8650 evaltree(&func->n, flags & EV_TESTED);
8656 localvars = savelocalvars;
8657 freeparam(&shellparam);
8658 shellparam = saveparam;
8659 exception_handler = savehandler;
8661 evalskip &= ~SKIPFUNC;
8665 #if ENABLE_ASH_CMDCMD
8667 parse_command_args(char **argv, const char **path)
8680 if (c == '-' && !*cp) {
8687 *path = bb_default_path;
8690 /* run 'typecmd' for other options */
8701 * Make a variable a local variable. When a variable is made local, it's
8702 * value and flags are saved in a localvar structure. The saved values
8703 * will be restored when the shell function returns. We handle the name
8704 * "-" as a special case.
8709 struct localvar *lvp;
8714 lvp = ckzalloc(sizeof(struct localvar));
8715 if (LONE_DASH(name)) {
8717 p = ckmalloc(sizeof(optlist));
8718 lvp->text = memcpy(p, optlist, sizeof(optlist));
8723 vpp = hashvar(name);
8724 vp = *findvar(vpp, name);
8725 eq = strchr(name, '=');
8728 setvareq(name, VSTRFIXED);
8730 setvar(name, NULL, VSTRFIXED);
8731 vp = *vpp; /* the new variable */
8732 lvp->flags = VUNSET;
8734 lvp->text = vp->text;
8735 lvp->flags = vp->flags;
8736 vp->flags |= VSTRFIXED|VTEXTFIXED;
8742 lvp->next = localvars;
8748 * The "local" command.
8750 static int FAST_FUNC
8751 localcmd(int argc UNUSED_PARAM, char **argv)
8756 while ((name = *argv++) != NULL) {
8762 static int FAST_FUNC
8763 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8768 static int FAST_FUNC
8769 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8774 static int FAST_FUNC
8775 execcmd(int argc UNUSED_PARAM, char **argv)
8778 iflag = 0; /* exit on error */
8781 shellexec(argv + 1, pathval(), 0);
8787 * The return command.
8789 static int FAST_FUNC
8790 returncmd(int argc UNUSED_PARAM, char **argv)
8793 * If called outside a function, do what ksh does;
8794 * skip the rest of the file.
8796 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8797 return argv[1] ? number(argv[1]) : exitstatus;
8800 /* Forward declarations for builtintab[] */
8801 static int breakcmd(int, char **) FAST_FUNC;
8802 static int dotcmd(int, char **) FAST_FUNC;
8803 static int evalcmd(int, char **) FAST_FUNC;
8804 static int exitcmd(int, char **) FAST_FUNC;
8805 static int exportcmd(int, char **) FAST_FUNC;
8806 #if ENABLE_ASH_GETOPTS
8807 static int getoptscmd(int, char **) FAST_FUNC;
8809 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8810 static int helpcmd(int, char **) FAST_FUNC;
8812 #if ENABLE_SH_MATH_SUPPORT
8813 static int letcmd(int, char **) FAST_FUNC;
8815 static int readcmd(int, char **) FAST_FUNC;
8816 static int setcmd(int, char **) FAST_FUNC;
8817 static int shiftcmd(int, char **) FAST_FUNC;
8818 static int timescmd(int, char **) FAST_FUNC;
8819 static int trapcmd(int, char **) FAST_FUNC;
8820 static int umaskcmd(int, char **) FAST_FUNC;
8821 static int unsetcmd(int, char **) FAST_FUNC;
8822 static int ulimitcmd(int, char **) FAST_FUNC;
8824 #define BUILTIN_NOSPEC "0"
8825 #define BUILTIN_SPECIAL "1"
8826 #define BUILTIN_REGULAR "2"
8827 #define BUILTIN_SPEC_REG "3"
8828 #define BUILTIN_ASSIGN "4"
8829 #define BUILTIN_SPEC_ASSG "5"
8830 #define BUILTIN_REG_ASSG "6"
8831 #define BUILTIN_SPEC_REG_ASSG "7"
8833 /* Stubs for calling non-FAST_FUNC's */
8834 #if ENABLE_ASH_BUILTIN_ECHO
8835 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8837 #if ENABLE_ASH_BUILTIN_PRINTF
8838 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8840 #if ENABLE_ASH_BUILTIN_TEST
8841 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8844 /* Keep these in proper order since it is searched via bsearch() */
8845 static const struct builtincmd builtintab[] = {
8846 { BUILTIN_SPEC_REG ".", dotcmd },
8847 { BUILTIN_SPEC_REG ":", truecmd },
8848 #if ENABLE_ASH_BUILTIN_TEST
8849 { BUILTIN_REGULAR "[", testcmd },
8850 #if ENABLE_ASH_BASH_COMPAT
8851 { BUILTIN_REGULAR "[[", testcmd },
8854 #if ENABLE_ASH_ALIAS
8855 { BUILTIN_REG_ASSG "alias", aliascmd },
8858 { BUILTIN_REGULAR "bg", fg_bgcmd },
8860 { BUILTIN_SPEC_REG "break", breakcmd },
8861 { BUILTIN_REGULAR "cd", cdcmd },
8862 { BUILTIN_NOSPEC "chdir", cdcmd },
8863 #if ENABLE_ASH_CMDCMD
8864 { BUILTIN_REGULAR "command", commandcmd },
8866 { BUILTIN_SPEC_REG "continue", breakcmd },
8867 #if ENABLE_ASH_BUILTIN_ECHO
8868 { BUILTIN_REGULAR "echo", echocmd },
8870 { BUILTIN_SPEC_REG "eval", evalcmd },
8871 { BUILTIN_SPEC_REG "exec", execcmd },
8872 { BUILTIN_SPEC_REG "exit", exitcmd },
8873 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8874 { BUILTIN_REGULAR "false", falsecmd },
8876 { BUILTIN_REGULAR "fg", fg_bgcmd },
8878 #if ENABLE_ASH_GETOPTS
8879 { BUILTIN_REGULAR "getopts", getoptscmd },
8881 { BUILTIN_NOSPEC "hash", hashcmd },
8882 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8883 { BUILTIN_NOSPEC "help", helpcmd },
8886 { BUILTIN_REGULAR "jobs", jobscmd },
8887 { BUILTIN_REGULAR "kill", killcmd },
8889 #if ENABLE_SH_MATH_SUPPORT
8890 { BUILTIN_NOSPEC "let", letcmd },
8892 { BUILTIN_ASSIGN "local", localcmd },
8893 #if ENABLE_ASH_BUILTIN_PRINTF
8894 { BUILTIN_REGULAR "printf", printfcmd },
8896 { BUILTIN_NOSPEC "pwd", pwdcmd },
8897 { BUILTIN_REGULAR "read", readcmd },
8898 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8899 { BUILTIN_SPEC_REG "return", returncmd },
8900 { BUILTIN_SPEC_REG "set", setcmd },
8901 { BUILTIN_SPEC_REG "shift", shiftcmd },
8902 { BUILTIN_SPEC_REG "source", dotcmd },
8903 #if ENABLE_ASH_BUILTIN_TEST
8904 { BUILTIN_REGULAR "test", testcmd },
8906 { BUILTIN_SPEC_REG "times", timescmd },
8907 { BUILTIN_SPEC_REG "trap", trapcmd },
8908 { BUILTIN_REGULAR "true", truecmd },
8909 { BUILTIN_NOSPEC "type", typecmd },
8910 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8911 { BUILTIN_REGULAR "umask", umaskcmd },
8912 #if ENABLE_ASH_ALIAS
8913 { BUILTIN_REGULAR "unalias", unaliascmd },
8915 { BUILTIN_SPEC_REG "unset", unsetcmd },
8916 { BUILTIN_REGULAR "wait", waitcmd },
8919 /* Should match the above table! */
8920 #define COMMANDCMD (builtintab + \
8922 1 * ENABLE_ASH_BUILTIN_TEST + \
8923 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8924 1 * ENABLE_ASH_ALIAS + \
8925 1 * ENABLE_ASH_JOB_CONTROL + \
8927 #define EXECCMD (builtintab + \
8929 1 * ENABLE_ASH_BUILTIN_TEST + \
8930 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8931 1 * ENABLE_ASH_ALIAS + \
8932 1 * ENABLE_ASH_JOB_CONTROL + \
8934 1 * ENABLE_ASH_CMDCMD + \
8936 ENABLE_ASH_BUILTIN_ECHO + \
8940 * Search the table of builtin commands.
8942 static struct builtincmd *
8943 find_builtin(const char *name)
8945 struct builtincmd *bp;
8948 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8955 * Execute a simple command.
8958 isassignment(const char *p)
8960 const char *q = endofname(p);
8965 static int FAST_FUNC
8966 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8968 /* Preserve exitstatus of a previous possible redirection
8969 * as POSIX mandates */
8970 return back_exitstatus;
8973 evalcommand(union node *cmd, int flags)
8975 static const struct builtincmd null_bltin = {
8976 "\0\0", bltincmd /* why three NULs? */
8978 struct stackmark smark;
8980 struct arglist arglist;
8981 struct arglist varlist;
8984 const struct strlist *sp;
8985 struct cmdentry cmdentry;
8992 struct builtincmd *bcmd;
8993 smallint cmd_is_exec;
8994 smallint pseudovarflag = 0;
8996 /* First expand the arguments. */
8997 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8998 setstackmark(&smark);
8999 back_exitstatus = 0;
9001 cmdentry.cmdtype = CMDBUILTIN;
9002 cmdentry.u.cmd = &null_bltin;
9003 varlist.lastp = &varlist.list;
9004 *varlist.lastp = NULL;
9005 arglist.lastp = &arglist.list;
9006 *arglist.lastp = NULL;
9009 if (cmd->ncmd.args) {
9010 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9011 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9014 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9015 struct strlist **spp;
9017 spp = arglist.lastp;
9018 if (pseudovarflag && isassignment(argp->narg.text))
9019 expandarg(argp, &arglist, EXP_VARTILDE);
9021 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9023 for (sp = *spp; sp; sp = sp->next)
9027 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9028 for (sp = arglist.list; sp; sp = sp->next) {
9029 TRACE(("evalcommand arg: %s\n", sp->text));
9030 *nargv++ = sp->text;
9035 if (iflag && funcnest == 0 && argc > 0)
9036 lastarg = nargv[-1];
9039 expredir(cmd->ncmd.redirect);
9040 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9043 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9044 struct strlist **spp;
9047 spp = varlist.lastp;
9048 expandarg(argp, &varlist, EXP_VARTILDE);
9051 * Modify the command lookup path, if a PATH= assignment
9055 if (varequal(p, path))
9059 /* Print the command if xflag is set. */
9062 const char *p = " %s";
9065 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9068 for (n = 0; n < 2; n++) {
9070 fdprintf(preverrout_fd, p, sp->text);
9078 safe_write(preverrout_fd, "\n", 1);
9084 /* Now locate the command. */
9086 const char *oldpath;
9087 int cmd_flag = DO_ERR;
9092 find_command(argv[0], &cmdentry, cmd_flag, path);
9093 if (cmdentry.cmdtype == CMDUNKNOWN) {
9094 flush_stdout_stderr();
9099 /* implement bltin and command here */
9100 if (cmdentry.cmdtype != CMDBUILTIN)
9103 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9104 if (cmdentry.u.cmd == EXECCMD)
9106 #if ENABLE_ASH_CMDCMD
9107 if (cmdentry.u.cmd == COMMANDCMD) {
9109 nargv = parse_command_args(argv, &path);
9112 argc -= nargv - argv;
9114 cmd_flag |= DO_NOFUNC;
9122 /* We have a redirection error. */
9124 raise_exception(EXERROR);
9126 exitstatus = status;
9130 /* Execute the command. */
9131 switch (cmdentry.cmdtype) {
9134 #if ENABLE_FEATURE_SH_NOFORK
9135 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9136 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9138 /* find_command() encodes applet_no as (-2 - applet_no) */
9139 int applet_no = (- cmdentry.u.index - 2);
9140 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9141 listsetvar(varlist.list, VEXPORT|VSTACK);
9142 /* run <applet>_main() */
9143 exitstatus = run_nofork_applet(applet_no, argv);
9148 /* Fork off a child process if necessary. */
9149 if (!(flags & EV_EXIT) || trap[0]) {
9151 jp = makejob(/*cmd,*/ 1);
9152 if (forkshell(jp, cmd, FORK_FG) != 0) {
9153 exitstatus = waitforjob(jp);
9155 TRACE(("forked child exited with %d\n", exitstatus));
9160 listsetvar(varlist.list, VEXPORT|VSTACK);
9161 shellexec(argv, path, cmdentry.u.index);
9165 cmdenviron = varlist.list;
9167 struct strlist *list = cmdenviron;
9169 if (spclbltin > 0 || argc == 0) {
9171 if (cmd_is_exec && argc > 1)
9174 listsetvar(list, i);
9176 /* Tight loop with builtins only:
9177 * "while kill -0 $child; do true; done"
9178 * will never exit even if $child died, unless we do this
9179 * to reap the zombie and make kill detect that it's gone: */
9180 dowait(DOWAIT_NONBLOCK, NULL);
9182 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9184 int i = exception_type;
9189 exit_status = 128 + SIGINT;
9191 exit_status = 128 + pending_sig;
9192 exitstatus = exit_status;
9193 if (i == EXINT || spclbltin > 0) {
9195 longjmp(exception_handler->loc, 1);
9202 listsetvar(varlist.list, 0);
9203 /* See above for the rationale */
9204 dowait(DOWAIT_NONBLOCK, NULL);
9205 if (evalfun(cmdentry.u.func, argc, argv, flags))
9211 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9213 /* dsl: I think this is intended to be used to support
9214 * '_' in 'vi' command mode during line editing...
9215 * However I implemented that within libedit itself.
9217 setvar("_", lastarg, 0);
9219 popstackmark(&smark);
9223 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9225 char *volatile savecmdname;
9226 struct jmploc *volatile savehandler;
9227 struct jmploc jmploc;
9230 savecmdname = commandname;
9231 i = setjmp(jmploc.loc);
9234 savehandler = exception_handler;
9235 exception_handler = &jmploc;
9236 commandname = argv[0];
9238 optptr = NULL; /* initialize nextopt */
9239 exitstatus = (*cmd->builtin)(argc, argv);
9240 flush_stdout_stderr();
9242 exitstatus |= ferror(stdout);
9244 commandname = savecmdname;
9245 exception_handler = savehandler;
9251 goodname(const char *p)
9253 return !*endofname(p);
9258 * Search for a command. This is called before we fork so that the
9259 * location of the command will be available in the parent as well as
9260 * the child. The check for "goodname" is an overly conservative
9261 * check that the name will not be subject to expansion.
9264 prehash(union node *n)
9266 struct cmdentry entry;
9268 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9269 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9273 /* ============ Builtin commands
9275 * Builtin commands whose functions are closely tied to evaluation
9276 * are implemented here.
9280 * Handle break and continue commands. Break, continue, and return are
9281 * all handled by setting the evalskip flag. The evaluation routines
9282 * above all check this flag, and if it is set they start skipping
9283 * commands rather than executing them. The variable skipcount is
9284 * the number of loops to break/continue, or the number of function
9285 * levels to return. (The latter is always 1.) It should probably
9286 * be an error to break out of more loops than exist, but it isn't
9287 * in the standard shell so we don't make it one here.
9289 static int FAST_FUNC
9290 breakcmd(int argc UNUSED_PARAM, char **argv)
9292 int n = argv[1] ? number(argv[1]) : 1;
9295 ash_msg_and_raise_error(msg_illnum, argv[1]);
9299 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9306 /* ============ input.c
9308 * This implements the input routines used by the parser.
9312 INPUT_PUSH_FILE = 1,
9313 INPUT_NOFILE_OK = 2,
9316 static smallint checkkwd;
9317 /* values of checkkwd variable */
9318 #define CHKALIAS 0x1
9323 * Push a string back onto the input at this current parsefile level.
9324 * We handle aliases this way.
9326 #if !ENABLE_ASH_ALIAS
9327 #define pushstring(s, ap) pushstring(s)
9330 pushstring(char *s, struct alias *ap)
9337 if (g_parsefile->strpush) {
9338 sp = ckzalloc(sizeof(*sp));
9339 sp->prev = g_parsefile->strpush;
9341 sp = &(g_parsefile->basestrpush);
9343 g_parsefile->strpush = sp;
9344 sp->prev_string = g_parsefile->next_to_pgetc;
9345 sp->prev_left_in_line = g_parsefile->left_in_line;
9346 #if ENABLE_ASH_ALIAS
9349 ap->flag |= ALIASINUSE;
9353 g_parsefile->next_to_pgetc = s;
9354 g_parsefile->left_in_line = len;
9361 struct strpush *sp = g_parsefile->strpush;
9364 #if ENABLE_ASH_ALIAS
9366 if (g_parsefile->next_to_pgetc[-1] == ' '
9367 || g_parsefile->next_to_pgetc[-1] == '\t'
9369 checkkwd |= CHKALIAS;
9371 if (sp->string != sp->ap->val) {
9374 sp->ap->flag &= ~ALIASINUSE;
9375 if (sp->ap->flag & ALIASDEAD) {
9376 unalias(sp->ap->name);
9380 g_parsefile->next_to_pgetc = sp->prev_string;
9381 g_parsefile->left_in_line = sp->prev_left_in_line;
9382 g_parsefile->strpush = sp->prev;
9383 if (sp != &(g_parsefile->basestrpush))
9388 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9389 //it peeks whether it is &>, and then pushes back both chars.
9390 //This function needs to save last *next_to_pgetc to buf[0]
9391 //to make two pungetc() reliable. Currently,
9392 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9397 char *buf = g_parsefile->buf;
9399 g_parsefile->next_to_pgetc = buf;
9400 #if ENABLE_FEATURE_EDITING
9402 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9403 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9405 #if ENABLE_FEATURE_TAB_COMPLETION
9406 line_input_state->path_lookup = pathval();
9408 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9410 /* Ctrl+C pressed */
9419 if (nr < 0 && errno == 0) {
9420 /* Ctrl+D pressed */
9425 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9429 /* nonblock_safe_read() handles this problem */
9431 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9432 int flags = fcntl(0, F_GETFL);
9433 if (flags >= 0 && (flags & O_NONBLOCK)) {
9434 flags &= ~O_NONBLOCK;
9435 if (fcntl(0, F_SETFL, flags) >= 0) {
9436 out2str("sh: turning off NDELAY mode\n");
9447 * Refill the input buffer and return the next input character:
9449 * 1) If a string was pushed back on the input, pop it;
9450 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9451 * or we are reading from a string so we can't refill the buffer,
9453 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9454 * 4) Process input up to the next newline, deleting nul characters.
9456 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9457 #define pgetc_debug(...) ((void)0)
9464 while (g_parsefile->strpush) {
9465 #if ENABLE_ASH_ALIAS
9466 if (g_parsefile->left_in_line == -1
9467 && g_parsefile->strpush->ap
9468 && g_parsefile->next_to_pgetc[-1] != ' '
9469 && g_parsefile->next_to_pgetc[-1] != '\t'
9471 pgetc_debug("preadbuffer PEOA");
9476 /* try "pgetc" now: */
9477 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9478 g_parsefile->left_in_line,
9479 g_parsefile->next_to_pgetc,
9480 g_parsefile->next_to_pgetc);
9481 if (--g_parsefile->left_in_line >= 0)
9482 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9484 /* on both branches above g_parsefile->left_in_line < 0.
9485 * "pgetc" needs refilling.
9488 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9489 * pungetc() may increment it a few times.
9490 * Assuming it won't increment it to less than -90.
9492 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9493 pgetc_debug("preadbuffer PEOF1");
9494 /* even in failure keep left_in_line and next_to_pgetc
9495 * in lock step, for correct multi-layer pungetc.
9496 * left_in_line was decremented before preadbuffer(),
9497 * must inc next_to_pgetc: */
9498 g_parsefile->next_to_pgetc++;
9502 more = g_parsefile->left_in_buffer;
9504 flush_stdout_stderr();
9508 /* don't try reading again */
9509 g_parsefile->left_in_line = -99;
9510 pgetc_debug("preadbuffer PEOF2");
9511 g_parsefile->next_to_pgetc++;
9516 /* Find out where's the end of line.
9517 * Set g_parsefile->left_in_line
9518 * and g_parsefile->left_in_buffer acordingly.
9519 * NUL chars are deleted.
9521 q = g_parsefile->next_to_pgetc;
9529 memmove(q, q + 1, more);
9533 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9539 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9540 if (g_parsefile->left_in_line < 0)
9545 g_parsefile->left_in_buffer = more;
9550 out2str(g_parsefile->next_to_pgetc);
9554 pgetc_debug("preadbuffer at %d:%p'%s'",
9555 g_parsefile->left_in_line,
9556 g_parsefile->next_to_pgetc,
9557 g_parsefile->next_to_pgetc);
9558 return (unsigned char)*g_parsefile->next_to_pgetc++;
9561 #define pgetc_as_macro() \
9562 (--g_parsefile->left_in_line >= 0 \
9563 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9570 pgetc_debug("pgetc_fast at %d:%p'%s'",
9571 g_parsefile->left_in_line,
9572 g_parsefile->next_to_pgetc,
9573 g_parsefile->next_to_pgetc);
9574 return pgetc_as_macro();
9577 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9578 #define pgetc_fast() pgetc()
9580 #define pgetc_fast() pgetc_as_macro()
9584 * Same as pgetc(), but ignores PEOA.
9586 #if ENABLE_ASH_ALIAS
9592 pgetc_debug("pgetc_fast at %d:%p'%s'",
9593 g_parsefile->left_in_line,
9594 g_parsefile->next_to_pgetc,
9595 g_parsefile->next_to_pgetc);
9597 } while (c == PEOA);
9601 #define pgetc2() pgetc()
9605 * Read a line from the script.
9608 pfgets(char *line, int len)
9614 while (--nleft > 0) {
9630 * Undo the last call to pgetc. Only one character may be pushed back.
9631 * PEOF may be pushed back.
9636 g_parsefile->left_in_line++;
9637 g_parsefile->next_to_pgetc--;
9638 pgetc_debug("pushed back to %d:%p'%s'",
9639 g_parsefile->left_in_line,
9640 g_parsefile->next_to_pgetc,
9641 g_parsefile->next_to_pgetc);
9645 * To handle the "." command, a stack of input files is used. Pushfile
9646 * adds a new entry to the stack and popfile restores the previous level.
9651 struct parsefile *pf;
9653 pf = ckzalloc(sizeof(*pf));
9654 pf->prev = g_parsefile;
9656 /*pf->strpush = NULL; - ckzalloc did it */
9657 /*pf->basestrpush.prev = NULL;*/
9664 struct parsefile *pf = g_parsefile;
9672 g_parsefile = pf->prev;
9678 * Return to top level.
9683 while (g_parsefile != &basepf)
9688 * Close the file(s) that the shell is reading commands from. Called
9689 * after a fork is done.
9695 if (g_parsefile->fd > 0) {
9696 close(g_parsefile->fd);
9697 g_parsefile->fd = 0;
9702 * Like setinputfile, but takes an open file descriptor. Call this with
9706 setinputfd(int fd, int push)
9708 close_on_exec_on(fd);
9711 g_parsefile->buf = NULL;
9713 g_parsefile->fd = fd;
9714 if (g_parsefile->buf == NULL)
9715 g_parsefile->buf = ckmalloc(IBUFSIZ);
9716 g_parsefile->left_in_buffer = 0;
9717 g_parsefile->left_in_line = 0;
9718 g_parsefile->linno = 1;
9722 * Set the input to take input from a file. If push is set, push the
9723 * old input onto the stack first.
9726 setinputfile(const char *fname, int flags)
9732 fd = open(fname, O_RDONLY);
9734 if (flags & INPUT_NOFILE_OK)
9736 ash_msg_and_raise_error("can't open '%s'", fname);
9739 fd2 = copyfd(fd, 10);
9742 ash_msg_and_raise_error("out of file descriptors");
9745 setinputfd(fd, flags & INPUT_PUSH_FILE);
9752 * Like setinputfile, but takes input from a string.
9755 setinputstring(char *string)
9759 g_parsefile->next_to_pgetc = string;
9760 g_parsefile->left_in_line = strlen(string);
9761 g_parsefile->buf = NULL;
9762 g_parsefile->linno = 1;
9767 /* ============ mail.c
9769 * Routines to check for mail.
9774 #define MAXMBOXES 10
9776 /* times of mailboxes */
9777 static time_t mailtime[MAXMBOXES];
9778 /* Set if MAIL or MAILPATH is changed. */
9779 static smallint mail_var_path_changed;
9782 * Print appropriate message(s) if mail has arrived.
9783 * If mail_var_path_changed is set,
9784 * then the value of MAIL has mail_var_path_changed,
9785 * so we just update the values.
9794 struct stackmark smark;
9797 setstackmark(&smark);
9798 mpath = mpathset() ? mpathval() : mailval();
9799 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9800 p = path_advance(&mpath, nullstr);
9805 for (q = p; *q; q++)
9811 q[-1] = '\0'; /* delete trailing '/' */
9812 if (stat(p, &statb) < 0) {
9816 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9819 pathopt ? pathopt : "you have mail"
9822 *mtp = statb.st_mtime;
9824 mail_var_path_changed = 0;
9825 popstackmark(&smark);
9828 static void FAST_FUNC
9829 changemail(const char *val UNUSED_PARAM)
9831 mail_var_path_changed = 1;
9834 #endif /* ASH_MAIL */
9837 /* ============ ??? */
9840 * Set the shell parameters.
9843 setparam(char **argv)
9849 for (nparam = 0; argv[nparam]; nparam++)
9851 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9853 *ap++ = ckstrdup(*argv++);
9856 freeparam(&shellparam);
9857 shellparam.malloced = 1;
9858 shellparam.nparam = nparam;
9859 shellparam.p = newparam;
9860 #if ENABLE_ASH_GETOPTS
9861 shellparam.optind = 1;
9862 shellparam.optoff = -1;
9867 * Process shell options. The global variable argptr contains a pointer
9868 * to the argument list; we advance it past the options.
9870 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9871 * For a non-interactive shell, an error condition encountered
9872 * by a special built-in ... shall cause the shell to write a diagnostic message
9873 * to standard error and exit as shown in the following table:
9874 * Error Special Built-In
9876 * Utility syntax error (option or operand error) Shall exit
9878 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9879 * we see that bash does not do that (set "finishes" with error code 1 instead,
9880 * and shell continues), and people rely on this behavior!
9882 * set -o barfoo 2>/dev/null
9885 * Oh well. Let's mimic that.
9888 plus_minus_o(char *name, int val)
9893 for (i = 0; i < NOPTS; i++) {
9894 if (strcmp(name, optnames(i)) == 0) {
9899 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9902 for (i = 0; i < NOPTS; i++) {
9904 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9906 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9912 setoption(int flag, int val)
9916 for (i = 0; i < NOPTS; i++) {
9917 if (optletters(i) == flag) {
9922 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9926 options(int cmdline)
9934 while ((p = *argptr) != NULL) {
9936 if (c != '-' && c != '+')
9939 val = 0; /* val = 0 if c == '+' */
9942 if (p[0] == '\0' || LONE_DASH(p)) {
9944 /* "-" means turn off -x and -v */
9947 /* "--" means reset params */
9948 else if (*argptr == NULL)
9951 break; /* "-" or "--" terminates options */
9954 /* first char was + or - */
9955 while ((c = *p++) != '\0') {
9956 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9957 if (c == 'c' && cmdline) {
9958 minusc = p; /* command is after shell args */
9959 } else if (c == 'o') {
9960 if (plus_minus_o(*argptr, val)) {
9961 /* it already printed err message */
9962 return 1; /* error */
9966 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9968 /* bash does not accept +-login, we also won't */
9969 } else if (cmdline && val && (c == '-')) { /* long options */
9970 if (strcmp(p, "login") == 0)
9982 * The shift builtin command.
9984 static int FAST_FUNC
9985 shiftcmd(int argc UNUSED_PARAM, char **argv)
9992 n = number(argv[1]);
9993 if (n > shellparam.nparam)
9994 n = 0; /* bash compat, was = shellparam.nparam; */
9996 shellparam.nparam -= n;
9997 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9998 if (shellparam.malloced)
10001 ap2 = shellparam.p;
10002 while ((*ap2++ = *ap1++) != NULL)
10004 #if ENABLE_ASH_GETOPTS
10005 shellparam.optind = 1;
10006 shellparam.optoff = -1;
10013 * POSIX requires that 'set' (but not export or readonly) output the
10014 * variables in lexicographic order - by the locale's collating order (sigh).
10015 * Maybe we could keep them in an ordered balanced binary tree
10016 * instead of hashed lists.
10017 * For now just roll 'em through qsort for printing...
10020 showvars(const char *sep_prefix, int on, int off)
10023 char **ep, **epend;
10025 ep = listvars(on, off, &epend);
10026 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10028 sep = *sep_prefix ? " " : sep_prefix;
10030 for (; ep < epend; ep++) {
10034 p = strchrnul(*ep, '=');
10037 q = single_quote(++p);
10038 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10044 * The set command builtin.
10046 static int FAST_FUNC
10047 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10052 return showvars(nullstr, 0, VUNSET);
10055 if (!options(0)) { /* if no parse error... */
10058 if (*argptr != NULL) {
10066 #if ENABLE_ASH_RANDOM_SUPPORT
10067 static void FAST_FUNC
10068 change_random(const char *value)
10072 if (value == NULL) {
10073 /* "get", generate */
10074 t = next_random(&random_gen);
10075 /* set without recursion */
10076 setvar(vrandom.text, utoa(t), VNOFUNC);
10077 vrandom.flags &= ~VNOFUNC;
10080 t = strtoul(value, NULL, 10);
10081 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10086 #if ENABLE_ASH_GETOPTS
10088 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10097 if (*param_optind < 1)
10099 optnext = optfirst + *param_optind - 1;
10101 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10104 p = optnext[-1] + *optoff;
10105 if (p == NULL || *p == '\0') {
10106 /* Current word is done, advance */
10108 if (p == NULL || *p != '-' || *++p == '\0') {
10115 if (LONE_DASH(p)) /* check for "--" */
10120 for (q = optstr; *q != c;) {
10122 if (optstr[0] == ':') {
10125 err |= setvarsafe("OPTARG", s, 0);
10127 fprintf(stderr, "Illegal option -%c\n", c);
10128 unsetvar("OPTARG");
10138 if (*p == '\0' && (p = *optnext) == NULL) {
10139 if (optstr[0] == ':') {
10142 err |= setvarsafe("OPTARG", s, 0);
10145 fprintf(stderr, "No arg for -%c option\n", c);
10146 unsetvar("OPTARG");
10154 err |= setvarsafe("OPTARG", p, 0);
10157 err |= setvarsafe("OPTARG", nullstr, 0);
10159 *optoff = p ? p - *(optnext - 1) : -1;
10160 *param_optind = optnext - optfirst + 1;
10161 fmtstr(s, sizeof(s), "%d", *param_optind);
10162 err |= setvarsafe("OPTIND", s, VNOFUNC);
10165 err |= setvarsafe(optvar, s, 0);
10169 flush_stdout_stderr();
10170 raise_exception(EXERROR);
10176 * The getopts builtin. Shellparam.optnext points to the next argument
10177 * to be processed. Shellparam.optptr points to the next character to
10178 * be processed in the current argument. If shellparam.optnext is NULL,
10179 * then it's the first time getopts has been called.
10181 static int FAST_FUNC
10182 getoptscmd(int argc, char **argv)
10187 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10189 optbase = shellparam.p;
10190 if (shellparam.optind > shellparam.nparam + 1) {
10191 shellparam.optind = 1;
10192 shellparam.optoff = -1;
10195 optbase = &argv[3];
10196 if (shellparam.optind > argc - 2) {
10197 shellparam.optind = 1;
10198 shellparam.optoff = -1;
10202 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10203 &shellparam.optoff);
10205 #endif /* ASH_GETOPTS */
10208 /* ============ Shell parser */
10211 struct heredoc *next; /* next here document in list */
10212 union node *here; /* redirection node */
10213 char *eofmark; /* string indicating end of input */
10214 smallint striptabs; /* if set, strip leading tabs */
10217 static smallint tokpushback; /* last token pushed back */
10218 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10219 static smallint quoteflag; /* set if (part of) last token was quoted */
10220 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10221 static struct heredoc *heredoclist; /* list of here documents to read */
10222 static char *wordtext; /* text of last word returned by readtoken */
10223 static struct nodelist *backquotelist;
10224 static union node *redirnode;
10225 static struct heredoc *heredoc;
10228 * Called when an unexpected token is read during the parse. The argument
10229 * is the token that is expected, or -1 if more than one type of token can
10230 * occur at this point.
10232 static void raise_error_unexpected_syntax(int) NORETURN;
10234 raise_error_unexpected_syntax(int token)
10239 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10241 sprintf(msg + l, " (expecting %s)", tokname(token));
10242 raise_error_syntax(msg);
10246 #define EOFMARKLEN 79
10248 /* parsing is heavily cross-recursive, need these forward decls */
10249 static union node *andor(void);
10250 static union node *pipeline(void);
10251 static union node *parse_command(void);
10252 static void parseheredoc(void);
10253 static char peektoken(void);
10254 static int readtoken(void);
10256 static union node *
10259 union node *n1, *n2, *n3;
10262 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10263 if (nlflag == 2 && peektoken())
10269 if (tok == TBACKGND) {
10270 if (n2->type == NPIPE) {
10271 n2->npipe.pipe_backgnd = 1;
10273 if (n2->type != NREDIR) {
10274 n3 = stzalloc(sizeof(struct nredir));
10276 /*n3->nredir.redirect = NULL; - stzalloc did it */
10279 n2->type = NBACKGND;
10285 n3 = stzalloc(sizeof(struct nbinary));
10287 n3->nbinary.ch1 = n1;
10288 n3->nbinary.ch2 = n2;
10304 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10312 pungetc(); /* push back EOF on input */
10316 raise_error_unexpected_syntax(-1);
10323 static union node *
10326 union node *n1, *n2, *n3;
10334 } else if (t == TOR) {
10340 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10342 n3 = stzalloc(sizeof(struct nbinary));
10344 n3->nbinary.ch1 = n1;
10345 n3->nbinary.ch2 = n2;
10350 static union node *
10353 union node *n1, *n2, *pipenode;
10354 struct nodelist *lp, *prev;
10358 TRACE(("pipeline: entered\n"));
10359 if (readtoken() == TNOT) {
10361 checkkwd = CHKKWD | CHKALIAS;
10364 n1 = parse_command();
10365 if (readtoken() == TPIPE) {
10366 pipenode = stzalloc(sizeof(struct npipe));
10367 pipenode->type = NPIPE;
10368 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10369 lp = stzalloc(sizeof(struct nodelist));
10370 pipenode->npipe.cmdlist = lp;
10374 lp = stzalloc(sizeof(struct nodelist));
10375 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10376 lp->n = parse_command();
10378 } while (readtoken() == TPIPE);
10384 n2 = stzalloc(sizeof(struct nnot));
10392 static union node *
10397 n = stzalloc(sizeof(struct narg));
10399 /*n->narg.next = NULL; - stzalloc did it */
10400 n->narg.text = wordtext;
10401 n->narg.backquote = backquotelist;
10406 fixredir(union node *n, const char *text, int err)
10410 TRACE(("Fix redir %s %d\n", text, err));
10412 n->ndup.vname = NULL;
10414 fd = bb_strtou(text, NULL, 10);
10415 if (!errno && fd >= 0)
10416 n->ndup.dupfd = fd;
10417 else if (LONE_DASH(text))
10418 n->ndup.dupfd = -1;
10421 raise_error_syntax("bad fd number");
10422 n->ndup.vname = makename();
10427 * Returns true if the text contains nothing to expand (no dollar signs
10431 noexpand(const char *text)
10435 while ((c = *text++) != '\0') {
10436 if (c == CTLQUOTEMARK)
10440 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10449 union node *n = redirnode;
10451 if (readtoken() != TWORD)
10452 raise_error_unexpected_syntax(-1);
10453 if (n->type == NHERE) {
10454 struct heredoc *here = heredoc;
10458 if (quoteflag == 0)
10460 TRACE(("Here document %d\n", n->type));
10461 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10462 raise_error_syntax("illegal eof marker for << redirection");
10463 rmescapes(wordtext, 0);
10464 here->eofmark = wordtext;
10466 if (heredoclist == NULL)
10467 heredoclist = here;
10469 for (p = heredoclist; p->next; p = p->next)
10473 } else if (n->type == NTOFD || n->type == NFROMFD) {
10474 fixredir(n, wordtext, 0);
10476 n->nfile.fname = makename();
10480 static union node *
10483 union node *args, **app;
10484 union node *n = NULL;
10485 union node *vars, **vpp;
10486 union node **rpp, *redir;
10488 #if ENABLE_ASH_BASH_COMPAT
10489 smallint double_brackets_flag = 0;
10499 savecheckkwd = CHKALIAS;
10502 checkkwd = savecheckkwd;
10505 #if ENABLE_ASH_BASH_COMPAT
10506 case TAND: /* "&&" */
10507 case TOR: /* "||" */
10508 if (!double_brackets_flag) {
10512 wordtext = (char *) (t == TAND ? "-a" : "-o");
10515 n = stzalloc(sizeof(struct narg));
10517 /*n->narg.next = NULL; - stzalloc did it */
10518 n->narg.text = wordtext;
10519 #if ENABLE_ASH_BASH_COMPAT
10520 if (strcmp("[[", wordtext) == 0)
10521 double_brackets_flag = 1;
10522 else if (strcmp("]]", wordtext) == 0)
10523 double_brackets_flag = 0;
10525 n->narg.backquote = backquotelist;
10526 if (savecheckkwd && isassignment(wordtext)) {
10528 vpp = &n->narg.next;
10531 app = &n->narg.next;
10536 *rpp = n = redirnode;
10537 rpp = &n->nfile.next;
10538 parsefname(); /* read name of redirection file */
10541 if (args && app == &args->narg.next
10544 struct builtincmd *bcmd;
10547 /* We have a function */
10548 if (readtoken() != TRP)
10549 raise_error_unexpected_syntax(TRP);
10550 name = n->narg.text;
10551 if (!goodname(name)
10552 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10554 raise_error_syntax("bad function name");
10557 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10558 n->narg.next = parse_command();
10571 n = stzalloc(sizeof(struct ncmd));
10573 n->ncmd.args = args;
10574 n->ncmd.assign = vars;
10575 n->ncmd.redirect = redir;
10579 static union node *
10580 parse_command(void)
10582 union node *n1, *n2;
10583 union node *ap, **app;
10584 union node *cp, **cpp;
10585 union node *redir, **rpp;
10592 switch (readtoken()) {
10594 raise_error_unexpected_syntax(-1);
10597 n1 = stzalloc(sizeof(struct nif));
10599 n1->nif.test = list(0);
10600 if (readtoken() != TTHEN)
10601 raise_error_unexpected_syntax(TTHEN);
10602 n1->nif.ifpart = list(0);
10604 while (readtoken() == TELIF) {
10605 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10606 n2 = n2->nif.elsepart;
10608 n2->nif.test = list(0);
10609 if (readtoken() != TTHEN)
10610 raise_error_unexpected_syntax(TTHEN);
10611 n2->nif.ifpart = list(0);
10613 if (lasttoken == TELSE)
10614 n2->nif.elsepart = list(0);
10616 n2->nif.elsepart = NULL;
10624 n1 = stzalloc(sizeof(struct nbinary));
10625 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10626 n1->nbinary.ch1 = list(0);
10629 TRACE(("expecting DO got %s %s\n", tokname(got),
10630 got == TWORD ? wordtext : ""));
10631 raise_error_unexpected_syntax(TDO);
10633 n1->nbinary.ch2 = list(0);
10638 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10639 raise_error_syntax("bad for loop variable");
10640 n1 = stzalloc(sizeof(struct nfor));
10642 n1->nfor.var = wordtext;
10643 checkkwd = CHKKWD | CHKALIAS;
10644 if (readtoken() == TIN) {
10646 while (readtoken() == TWORD) {
10647 n2 = stzalloc(sizeof(struct narg));
10649 /*n2->narg.next = NULL; - stzalloc did it */
10650 n2->narg.text = wordtext;
10651 n2->narg.backquote = backquotelist;
10653 app = &n2->narg.next;
10656 n1->nfor.args = ap;
10657 if (lasttoken != TNL && lasttoken != TSEMI)
10658 raise_error_unexpected_syntax(-1);
10660 n2 = stzalloc(sizeof(struct narg));
10662 /*n2->narg.next = NULL; - stzalloc did it */
10663 n2->narg.text = (char *)dolatstr;
10664 /*n2->narg.backquote = NULL;*/
10665 n1->nfor.args = n2;
10667 * Newline or semicolon here is optional (but note
10668 * that the original Bourne shell only allowed NL).
10670 if (lasttoken != TNL && lasttoken != TSEMI)
10673 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10674 if (readtoken() != TDO)
10675 raise_error_unexpected_syntax(TDO);
10676 n1->nfor.body = list(0);
10680 n1 = stzalloc(sizeof(struct ncase));
10682 if (readtoken() != TWORD)
10683 raise_error_unexpected_syntax(TWORD);
10684 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10686 /*n2->narg.next = NULL; - stzalloc did it */
10687 n2->narg.text = wordtext;
10688 n2->narg.backquote = backquotelist;
10690 checkkwd = CHKKWD | CHKALIAS;
10691 } while (readtoken() == TNL);
10692 if (lasttoken != TIN)
10693 raise_error_unexpected_syntax(TIN);
10694 cpp = &n1->ncase.cases;
10696 checkkwd = CHKNL | CHKKWD;
10698 while (t != TESAC) {
10699 if (lasttoken == TLP)
10701 *cpp = cp = stzalloc(sizeof(struct nclist));
10703 app = &cp->nclist.pattern;
10705 *app = ap = stzalloc(sizeof(struct narg));
10707 /*ap->narg.next = NULL; - stzalloc did it */
10708 ap->narg.text = wordtext;
10709 ap->narg.backquote = backquotelist;
10710 if (readtoken() != TPIPE)
10712 app = &ap->narg.next;
10715 //ap->narg.next = NULL;
10716 if (lasttoken != TRP)
10717 raise_error_unexpected_syntax(TRP);
10718 cp->nclist.body = list(2);
10720 cpp = &cp->nclist.next;
10722 checkkwd = CHKNL | CHKKWD;
10726 raise_error_unexpected_syntax(TENDCASE);
10733 n1 = stzalloc(sizeof(struct nredir));
10734 n1->type = NSUBSHELL;
10735 n1->nredir.n = list(0);
10736 /*n1->nredir.redirect = NULL; - stzalloc did it */
10746 return simplecmd();
10749 if (readtoken() != t)
10750 raise_error_unexpected_syntax(t);
10753 /* Now check for redirection which may follow command */
10754 checkkwd = CHKKWD | CHKALIAS;
10756 while (readtoken() == TREDIR) {
10757 *rpp = n2 = redirnode;
10758 rpp = &n2->nfile.next;
10764 if (n1->type != NSUBSHELL) {
10765 n2 = stzalloc(sizeof(struct nredir));
10770 n1->nredir.redirect = redir;
10775 #if ENABLE_ASH_BASH_COMPAT
10776 static int decode_dollar_squote(void)
10778 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10784 p = strchr(C_escapes, c);
10789 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10793 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10795 } else if (c == 'x') { /* \xHH */
10799 } while (isxdigit(c) && --cnt);
10801 if (cnt == 3) { /* \x but next char is "bad" */
10805 } else { /* simple seq like \\ or \t */
10810 c = bb_process_escape_sequence((void*)&p);
10811 } else { /* unrecognized "\z": print both chars unless ' or " */
10812 if (c != '\'' && c != '"') {
10814 c |= 0x100; /* "please encode \, then me" */
10822 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10823 * is not NULL, read a here document. In the latter case, eofmark is the
10824 * word which marks the end of the document and striptabs is true if
10825 * leading tabs should be stripped from the document. The argument c
10826 * is the first character of the input token or document.
10828 * Because C does not have internal subroutines, I have simulated them
10829 * using goto's to implement the subroutine linkage. The following macros
10830 * will run code that appears at the end of readtoken1.
10832 #define CHECKEND() {goto checkend; checkend_return:;}
10833 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10834 #define PARSESUB() {goto parsesub; parsesub_return:;}
10835 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10836 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10837 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10839 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10841 /* NB: syntax parameter fits into smallint */
10842 /* c parameter is an unsigned char or PEOF or PEOA */
10845 char line[EOFMARKLEN + 1];
10846 struct nodelist *bqlist;
10850 smallint prevsyntax; /* syntax before arithmetic */
10851 #if ENABLE_ASH_EXPAND_PRMT
10852 smallint pssyntax; /* we are expanding a prompt string */
10854 int varnest; /* levels of variables expansion */
10855 int arinest; /* levels of arithmetic expansion */
10856 int parenlevel; /* levels of parens in arithmetic */
10857 int dqvarnest; /* levels of variables expansion within double quotes */
10859 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10862 /* Avoid longjmp clobbering */
10868 (void) &parenlevel;
10871 (void) &prevsyntax;
10874 startlinno = g_parsefile->linno;
10879 #if ENABLE_ASH_EXPAND_PRMT
10880 pssyntax = (syntax == PSSYNTAX);
10884 dblquote = (syntax == DQSYNTAX);
10890 STARTSTACKSTR(out);
10892 /* For each line, until end of word */
10894 CHECKEND(); /* set c to PEOF if at end of here document */
10895 for (;;) { /* until end of line or end of word */
10896 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10897 switch (SIT(c, syntax)) {
10898 case CNL: /* '\n' */
10899 if (syntax == BASESYNTAX)
10900 goto endword; /* exit outer loop */
10902 g_parsefile->linno++;
10906 goto loop; /* continue outer loop */
10911 if (eofmark == NULL || dblquote)
10912 USTPUTC(CTLESC, out);
10913 #if ENABLE_ASH_BASH_COMPAT
10914 if (c == '\\' && bash_dollar_squote) {
10915 c = decode_dollar_squote();
10917 USTPUTC('\\', out);
10918 c = (unsigned char)c;
10924 case CBACK: /* backslash */
10927 USTPUTC(CTLESC, out);
10928 USTPUTC('\\', out);
10930 } else if (c == '\n') {
10934 #if ENABLE_ASH_EXPAND_PRMT
10935 if (c == '$' && pssyntax) {
10936 USTPUTC(CTLESC, out);
10937 USTPUTC('\\', out);
10940 if (dblquote && c != '\\'
10941 && c != '`' && c != '$'
10942 && (c != '"' || eofmark != NULL)
10944 USTPUTC(CTLESC, out);
10945 USTPUTC('\\', out);
10947 if (SIT(c, SQSYNTAX) == CCTL)
10948 USTPUTC(CTLESC, out);
10956 if (eofmark == NULL) {
10957 USTPUTC(CTLQUOTEMARK, out);
10965 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10966 if (eofmark != NULL && arinest == 0
10971 if (dqvarnest == 0) {
10972 syntax = BASESYNTAX;
10979 case CVAR: /* '$' */
10980 PARSESUB(); /* parse substitution */
10982 case CENDVAR: /* '}' */
10985 if (dqvarnest > 0) {
10988 USTPUTC(CTLENDVAR, out);
10993 #if ENABLE_SH_MATH_SUPPORT
10994 case CLP: /* '(' in arithmetic */
10998 case CRP: /* ')' in arithmetic */
10999 if (parenlevel > 0) {
11003 if (pgetc() == ')') {
11004 if (--arinest == 0) {
11005 USTPUTC(CTLENDARI, out);
11006 syntax = prevsyntax;
11007 dblquote = (syntax == DQSYNTAX);
11012 * unbalanced parens
11013 * (don't 2nd guess - no error)
11021 case CBQUOTE: /* '`' */
11025 goto endword; /* exit outer loop */
11029 if (varnest == 0) {
11030 #if ENABLE_ASH_BASH_COMPAT
11032 if (pgetc() == '>')
11033 c = 0x100 + '>'; /* flag &> */
11037 goto endword; /* exit outer loop */
11039 #if ENABLE_ASH_ALIAS
11049 #if ENABLE_SH_MATH_SUPPORT
11050 if (syntax == ARISYNTAX)
11051 raise_error_syntax("missing '))'");
11053 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11054 raise_error_syntax("unterminated quoted string");
11055 if (varnest != 0) {
11056 startlinno = g_parsefile->linno;
11058 raise_error_syntax("missing '}'");
11060 USTPUTC('\0', out);
11061 len = out - (char *)stackblock();
11062 out = stackblock();
11063 if (eofmark == NULL) {
11064 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11067 if (isdigit_str9(out)) {
11068 PARSEREDIR(); /* passed as params: out, c */
11069 lasttoken = TREDIR;
11072 /* else: non-number X seen, interpret it
11073 * as "NNNX>file" = "NNNX >file" */
11077 quoteflag = quotef;
11078 backquotelist = bqlist;
11079 grabstackblock(len);
11083 /* end of readtoken routine */
11086 * Check to see whether we are at the end of the here document. When this
11087 * is called, c is set to the first character of the next input line. If
11088 * we are at the end of the here document, this routine sets the c to PEOF.
11092 #if ENABLE_ASH_ALIAS
11098 while (c == '\t') {
11102 if (c == *eofmark) {
11103 if (pfgets(line, sizeof(line)) != NULL) {
11107 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11109 if (*p == '\n' && *q == '\0') {
11111 g_parsefile->linno++;
11112 needprompt = doprompt;
11114 pushstring(line, NULL);
11119 goto checkend_return;
11123 * Parse a redirection operator. The variable "out" points to a string
11124 * specifying the fd to be redirected. The variable "c" contains the
11125 * first character of the redirection operator.
11128 /* out is already checked to be a valid number or "" */
11129 int fd = (*out == '\0' ? -1 : atoi(out));
11132 np = stzalloc(sizeof(struct nfile));
11137 np->type = NAPPEND;
11139 np->type = NCLOBBER;
11142 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11148 #if ENABLE_ASH_BASH_COMPAT
11149 else if (c == 0x100 + '>') { /* this flags &> redirection */
11151 pgetc(); /* this is '>', no need to check */
11155 else { /* c == '<' */
11156 /*np->nfile.fd = 0; - stzalloc did it */
11160 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11161 np = stzalloc(sizeof(struct nhere));
11162 /*np->nfile.fd = 0; - stzalloc did it */
11165 heredoc = stzalloc(sizeof(struct heredoc));
11166 heredoc->here = np;
11169 heredoc->striptabs = 1;
11171 /*heredoc->striptabs = 0; - stzalloc did it */
11177 np->type = NFROMFD;
11181 np->type = NFROMTO;
11193 goto parseredir_return;
11197 * Parse a substitution. At this point, we have read the dollar sign
11198 * and nothing else.
11201 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11202 * (assuming ascii char codes, as the original implementation did) */
11203 #define is_special(c) \
11204 (((unsigned)(c) - 33 < 32) \
11205 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11207 unsigned char subtype;
11211 static const char types[] ALIGN1 = "}-+?=";
11214 if (c > 255 /* PEOA or PEOF */
11215 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11217 #if ENABLE_ASH_BASH_COMPAT
11219 bash_dollar_squote = 1;
11224 } else if (c == '(') { /* $(command) or $((arith)) */
11225 if (pgetc() == '(') {
11226 #if ENABLE_SH_MATH_SUPPORT
11229 raise_error_syntax("you disabled math support for $((arith)) syntax");
11236 USTPUTC(CTLVAR, out);
11237 typeloc = out - (char *)stackblock();
11238 USTPUTC(VSNORMAL, out);
11239 subtype = VSNORMAL;
11247 subtype = VSLENGTH;
11251 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11255 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11256 } else if (isdigit(c)) {
11260 } while (isdigit(c));
11261 } else if (is_special(c)) {
11266 raise_error_syntax("bad substitution");
11268 if (c != '}' && subtype == VSLENGTH)
11273 if (subtype == 0) {
11277 #if ENABLE_ASH_BASH_COMPAT
11278 if (c == ':' || c == '$' || isdigit(c)) {
11280 subtype = VSSUBSTR;
11287 p = strchr(types, c);
11290 subtype = p - types + VSNORMAL;
11295 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11303 #if ENABLE_ASH_BASH_COMPAT
11305 subtype = VSREPLACE;
11308 subtype++; /* VSREPLACEALL */
11317 if (dblquote || arinest)
11319 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11320 if (subtype != VSNORMAL) {
11322 if (dblquote || arinest) {
11327 goto parsesub_return;
11331 * Called to parse command substitutions. Newstyle is set if the command
11332 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11333 * list of commands (passed by reference), and savelen is the number of
11334 * characters on the top of the stack which must be preserved.
11337 struct nodelist **nlpp;
11340 char *volatile str;
11341 struct jmploc jmploc;
11342 struct jmploc *volatile savehandler;
11344 smallint saveprompt = 0;
11347 (void) &saveprompt;
11349 savepbq = parsebackquote;
11350 if (setjmp(jmploc.loc)) {
11352 parsebackquote = 0;
11353 exception_handler = savehandler;
11354 longjmp(exception_handler->loc, 1);
11358 savelen = out - (char *)stackblock();
11360 str = ckmalloc(savelen);
11361 memcpy(str, stackblock(), savelen);
11363 savehandler = exception_handler;
11364 exception_handler = &jmploc;
11367 /* We must read until the closing backquote, giving special
11368 treatment to some slashes, and then push the string and
11369 reread it as input, interpreting it normally. */
11376 STARTSTACKSTR(pout);
11389 g_parsefile->linno++;
11393 * If eating a newline, avoid putting
11394 * the newline into the new character
11395 * stream (via the STPUTC after the
11400 if (pc != '\\' && pc != '`' && pc != '$'
11401 && (!dblquote || pc != '"'))
11402 STPUTC('\\', pout);
11403 if (pc <= 255 /* not PEOA or PEOF */) {
11409 #if ENABLE_ASH_ALIAS
11412 startlinno = g_parsefile->linno;
11413 raise_error_syntax("EOF in backquote substitution");
11416 g_parsefile->linno++;
11417 needprompt = doprompt;
11426 STPUTC('\0', pout);
11427 psavelen = pout - (char *)stackblock();
11428 if (psavelen > 0) {
11429 pstr = grabstackstr(pout);
11430 setinputstring(pstr);
11435 nlpp = &(*nlpp)->next;
11436 *nlpp = stzalloc(sizeof(**nlpp));
11437 /* (*nlpp)->next = NULL; - stzalloc did it */
11438 parsebackquote = oldstyle;
11441 saveprompt = doprompt;
11448 doprompt = saveprompt;
11449 else if (readtoken() != TRP)
11450 raise_error_unexpected_syntax(TRP);
11455 * Start reading from old file again, ignoring any pushed back
11456 * tokens left from the backquote parsing
11461 while (stackblocksize() <= savelen)
11463 STARTSTACKSTR(out);
11465 memcpy(out, str, savelen);
11466 STADJUST(savelen, out);
11472 parsebackquote = savepbq;
11473 exception_handler = savehandler;
11474 if (arinest || dblquote)
11475 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11477 USTPUTC(CTLBACKQ, out);
11479 goto parsebackq_oldreturn;
11480 goto parsebackq_newreturn;
11483 #if ENABLE_SH_MATH_SUPPORT
11485 * Parse an arithmetic expansion (indicate start of one and set state)
11488 if (++arinest == 1) {
11489 prevsyntax = syntax;
11490 syntax = ARISYNTAX;
11491 USTPUTC(CTLARI, out);
11498 * we collapse embedded arithmetic expansion to
11499 * parenthesis, which should be equivalent
11503 goto parsearith_return;
11507 } /* end of readtoken */
11510 * Read the next input token.
11511 * If the token is a word, we set backquotelist to the list of cmds in
11512 * backquotes. We set quoteflag to true if any part of the word was
11514 * If the token is TREDIR, then we set redirnode to a structure containing
11516 * In all cases, the variable startlinno is set to the number of the line
11517 * on which the token starts.
11519 * [Change comment: here documents and internal procedures]
11520 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11521 * word parsing code into a separate routine. In this case, readtoken
11522 * doesn't need to have any internal procedures, but parseword does.
11523 * We could also make parseoperator in essence the main routine, and
11524 * have parseword (readtoken1?) handle both words and redirection.]
11526 #define NEW_xxreadtoken
11527 #ifdef NEW_xxreadtoken
11528 /* singles must be first! */
11529 static const char xxreadtoken_chars[7] ALIGN1 = {
11530 '\n', '(', ')', /* singles */
11531 '&', '|', ';', /* doubles */
11535 #define xxreadtoken_singles 3
11536 #define xxreadtoken_doubles 3
11538 static const char xxreadtoken_tokens[] ALIGN1 = {
11539 TNL, TLP, TRP, /* only single occurrence allowed */
11540 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11541 TEOF, /* corresponds to trailing nul */
11542 TAND, TOR, TENDCASE /* if double occurrence */
11557 startlinno = g_parsefile->linno;
11558 for (;;) { /* until token or start of word found */
11560 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11564 while ((c = pgetc()) != '\n' && c != PEOF)
11567 } else if (c == '\\') {
11568 if (pgetc() != '\n') {
11570 break; /* return readtoken1(...) */
11572 startlinno = ++g_parsefile->linno;
11578 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11581 g_parsefile->linno++;
11582 needprompt = doprompt;
11585 p = strchr(xxreadtoken_chars, c);
11587 break; /* return readtoken1(...) */
11589 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11591 if (cc == c) { /* double occurrence? */
11592 p += xxreadtoken_doubles + 1;
11595 #if ENABLE_ASH_BASH_COMPAT
11596 if (c == '&' && cc == '>') /* &> */
11597 break; /* return readtoken1(...) */
11602 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11607 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11609 #else /* old xxreadtoken */
11610 #define RETURN(token) return lasttoken = token
11623 startlinno = g_parsefile->linno;
11624 for (;;) { /* until token or start of word found */
11627 case ' ': case '\t':
11628 #if ENABLE_ASH_ALIAS
11633 while ((c = pgetc()) != '\n' && c != PEOF)
11638 if (pgetc() == '\n') {
11639 startlinno = ++g_parsefile->linno;
11647 g_parsefile->linno++;
11648 needprompt = doprompt;
11653 if (pgetc() == '&')
11658 if (pgetc() == '|')
11663 if (pgetc() == ';')
11676 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11679 #endif /* old xxreadtoken */
11686 smallint alreadyseen = tokpushback;
11689 #if ENABLE_ASH_ALIAS
11698 if (checkkwd & CHKNL) {
11705 if (t != TWORD || quoteflag) {
11710 * check for keywords
11712 if (checkkwd & CHKKWD) {
11713 const char *const *pp;
11715 pp = findkwd(wordtext);
11717 lasttoken = t = pp - tokname_array;
11718 TRACE(("keyword %s recognized\n", tokname(t)));
11723 if (checkkwd & CHKALIAS) {
11724 #if ENABLE_ASH_ALIAS
11726 ap = lookupalias(wordtext, 1);
11729 pushstring(ap->val, ap);
11739 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11741 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11753 return tokname_array[t][0];
11757 * Read and parse a command. Returns NODE_EOF on end of file.
11758 * (NULL is a valid parse tree indicating a blank line.)
11760 static union node *
11761 parsecmd(int interact)
11766 doprompt = interact;
11768 setprompt(doprompt);
11780 * Input any here documents.
11785 struct heredoc *here;
11788 here = heredoclist;
11789 heredoclist = NULL;
11795 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11796 here->eofmark, here->striptabs);
11797 n = stzalloc(sizeof(struct narg));
11798 n->narg.type = NARG;
11799 /*n->narg.next = NULL; - stzalloc did it */
11800 n->narg.text = wordtext;
11801 n->narg.backquote = backquotelist;
11802 here->here->nhere.doc = n;
11809 * called by editline -- any expansions to the prompt should be added here.
11811 #if ENABLE_ASH_EXPAND_PRMT
11812 static const char *
11813 expandstr(const char *ps)
11817 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11818 * and token processing _can_ alter it (delete NULs etc). */
11819 setinputstring((char *)ps);
11820 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11823 n.narg.type = NARG;
11824 n.narg.next = NULL;
11825 n.narg.text = wordtext;
11826 n.narg.backquote = backquotelist;
11828 expandarg(&n, NULL, 0);
11829 return stackblock();
11834 * Execute a command or commands contained in a string.
11837 evalstring(char *s, int mask)
11840 struct stackmark smark;
11844 setstackmark(&smark);
11847 while ((n = parsecmd(0)) != NODE_EOF) {
11849 popstackmark(&smark);
11862 * The eval command.
11864 static int FAST_FUNC
11865 evalcmd(int argc UNUSED_PARAM, char **argv)
11874 STARTSTACKSTR(concat);
11876 concat = stack_putstr(p, concat);
11880 STPUTC(' ', concat);
11882 STPUTC('\0', concat);
11883 p = grabstackstr(concat);
11885 evalstring(p, ~SKIPEVAL);
11892 * Read and execute commands. "Top" is nonzero for the top level command
11893 * loop; it turns on prompting if the shell is interactive.
11899 struct stackmark smark;
11903 TRACE(("cmdloop(%d) called\n", top));
11907 setstackmark(&smark);
11910 showjobs(stderr, SHOW_CHANGED);
11913 if (iflag && top) {
11915 #if ENABLE_ASH_MAIL
11919 n = parsecmd(inter);
11921 if (DEBUG > 2 && debug && (n != NODE_EOF))
11924 if (n == NODE_EOF) {
11925 if (!top || numeof >= 50)
11927 if (!stoppedjobs()) {
11930 out2str("\nUse \"exit\" to leave shell.\n");
11933 } else if (nflag == 0) {
11934 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11939 popstackmark(&smark);
11944 return skip & SKIPEVAL;
11951 * Take commands from a file. To be compatible we should do a path
11952 * search for the file, which is necessary to find sub-commands.
11955 find_dot_file(char *name)
11958 const char *path = pathval();
11961 /* don't try this for absolute or relative paths */
11962 if (strchr(name, '/'))
11965 /* IIRC standards do not say whether . is to be searched.
11966 * And it is even smaller this way, making it unconditional for now:
11968 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11973 while ((fullname = path_advance(&path, name)) != NULL) {
11975 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11977 * Don't bother freeing here, since it will
11978 * be freed by the caller.
11982 if (fullname != name)
11983 stunalloc(fullname);
11986 /* not found in the PATH */
11987 ash_msg_and_raise_error("%s: not found", name);
11991 static int FAST_FUNC
11992 dotcmd(int argc, char **argv)
11994 struct strlist *sp;
11995 volatile struct shparam saveparam;
11998 for (sp = cmdenviron; sp; sp = sp->next)
11999 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12001 if (argv[1]) { /* That's what SVR2 does */
12002 char *fullname = find_dot_file(argv[1]);
12005 if (argc) { /* argc > 0, argv[0] != NULL */
12006 saveparam = shellparam;
12007 shellparam.malloced = 0;
12008 shellparam.nparam = argc;
12009 shellparam.p = argv;
12012 setinputfile(fullname, INPUT_PUSH_FILE);
12013 commandname = fullname;
12018 freeparam(&shellparam);
12019 shellparam = saveparam;
12021 status = exitstatus;
12026 static int FAST_FUNC
12027 exitcmd(int argc UNUSED_PARAM, char **argv)
12032 exitstatus = number(argv[1]);
12033 raise_exception(EXEXIT);
12038 * Read a file containing shell functions.
12041 readcmdfile(char *name)
12043 setinputfile(name, INPUT_PUSH_FILE);
12049 /* ============ find_command inplementation */
12052 * Resolve a command name. If you change this routine, you may have to
12053 * change the shellexec routine as well.
12056 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12058 struct tblentry *cmdp;
12065 struct builtincmd *bcmd;
12067 /* If name contains a slash, don't use PATH or hash table */
12068 if (strchr(name, '/') != NULL) {
12069 entry->u.index = -1;
12070 if (act & DO_ABS) {
12071 while (stat(name, &statb) < 0) {
12073 if (errno == EINTR)
12076 entry->cmdtype = CMDUNKNOWN;
12080 entry->cmdtype = CMDNORMAL;
12084 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12086 updatetbl = (path == pathval());
12089 if (strstr(path, "%builtin") != NULL)
12090 act |= DO_ALTBLTIN;
12093 /* If name is in the table, check answer will be ok */
12094 cmdp = cmdlookup(name, 0);
12095 if (cmdp != NULL) {
12098 switch (cmdp->cmdtype) {
12116 } else if (cmdp->rehash == 0)
12117 /* if not invalidated by cd, we're done */
12121 /* If %builtin not in path, check for builtin next */
12122 bcmd = find_builtin(name);
12124 if (IS_BUILTIN_REGULAR(bcmd))
12125 goto builtin_success;
12126 if (act & DO_ALTPATH) {
12127 if (!(act & DO_ALTBLTIN))
12128 goto builtin_success;
12129 } else if (builtinloc <= 0) {
12130 goto builtin_success;
12134 #if ENABLE_FEATURE_SH_STANDALONE
12136 int applet_no = find_applet_by_name(name);
12137 if (applet_no >= 0) {
12138 entry->cmdtype = CMDNORMAL;
12139 entry->u.index = -2 - applet_no;
12145 /* We have to search path. */
12146 prev = -1; /* where to start */
12147 if (cmdp && cmdp->rehash) { /* doing a rehash */
12148 if (cmdp->cmdtype == CMDBUILTIN)
12151 prev = cmdp->param.index;
12157 while ((fullname = path_advance(&path, name)) != NULL) {
12158 stunalloc(fullname);
12159 /* NB: code below will still use fullname
12160 * despite it being "unallocated" */
12163 if (prefix(pathopt, "builtin")) {
12165 goto builtin_success;
12168 if ((act & DO_NOFUNC)
12169 || !prefix(pathopt, "func")
12170 ) { /* ignore unimplemented options */
12174 /* if rehash, don't redo absolute path names */
12175 if (fullname[0] == '/' && idx <= prev) {
12178 TRACE(("searchexec \"%s\": no change\n", name));
12181 while (stat(fullname, &statb) < 0) {
12183 if (errno == EINTR)
12186 if (errno != ENOENT && errno != ENOTDIR)
12190 e = EACCES; /* if we fail, this will be the error */
12191 if (!S_ISREG(statb.st_mode))
12193 if (pathopt) { /* this is a %func directory */
12194 stalloc(strlen(fullname) + 1);
12195 /* NB: stalloc will return space pointed by fullname
12196 * (because we don't have any intervening allocations
12197 * between stunalloc above and this stalloc) */
12198 readcmdfile(fullname);
12199 cmdp = cmdlookup(name, 0);
12200 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12201 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12202 stunalloc(fullname);
12205 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12207 entry->cmdtype = CMDNORMAL;
12208 entry->u.index = idx;
12212 cmdp = cmdlookup(name, 1);
12213 cmdp->cmdtype = CMDNORMAL;
12214 cmdp->param.index = idx;
12219 /* We failed. If there was an entry for this command, delete it */
12220 if (cmdp && updatetbl)
12221 delete_cmd_entry();
12223 ash_msg("%s: %s", name, errmsg(e, "not found"));
12224 entry->cmdtype = CMDUNKNOWN;
12229 entry->cmdtype = CMDBUILTIN;
12230 entry->u.cmd = bcmd;
12234 cmdp = cmdlookup(name, 1);
12235 cmdp->cmdtype = CMDBUILTIN;
12236 cmdp->param.cmd = bcmd;
12240 entry->cmdtype = cmdp->cmdtype;
12241 entry->u = cmdp->param;
12245 /* ============ trap.c */
12248 * The trap builtin.
12250 static int FAST_FUNC
12251 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12260 for (signo = 0; signo < NSIG; signo++) {
12261 char *tr = trap_ptr[signo];
12263 /* note: bash adds "SIG", but only if invoked
12264 * as "bash". If called as "sh", or if set -o posix,
12265 * then it prints short signal names.
12266 * We are printing short names: */
12267 out1fmt("trap -- %s %s\n",
12269 get_signame(signo));
12270 /* trap_ptr != trap only if we are in special-cased `trap` code.
12271 * In this case, we will exit very soon, no need to free(). */
12272 /* if (trap_ptr != trap && tp[0]) */
12277 if (trap_ptr != trap) {
12289 signo = get_signum(*ap);
12291 ash_msg_and_raise_error("%s: bad trap", *ap);
12294 if (LONE_DASH(action))
12297 action = ckstrdup(action);
12300 trap[signo] = action;
12310 /* ============ Builtins */
12312 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12314 * Lists available builtins
12316 static int FAST_FUNC
12317 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12323 "Built-in commands:\n"
12324 "------------------\n");
12325 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12326 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12327 builtintab[i].name + 1);
12333 #if ENABLE_FEATURE_SH_STANDALONE
12335 const char *a = applet_names;
12337 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12342 a += strlen(a) + 1;
12347 return EXIT_SUCCESS;
12349 #endif /* FEATURE_SH_EXTRA_QUIET */
12352 * The export and readonly commands.
12354 static int FAST_FUNC
12355 exportcmd(int argc UNUSED_PARAM, char **argv)
12361 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12363 if (nextopt("p") != 'p') {
12368 p = strchr(name, '=');
12372 vp = *findvar(hashvar(name), name);
12378 setvar(name, p, flag);
12379 } while ((name = *++aptr) != NULL);
12383 showvars(argv[0], flag, 0);
12388 * Delete a function if it exists.
12391 unsetfunc(const char *name)
12393 struct tblentry *cmdp;
12395 cmdp = cmdlookup(name, 0);
12396 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12397 delete_cmd_entry();
12401 * The unset builtin command. We unset the function before we unset the
12402 * variable to allow a function to be unset when there is a readonly variable
12403 * with the same name.
12405 static int FAST_FUNC
12406 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12413 while ((i = nextopt("vf")) != '\0') {
12417 for (ap = argptr; *ap; ap++) {
12433 #include <sys/times.h>
12435 static const unsigned char timescmd_str[] ALIGN1 = {
12436 ' ', offsetof(struct tms, tms_utime),
12437 '\n', offsetof(struct tms, tms_stime),
12438 ' ', offsetof(struct tms, tms_cutime),
12439 '\n', offsetof(struct tms, tms_cstime),
12443 static int FAST_FUNC
12444 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12446 long clk_tck, s, t;
12447 const unsigned char *p;
12450 clk_tck = sysconf(_SC_CLK_TCK);
12455 t = *(clock_t *)(((char *) &buf) + p[1]);
12457 out1fmt("%ldm%ld.%.3lds%c",
12459 ((t - s * clk_tck) * 1000) / clk_tck,
12461 } while (*(p += 2));
12466 #if ENABLE_SH_MATH_SUPPORT
12468 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12469 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12471 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12473 static int FAST_FUNC
12474 letcmd(int argc UNUSED_PARAM, char **argv)
12480 ash_msg_and_raise_error("expression expected");
12482 i = ash_arith(*argv);
12487 #endif /* SH_MATH_SUPPORT */
12490 /* ============ miscbltin.c
12492 * Miscellaneous builtins.
12497 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12498 typedef enum __rlimit_resource rlim_t;
12502 * The read builtin. Options:
12503 * -r Do not interpret '\' specially
12504 * -s Turn off echo (tty only)
12505 * -n NCHARS Read NCHARS max
12506 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12507 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12508 * -u FD Read from given FD instead of fd 0
12509 * This uses unbuffered input, which may be avoidable in some cases.
12510 * TODO: bash also has:
12511 * -a ARRAY Read into array[0],[1],etc
12512 * -d DELIM End on DELIM char, not newline
12513 * -e Use line editing (tty only)
12515 static int FAST_FUNC
12516 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12518 static const char *const arg_REPLY[] = { "REPLY", NULL };
12531 #if ENABLE_ASH_READ_NCHARS
12532 int nchars = 0; /* if != 0, -n is in effect */
12534 struct termios tty, old_tty;
12536 #if ENABLE_ASH_READ_TIMEOUT
12537 unsigned end_ms = 0;
12538 unsigned timeout = 0;
12543 while ((i = nextopt("p:u:r"
12544 IF_ASH_READ_TIMEOUT("t:")
12545 IF_ASH_READ_NCHARS("n:s")
12549 prompt = optionarg;
12551 #if ENABLE_ASH_READ_NCHARS
12553 nchars = bb_strtou(optionarg, NULL, 10);
12554 if (nchars < 0 || errno)
12555 ash_msg_and_raise_error("invalid count");
12556 /* nchars == 0: off (bash 3.2 does this too) */
12562 #if ENABLE_ASH_READ_TIMEOUT
12564 timeout = bb_strtou(optionarg, NULL, 10);
12565 if (errno || timeout > UINT_MAX / 2048)
12566 ash_msg_and_raise_error("invalid timeout");
12568 #if 0 /* even bash have no -t N.NNN support */
12569 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12571 /* EINVAL means number is ok, but not terminated by NUL */
12572 if (*p == '.' && errno == EINVAL) {
12576 ts.tv_usec = bb_strtou(p, &p2, 10);
12578 ash_msg_and_raise_error("invalid timeout");
12580 /* normalize to usec */
12582 ash_msg_and_raise_error("invalid timeout");
12583 while (scale++ < 6)
12586 } else if (ts.tv_sec < 0 || errno) {
12587 ash_msg_and_raise_error("invalid timeout");
12589 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12590 ash_msg_and_raise_error("invalid timeout");
12599 fd = bb_strtou(optionarg, NULL, 10);
12600 if (fd < 0 || errno)
12601 ash_msg_and_raise_error("invalid file descriptor");
12607 if (prompt && isatty(fd)) {
12612 ap = (char**)arg_REPLY;
12613 ifs = bltinlookup("IFS");
12616 #if ENABLE_ASH_READ_NCHARS
12617 tcgetattr(fd, &tty);
12619 if (nchars || silent) {
12621 tty.c_lflag &= ~ICANON;
12622 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12625 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12627 /* if tcgetattr failed, tcsetattr will fail too.
12628 * Ignoring, it's harmless. */
12629 tcsetattr(fd, TCSANOW, &tty);
12636 #if ENABLE_ASH_READ_TIMEOUT
12637 if (timeout) /* NB: ensuring end_ms is nonzero */
12638 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12642 const char *is_ifs;
12644 #if ENABLE_ASH_READ_TIMEOUT
12646 struct pollfd pfd[1];
12648 pfd[0].events = POLLIN;
12649 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12650 if ((int)timeout <= 0 /* already late? */
12651 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12652 ) { /* timed out! */
12653 #if ENABLE_ASH_READ_NCHARS
12654 tcsetattr(fd, TCSANOW, &old_tty);
12660 if (nonblock_safe_read(fd, &c, 1) != 1) {
12672 if (!rflag && c == '\\') {
12678 /* $IFS splitting */
12679 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12680 is_ifs = strchr(ifs, c);
12681 if (startword && is_ifs) {
12684 /* it is a non-space ifs char */
12686 if (startword == 1) /* first one? */
12687 continue; /* yes, it is not next word yet */
12690 if (ap[1] != NULL && is_ifs) {
12693 beg = stackblock();
12694 setvar(*ap, beg, 0);
12696 /* can we skip one non-space ifs char? (2: yes) */
12697 startword = isspace(c) ? 2 : 1;
12704 /* end of do {} while: */
12705 #if ENABLE_ASH_READ_NCHARS
12711 #if ENABLE_ASH_READ_NCHARS
12712 tcsetattr(fd, TCSANOW, &old_tty);
12716 /* Remove trailing space ifs chars */
12717 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12719 setvar(*ap, stackblock(), 0);
12720 while (*++ap != NULL)
12721 setvar(*ap, nullstr, 0);
12725 static int FAST_FUNC
12726 umaskcmd(int argc UNUSED_PARAM, char **argv)
12728 static const char permuser[3] ALIGN1 = "ugo";
12729 static const char permmode[3] ALIGN1 = "rwx";
12730 static const short permmask[] ALIGN2 = {
12731 S_IRUSR, S_IWUSR, S_IXUSR,
12732 S_IRGRP, S_IWGRP, S_IXGRP,
12733 S_IROTH, S_IWOTH, S_IXOTH
12736 /* TODO: use bb_parse_mode() instead */
12741 int symbolic_mode = 0;
12743 while (nextopt("S") != '\0') {
12754 if (symbolic_mode) {
12758 for (i = 0; i < 3; i++) {
12761 *p++ = permuser[i];
12763 for (j = 0; j < 3; j++) {
12764 if ((mask & permmask[3 * i + j]) == 0) {
12765 *p++ = permmode[j];
12773 out1fmt("%.4o\n", mask);
12776 if (isdigit((unsigned char) *ap)) {
12779 if (*ap >= '8' || *ap < '0')
12780 ash_msg_and_raise_error(msg_illnum, argv[1]);
12781 mask = (mask << 3) + (*ap - '0');
12782 } while (*++ap != '\0');
12785 mask = ~mask & 0777;
12786 if (!bb_parse_mode(ap, &mask)) {
12787 ash_msg_and_raise_error("illegal mode: %s", ap);
12789 umask(~mask & 0777);
12798 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12799 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12800 * ash by J.T. Conklin.
12805 uint8_t cmd; /* RLIMIT_xxx fit into it */
12806 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12810 static const struct limits limits_tbl[] = {
12812 { RLIMIT_CPU, 0, 't' },
12814 #ifdef RLIMIT_FSIZE
12815 { RLIMIT_FSIZE, 9, 'f' },
12818 { RLIMIT_DATA, 10, 'd' },
12820 #ifdef RLIMIT_STACK
12821 { RLIMIT_STACK, 10, 's' },
12824 { RLIMIT_CORE, 9, 'c' },
12827 { RLIMIT_RSS, 10, 'm' },
12829 #ifdef RLIMIT_MEMLOCK
12830 { RLIMIT_MEMLOCK, 10, 'l' },
12832 #ifdef RLIMIT_NPROC
12833 { RLIMIT_NPROC, 0, 'p' },
12835 #ifdef RLIMIT_NOFILE
12836 { RLIMIT_NOFILE, 0, 'n' },
12839 { RLIMIT_AS, 10, 'v' },
12841 #ifdef RLIMIT_LOCKS
12842 { RLIMIT_LOCKS, 0, 'w' },
12845 static const char limits_name[] =
12847 "time(seconds)" "\0"
12849 #ifdef RLIMIT_FSIZE
12850 "file(blocks)" "\0"
12855 #ifdef RLIMIT_STACK
12859 "coredump(blocks)" "\0"
12864 #ifdef RLIMIT_MEMLOCK
12865 "locked memory(kb)" "\0"
12867 #ifdef RLIMIT_NPROC
12870 #ifdef RLIMIT_NOFILE
12876 #ifdef RLIMIT_LOCKS
12881 enum limtype { SOFT = 0x1, HARD = 0x2 };
12884 printlim(enum limtype how, const struct rlimit *limit,
12885 const struct limits *l)
12889 val = limit->rlim_max;
12891 val = limit->rlim_cur;
12893 if (val == RLIM_INFINITY)
12894 out1fmt("unlimited\n");
12896 val >>= l->factor_shift;
12897 out1fmt("%lld\n", (long long) val);
12901 static int FAST_FUNC
12902 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12905 enum limtype how = SOFT | HARD;
12906 const struct limits *l;
12909 struct rlimit limit;
12912 while ((optc = nextopt("HSa"
12916 #ifdef RLIMIT_FSIZE
12922 #ifdef RLIMIT_STACK
12931 #ifdef RLIMIT_MEMLOCK
12934 #ifdef RLIMIT_NPROC
12937 #ifdef RLIMIT_NOFILE
12943 #ifdef RLIMIT_LOCKS
12961 for (l = limits_tbl; l->option != what; l++)
12964 set = *argptr ? 1 : 0;
12969 if (all || argptr[1])
12970 ash_msg_and_raise_error("too many arguments");
12971 if (strncmp(p, "unlimited\n", 9) == 0)
12972 val = RLIM_INFINITY;
12974 if (sizeof(val) == sizeof(int))
12975 val = bb_strtou(p, NULL, 10);
12976 else if (sizeof(val) == sizeof(long))
12977 val = bb_strtoul(p, NULL, 10);
12979 val = bb_strtoull(p, NULL, 10);
12981 ash_msg_and_raise_error("bad number");
12982 val <<= l->factor_shift;
12986 const char *lname = limits_name;
12987 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12988 getrlimit(l->cmd, &limit);
12989 out1fmt("%-20s ", lname);
12990 lname += strlen(lname) + 1;
12991 printlim(how, &limit, l);
12996 getrlimit(l->cmd, &limit);
12999 limit.rlim_max = val;
13001 limit.rlim_cur = val;
13002 if (setrlimit(l->cmd, &limit) < 0)
13003 ash_msg_and_raise_error("error setting limit (%m)");
13005 printlim(how, &limit, l);
13010 /* ============ main() and helpers */
13013 * Called to exit the shell.
13015 static void exitshell(void) NORETURN;
13023 status = exitstatus;
13024 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13025 if (setjmp(loc.loc)) {
13026 if (exception_type == EXEXIT)
13027 /* dash bug: it just does _exit(exitstatus) here
13028 * but we have to do setjobctl(0) first!
13029 * (bug is still not fixed in dash-0.5.3 - if you run dash
13030 * under Midnight Commander, on exit from dash MC is backgrounded) */
13031 status = exitstatus;
13034 exception_handler = &loc;
13041 flush_stdout_stderr();
13051 /* from input.c: */
13052 basepf.next_to_pgetc = basepf.buf = basebuf;
13055 signal(SIGCHLD, SIG_DFL);
13061 struct stat st1, st2;
13064 for (envp = environ; envp && *envp; envp++) {
13065 if (strchr(*envp, '=')) {
13066 setvareq(*envp, VEXPORT|VTEXTFIXED);
13070 setvar("PPID", utoa(getppid()), 0);
13072 p = lookupvar("PWD");
13074 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13075 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13082 * Process the shell command line arguments.
13085 procargs(char **argv)
13088 const char *xminusc;
13093 /* if (xargv[0]) - mmm, this is always true! */
13095 for (i = 0; i < NOPTS; i++)
13099 /* it already printed err message */
13100 raise_exception(EXERROR);
13104 if (*xargv == NULL) {
13106 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13109 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13113 for (i = 0; i < NOPTS; i++)
13114 if (optlist[i] == 2)
13119 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13124 } else if (!sflag) {
13125 setinputfile(*xargv, 0);
13128 commandname = arg0;
13131 shellparam.p = xargv;
13132 #if ENABLE_ASH_GETOPTS
13133 shellparam.optind = 1;
13134 shellparam.optoff = -1;
13136 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13138 shellparam.nparam++;
13145 * Read /etc/profile or .profile.
13148 read_profile(const char *name)
13152 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13161 * This routine is called when an error or an interrupt occurs in an
13162 * interactive shell and control is returned to the main command loop.
13170 /* from input.c: */
13171 g_parsefile->left_in_buffer = 0;
13172 g_parsefile->left_in_line = 0; /* clear input buffer */
13174 /* from parser.c: */
13177 /* from redir.c: */
13178 clearredir(/*drop:*/ 0);
13182 static short profile_buf[16384];
13183 extern int etext();
13187 * Main routine. We initialize things, parse the arguments, execute
13188 * profiles if we're a login shell, and then call cmdloop to execute
13189 * commands. The setjmp call sets up the location to jump to when an
13190 * exception occurs. When an exception occurs the variable "state"
13191 * is used to figure out how far we had gotten.
13193 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13194 int ash_main(int argc UNUSED_PARAM, char **argv)
13196 const char *shinit;
13197 volatile smallint state;
13198 struct jmploc jmploc;
13199 struct stackmark smark;
13201 /* Initialize global data */
13205 #if ENABLE_ASH_ALIAS
13211 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13214 #if ENABLE_FEATURE_EDITING
13215 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13218 if (setjmp(jmploc.loc)) {
13224 e = exception_type;
13228 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13231 outcslow('\n', stderr);
13233 popstackmark(&smark);
13234 FORCE_INT_ON; /* enable interrupts */
13243 exception_handler = &jmploc;
13246 TRACE(("Shell args: "));
13247 trace_puts_args(argv);
13249 rootpid = getpid();
13252 setstackmark(&smark);
13255 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13257 const char *hp = lookupvar("HISTFILE");
13260 hp = lookupvar("HOME");
13262 char *defhp = concat_path_file(hp, ".ash_history");
13263 setvar("HISTFILE", defhp, 0);
13269 if (/* argv[0] && */ argv[0][0] == '-')
13273 read_profile("/etc/profile");
13276 read_profile(".profile");
13282 getuid() == geteuid() && getgid() == getegid() &&
13286 shinit = lookupvar("ENV");
13287 if (shinit != NULL && *shinit != '\0') {
13288 read_profile(shinit);
13294 /* evalstring pushes parsefile stack.
13295 * Ensure we don't falsely claim that 0 (stdin)
13296 * is one of stacked source fds.
13297 * Testcase: ash -c 'exec 1>&0' must not complain. */
13299 g_parsefile->fd = -1;
13300 evalstring(minusc, 0);
13303 if (sflag || minusc == NULL) {
13304 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13306 const char *hp = lookupvar("HISTFILE");
13308 line_input_state->hist_file = hp;
13311 state4: /* XXX ??? - why isn't this before the "if" statement */
13319 extern void _mcleanup(void);
13329 * Copyright (c) 1989, 1991, 1993, 1994
13330 * The Regents of the University of California. All rights reserved.
13332 * This code is derived from software contributed to Berkeley by
13333 * Kenneth Almquist.
13335 * Redistribution and use in source and binary forms, with or without
13336 * modification, are permitted provided that the following conditions
13338 * 1. Redistributions of source code must retain the above copyright
13339 * notice, this list of conditions and the following disclaimer.
13340 * 2. Redistributions in binary form must reproduce the above copyright
13341 * notice, this list of conditions and the following disclaimer in the
13342 * documentation and/or other materials provided with the distribution.
13343 * 3. Neither the name of the University nor the names of its contributors
13344 * may be used to endorse or promote products derived from this software
13345 * without specific prior written permission.
13347 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13348 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13349 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13350 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13351 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13352 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13353 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13354 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13355 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13356 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF