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 CTL_FIRST CTLESC
450 #define CTLESC ((unsigned char)'\201') /* escape next character */
451 #define CTLVAR ((unsigned char)'\202') /* variable defn */
452 #define CTLENDVAR ((unsigned char)'\203')
453 #define CTLBACKQ ((unsigned char)'\204')
454 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
455 /* CTLBACKQ | CTLQUOTE == '\205' */
456 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
457 #define CTLENDARI ((unsigned char)'\207')
458 #define CTLQUOTEMARK ((unsigned char)'\210')
459 #define CTL_LAST CTLQUOTEMARK
461 /* variable substitution byte (follows CTLVAR) */
462 #define VSTYPE 0x0f /* type of variable substitution */
463 #define VSNUL 0x10 /* colon--treat the empty string as unset */
464 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
466 /* values of VSTYPE field */
467 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
468 #define VSMINUS 0x2 /* ${var-text} */
469 #define VSPLUS 0x3 /* ${var+text} */
470 #define VSQUESTION 0x4 /* ${var?message} */
471 #define VSASSIGN 0x5 /* ${var=text} */
472 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
473 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
474 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
475 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
476 #define VSLENGTH 0xa /* ${#var} */
477 #if ENABLE_ASH_BASH_COMPAT
478 #define VSSUBSTR 0xc /* ${var:position:length} */
479 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
480 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
483 static const char dolatstr[] ALIGN1 = {
484 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
504 #if ENABLE_ASH_BASH_COMPAT
521 smallint type; /* Nxxxx */
524 union node *redirect;
529 smallint pipe_backgnd;
530 struct nodelist *cmdlist;
536 union node *redirect;
549 union node *elsepart;
576 struct nodelist *backquote;
579 /* nfile and ndup layout must match!
580 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
581 * that it is actually NTO2 (>&file), and change its type.
598 char *_unused_expfname;
617 struct nredir nredir;
618 struct nbinary nbinary;
622 struct nclist nclist;
631 * NODE_EOF is returned by parsecmd when it encounters an end of file.
632 * It must be distinct from NULL.
634 #define NODE_EOF ((union node *) -1L)
637 struct nodelist *next;
650 freefunc(struct funcnode *f)
652 if (f && --f->count < 0)
657 /* ============ Debugging output */
661 static FILE *tracefile;
664 trace_printf(const char *fmt, ...)
671 fprintf(tracefile, "%u ", (int) time(NULL));
673 fprintf(tracefile, "[%u] ", (int) getpid());
675 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
677 vfprintf(tracefile, fmt, va);
682 trace_vprintf(const char *fmt, va_list va)
687 fprintf(tracefile, "%u ", (int) time(NULL));
689 fprintf(tracefile, "[%u] ", (int) getpid());
691 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
692 vfprintf(tracefile, fmt, va);
696 trace_puts(const char *s)
704 trace_puts_quoted(char *s)
711 putc('"', tracefile);
712 for (p = s; *p; p++) {
713 switch ((unsigned char)*p) {
714 case '\n': c = 'n'; goto backslash;
715 case '\t': c = 't'; goto backslash;
716 case '\r': c = 'r'; goto backslash;
717 case '\"': c = '\"'; goto backslash;
718 case '\\': c = '\\'; goto backslash;
719 case CTLESC: c = 'e'; goto backslash;
720 case CTLVAR: c = 'v'; goto backslash;
721 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
722 case CTLBACKQ: c = 'q'; goto backslash;
723 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
725 putc('\\', tracefile);
729 if (*p >= ' ' && *p <= '~')
732 putc('\\', tracefile);
733 putc((*p >> 6) & 03, tracefile);
734 putc((*p >> 3) & 07, tracefile);
735 putc(*p & 07, tracefile);
740 putc('"', tracefile);
744 trace_puts_args(char **ap)
751 trace_puts_quoted(*ap);
753 putc('\n', tracefile);
756 putc(' ', tracefile);
771 /* leave open because libedit might be using it */
774 strcpy(s, "./trace");
776 if (!freopen(s, "a", tracefile)) {
777 fprintf(stderr, "Can't re-open %s\n", s);
782 tracefile = fopen(s, "a");
783 if (tracefile == NULL) {
784 fprintf(stderr, "Can't open %s\n", s);
790 flags = fcntl(fileno(tracefile), F_GETFL);
792 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
794 setlinebuf(tracefile);
795 fputs("\nTracing started.\n", tracefile);
799 indent(int amount, char *pfx, FILE *fp)
803 for (i = 0; i < amount; i++) {
804 if (pfx && i == amount - 1)
810 /* little circular references here... */
811 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
814 sharg(union node *arg, FILE *fp)
817 struct nodelist *bqlist;
818 unsigned char subtype;
820 if (arg->type != NARG) {
821 out1fmt("<node type %d>\n", arg->type);
824 bqlist = arg->narg.backquote;
825 for (p = arg->narg.text; *p; p++) {
826 switch ((unsigned char)*p) {
834 if (subtype == VSLENGTH)
843 switch (subtype & VSTYPE) {
876 out1fmt("<subtype %d>", subtype);
883 case CTLBACKQ|CTLQUOTE:
886 shtree(bqlist->n, -1, NULL, fp);
897 shcmd(union node *cmd, FILE *fp)
905 for (np = cmd->ncmd.args; np; np = np->narg.next) {
911 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
915 switch (np->nfile.type) {
916 case NTO: s = ">>"+1; dftfd = 1; break;
917 case NCLOBBER: s = ">|"; dftfd = 1; break;
918 case NAPPEND: s = ">>"; dftfd = 1; break;
919 #if ENABLE_ASH_BASH_COMPAT
922 case NTOFD: s = ">&"; dftfd = 1; break;
923 case NFROM: s = "<"; break;
924 case NFROMFD: s = "<&"; break;
925 case NFROMTO: s = "<>"; break;
926 default: s = "*error*"; break;
928 if (np->nfile.fd != dftfd)
929 fprintf(fp, "%d", np->nfile.fd);
931 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
932 fprintf(fp, "%d", np->ndup.dupfd);
934 sharg(np->nfile.fname, fp);
941 shtree(union node *n, int ind, char *pfx, FILE *fp)
949 indent(ind, pfx, fp);
966 shtree(n->nbinary.ch1, ind, NULL, fp);
969 shtree(n->nbinary.ch2, ind, NULL, fp);
977 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
978 shtree(lp->n, 0, NULL, fp);
982 if (n->npipe.pipe_backgnd)
988 fprintf(fp, "<node type %d>", n->type);
996 showtree(union node *n)
998 trace_puts("showtree called\n");
999 shtree(n, 1, NULL, stderr);
1005 /* ============ Parser data */
1008 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1011 struct strlist *next;
1018 struct strpush *prev; /* preceding string on stack */
1020 int prev_left_in_line;
1021 #if ENABLE_ASH_ALIAS
1022 struct alias *ap; /* if push was associated with an alias */
1024 char *string; /* remember the string since it may change */
1028 struct parsefile *prev; /* preceding file on stack */
1029 int linno; /* current line */
1030 int fd; /* file descriptor (or -1 if string) */
1031 int left_in_line; /* number of chars left in this line */
1032 int left_in_buffer; /* number of chars left in this buffer past the line */
1033 char *next_to_pgetc; /* next char in buffer */
1034 char *buf; /* input buffer */
1035 struct strpush *strpush; /* for pushing strings at this level */
1036 struct strpush basestrpush; /* so pushing one is fast */
1039 static struct parsefile basepf; /* top level input file */
1040 static struct parsefile *g_parsefile = &basepf; /* current input file */
1041 static int startlinno; /* line # where last token started */
1042 static char *commandname; /* currently executing command */
1043 static struct strlist *cmdenviron; /* environment for builtin command */
1044 static uint8_t exitstatus; /* exit status of last command */
1047 /* ============ Message printing */
1050 ash_vmsg(const char *msg, va_list ap)
1052 fprintf(stderr, "%s: ", arg0);
1054 if (strcmp(arg0, commandname))
1055 fprintf(stderr, "%s: ", commandname);
1056 if (!iflag || g_parsefile->fd)
1057 fprintf(stderr, "line %d: ", startlinno);
1059 vfprintf(stderr, msg, ap);
1060 outcslow('\n', stderr);
1064 * Exverror is called to raise the error exception. If the second argument
1065 * is not NULL then error prints an error message using printf style
1066 * formatting. It then raises the error exception.
1068 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1070 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1074 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1076 TRACE(("\") pid=%d\n", getpid()));
1078 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1083 flush_stdout_stderr();
1084 raise_exception(cond);
1088 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1090 ash_msg_and_raise_error(const char *msg, ...)
1095 ash_vmsg_and_raise(EXERROR, msg, ap);
1100 static void raise_error_syntax(const char *) NORETURN;
1102 raise_error_syntax(const char *msg)
1104 ash_msg_and_raise_error("syntax error: %s", msg);
1108 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1110 ash_msg_and_raise(int cond, const char *msg, ...)
1115 ash_vmsg_and_raise(cond, msg, ap);
1121 * error/warning routines for external builtins
1124 ash_msg(const char *fmt, ...)
1134 * Return a string describing an error. The returned string may be a
1135 * pointer to a static buffer that will be overwritten on the next call.
1136 * Action describes the operation that got the error.
1139 errmsg(int e, const char *em)
1141 if (e == ENOENT || e == ENOTDIR) {
1148 /* ============ Memory allocation */
1151 /* I consider these wrappers nearly useless:
1152 * ok, they return you to nearest exception handler, but
1153 * how much memory do you leak in the process, making
1154 * memory starvation worse?
1157 ckrealloc(void * p, size_t nbytes)
1159 p = realloc(p, nbytes);
1161 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1166 ckmalloc(size_t nbytes)
1168 return ckrealloc(NULL, nbytes);
1172 ckzalloc(size_t nbytes)
1174 return memset(ckmalloc(nbytes), 0, nbytes);
1178 ckstrdup(const char *s)
1180 char *p = strdup(s);
1182 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1186 /* Using bbox equivalents. They exit if out of memory */
1187 # define ckrealloc xrealloc
1188 # define ckmalloc xmalloc
1189 # define ckzalloc xzalloc
1190 # define ckstrdup xstrdup
1194 * It appears that grabstackstr() will barf with such alignments
1195 * because stalloc() will return a string allocated in a new stackblock.
1197 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1199 /* Most machines require the value returned from malloc to be aligned
1200 * in some way. The following macro will get this right
1201 * on many machines. */
1202 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1203 /* Minimum size of a block */
1204 MINSIZE = SHELL_ALIGN(504),
1207 struct stack_block {
1208 struct stack_block *prev;
1209 char space[MINSIZE];
1213 struct stack_block *stackp;
1216 struct stackmark *marknext;
1220 struct globals_memstack {
1221 struct stack_block *g_stackp; // = &stackbase;
1222 struct stackmark *markp;
1223 char *g_stacknxt; // = stackbase.space;
1224 char *sstrend; // = stackbase.space + MINSIZE;
1225 size_t g_stacknleft; // = MINSIZE;
1226 int herefd; // = -1;
1227 struct stack_block stackbase;
1229 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1230 #define G_memstack (*ash_ptr_to_globals_memstack)
1231 #define g_stackp (G_memstack.g_stackp )
1232 #define markp (G_memstack.markp )
1233 #define g_stacknxt (G_memstack.g_stacknxt )
1234 #define sstrend (G_memstack.sstrend )
1235 #define g_stacknleft (G_memstack.g_stacknleft)
1236 #define herefd (G_memstack.herefd )
1237 #define stackbase (G_memstack.stackbase )
1238 #define INIT_G_memstack() do { \
1239 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1241 g_stackp = &stackbase; \
1242 g_stacknxt = stackbase.space; \
1243 g_stacknleft = MINSIZE; \
1244 sstrend = stackbase.space + MINSIZE; \
1249 #define stackblock() ((void *)g_stacknxt)
1250 #define stackblocksize() g_stacknleft
1253 * Parse trees for commands are allocated in lifo order, so we use a stack
1254 * to make this more efficient, and also to avoid all sorts of exception
1255 * handling code to handle interrupts in the middle of a parse.
1257 * The size 504 was chosen because the Ultrix malloc handles that size
1261 stalloc(size_t nbytes)
1266 aligned = SHELL_ALIGN(nbytes);
1267 if (aligned > g_stacknleft) {
1270 struct stack_block *sp;
1272 blocksize = aligned;
1273 if (blocksize < MINSIZE)
1274 blocksize = MINSIZE;
1275 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1276 if (len < blocksize)
1277 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1280 sp->prev = g_stackp;
1281 g_stacknxt = sp->space;
1282 g_stacknleft = blocksize;
1283 sstrend = g_stacknxt + blocksize;
1288 g_stacknxt += aligned;
1289 g_stacknleft -= aligned;
1294 stzalloc(size_t nbytes)
1296 return memset(stalloc(nbytes), 0, nbytes);
1303 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1304 write(STDERR_FILENO, "stunalloc\n", 10);
1308 g_stacknleft += g_stacknxt - (char *)p;
1313 * Like strdup but works with the ash stack.
1316 ststrdup(const char *p)
1318 size_t len = strlen(p) + 1;
1319 return memcpy(stalloc(len), p, len);
1323 setstackmark(struct stackmark *mark)
1325 mark->stackp = g_stackp;
1326 mark->stacknxt = g_stacknxt;
1327 mark->stacknleft = g_stacknleft;
1328 mark->marknext = markp;
1333 popstackmark(struct stackmark *mark)
1335 struct stack_block *sp;
1341 markp = mark->marknext;
1342 while (g_stackp != mark->stackp) {
1344 g_stackp = sp->prev;
1347 g_stacknxt = mark->stacknxt;
1348 g_stacknleft = mark->stacknleft;
1349 sstrend = mark->stacknxt + mark->stacknleft;
1354 * When the parser reads in a string, it wants to stick the string on the
1355 * stack and only adjust the stack pointer when it knows how big the
1356 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1357 * of space on top of the stack and stackblocklen returns the length of
1358 * this block. Growstackblock will grow this space by at least one byte,
1359 * possibly moving it (like realloc). Grabstackblock actually allocates the
1360 * part of the block that has been used.
1363 growstackblock(void)
1367 newlen = g_stacknleft * 2;
1368 if (newlen < g_stacknleft)
1369 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1373 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1374 struct stack_block *oldstackp;
1375 struct stackmark *xmark;
1376 struct stack_block *sp;
1377 struct stack_block *prevstackp;
1381 oldstackp = g_stackp;
1383 prevstackp = sp->prev;
1384 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1385 sp = ckrealloc(sp, grosslen);
1386 sp->prev = prevstackp;
1388 g_stacknxt = sp->space;
1389 g_stacknleft = newlen;
1390 sstrend = sp->space + newlen;
1393 * Stack marks pointing to the start of the old block
1394 * must be relocated to point to the new block
1397 while (xmark != NULL && xmark->stackp == oldstackp) {
1398 xmark->stackp = g_stackp;
1399 xmark->stacknxt = g_stacknxt;
1400 xmark->stacknleft = g_stacknleft;
1401 xmark = xmark->marknext;
1405 char *oldspace = g_stacknxt;
1406 size_t oldlen = g_stacknleft;
1407 char *p = stalloc(newlen);
1409 /* free the space we just allocated */
1410 g_stacknxt = memcpy(p, oldspace, oldlen);
1411 g_stacknleft += newlen;
1416 grabstackblock(size_t len)
1418 len = SHELL_ALIGN(len);
1420 g_stacknleft -= len;
1424 * The following routines are somewhat easier to use than the above.
1425 * The user declares a variable of type STACKSTR, which may be declared
1426 * to be a register. The macro STARTSTACKSTR initializes things. Then
1427 * the user uses the macro STPUTC to add characters to the string. In
1428 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1429 * grown as necessary. When the user is done, she can just leave the
1430 * string there and refer to it using stackblock(). Or she can allocate
1431 * the space for it using grabstackstr(). If it is necessary to allow
1432 * someone else to use the stack temporarily and then continue to grow
1433 * the string, the user should use grabstack to allocate the space, and
1434 * then call ungrabstr(p) to return to the previous mode of operation.
1436 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1437 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1438 * is space for at least one character.
1443 size_t len = stackblocksize();
1444 if (herefd >= 0 && len >= 1024) {
1445 full_write(herefd, stackblock(), len);
1446 return stackblock();
1449 return (char *)stackblock() + len;
1453 * Called from CHECKSTRSPACE.
1456 makestrspace(size_t newlen, char *p)
1458 size_t len = p - g_stacknxt;
1459 size_t size = stackblocksize();
1464 size = stackblocksize();
1466 if (nleft >= newlen)
1470 return (char *)stackblock() + len;
1474 stack_nputstr(const char *s, size_t n, char *p)
1476 p = makestrspace(n, p);
1477 p = (char *)memcpy(p, s, n) + n;
1482 stack_putstr(const char *s, char *p)
1484 return stack_nputstr(s, strlen(s), p);
1488 _STPUTC(int c, char *p)
1496 #define STARTSTACKSTR(p) ((p) = stackblock())
1497 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1498 #define CHECKSTRSPACE(n, p) do { \
1501 size_t m = sstrend - q; \
1503 (p) = makestrspace(l, q); \
1505 #define USTPUTC(c, p) (*(p)++ = (c))
1506 #define STACKSTRNUL(p) do { \
1507 if ((p) == sstrend) \
1508 (p) = growstackstr(); \
1511 #define STUNPUTC(p) (--(p))
1512 #define STTOPC(p) ((p)[-1])
1513 #define STADJUST(amount, p) ((p) += (amount))
1515 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1516 #define ungrabstackstr(s, p) stunalloc(s)
1517 #define stackstrend() ((void *)sstrend)
1520 /* ============ String helpers */
1523 * prefix -- see if pfx is a prefix of string.
1526 prefix(const char *string, const char *pfx)
1529 if (*pfx++ != *string++)
1532 return (char *) string;
1536 * Check for a valid number. This should be elsewhere.
1539 is_number(const char *p)
1544 } while (*++p != '\0');
1549 * Convert a string of digits to an integer, printing an error message on
1553 number(const char *s)
1556 ash_msg_and_raise_error(msg_illnum, s);
1561 * Produce a possibly single quoted string suitable as input to the shell.
1562 * The return string is allocated on the stack.
1565 single_quote(const char *s)
1575 len = strchrnul(s, '\'') - s;
1577 q = p = makestrspace(len + 3, p);
1580 q = (char *)memcpy(q, s, len) + len;
1589 do len++; while (*++s == '\'');
1591 q = p = makestrspace(len + 3, p);
1594 q = (char *)memcpy(q, s - len, len) + len;
1602 return stackblock();
1606 /* ============ nextopt */
1608 static char **argptr; /* argument list for builtin commands */
1609 static char *optionarg; /* set by nextopt (like getopt) */
1610 static char *optptr; /* used by nextopt */
1613 * XXX - should get rid of. Have all builtins use getopt(3).
1614 * The library getopt must have the BSD extension static variable
1615 * "optreset", otherwise it can't be used within the shell safely.
1617 * Standard option processing (a la getopt) for builtin routines.
1618 * The only argument that is passed to nextopt is the option string;
1619 * the other arguments are unnecessary. It returns the character,
1620 * or '\0' on end of input.
1623 nextopt(const char *optstring)
1630 if (p == NULL || *p == '\0') {
1631 /* We ate entire "-param", take next one */
1637 if (*++p == '\0') /* just "-" ? */
1640 if (LONE_DASH(p)) /* "--" ? */
1642 /* p => next "-param" */
1644 /* p => some option char in the middle of a "-param" */
1646 for (q = optstring; *q != c;) {
1648 ash_msg_and_raise_error("illegal option -%c", c);
1656 ash_msg_and_raise_error("no arg for -%c option", c);
1666 /* ============ Shell variables */
1669 * The parsefile structure pointed to by the global variable parsefile
1670 * contains information about the current file being read.
1673 int nparam; /* # of positional parameters (without $0) */
1674 #if ENABLE_ASH_GETOPTS
1675 int optind; /* next parameter to be processed by getopts */
1676 int optoff; /* used by getopts */
1678 unsigned char malloced; /* if parameter list dynamically allocated */
1679 char **p; /* parameter list */
1683 * Free the list of positional parameters.
1686 freeparam(volatile struct shparam *param)
1688 if (param->malloced) {
1690 ap = ap1 = param->p;
1697 #if ENABLE_ASH_GETOPTS
1698 static void FAST_FUNC getoptsreset(const char *value);
1702 struct var *next; /* next entry in hash list */
1703 int flags; /* flags are defined above */
1704 const char *text; /* name=value */
1705 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1706 /* the variable gets set/unset */
1710 struct localvar *next; /* next local variable in list */
1711 struct var *vp; /* the variable that was made local */
1712 int flags; /* saved flags */
1713 const char *text; /* saved text */
1717 #define VEXPORT 0x01 /* variable is exported */
1718 #define VREADONLY 0x02 /* variable cannot be modified */
1719 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1720 #define VTEXTFIXED 0x08 /* text is statically allocated */
1721 #define VSTACK 0x10 /* text is allocated on the stack */
1722 #define VUNSET 0x20 /* the variable is not set */
1723 #define VNOFUNC 0x40 /* don't call the callback function */
1724 #define VNOSET 0x80 /* do not set variable - just readonly test */
1725 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1726 #if ENABLE_ASH_RANDOM_SUPPORT
1727 # define VDYNAMIC 0x200 /* dynamic variable */
1733 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1734 #define defifs (defifsvar + 4)
1736 static const char defifs[] ALIGN1 = " \t\n";
1740 /* Need to be before varinit_data[] */
1741 #if ENABLE_LOCALE_SUPPORT
1742 static void FAST_FUNC
1743 change_lc_all(const char *value)
1745 if (value && *value != '\0')
1746 setlocale(LC_ALL, value);
1748 static void FAST_FUNC
1749 change_lc_ctype(const char *value)
1751 if (value && *value != '\0')
1752 setlocale(LC_CTYPE, value);
1756 static void chkmail(void);
1757 static void changemail(const char *) FAST_FUNC;
1759 static void changepath(const char *) FAST_FUNC;
1760 #if ENABLE_ASH_RANDOM_SUPPORT
1761 static void change_random(const char *) FAST_FUNC;
1764 static const struct {
1767 void (*func)(const char *) FAST_FUNC;
1768 } varinit_data[] = {
1770 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1772 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1778 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1779 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1782 #if ENABLE_ASH_GETOPTS
1783 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1785 #if ENABLE_ASH_RANDOM_SUPPORT
1786 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1788 #if ENABLE_LOCALE_SUPPORT
1789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1792 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1793 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1799 struct globals_var {
1800 struct shparam shellparam; /* $@ current positional parameters */
1801 struct redirtab *redirlist;
1803 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1804 struct var *vartab[VTABSIZE];
1805 struct var varinit[ARRAY_SIZE(varinit_data)];
1807 extern struct globals_var *const ash_ptr_to_globals_var;
1808 #define G_var (*ash_ptr_to_globals_var)
1809 #define shellparam (G_var.shellparam )
1810 //#define redirlist (G_var.redirlist )
1811 #define g_nullredirs (G_var.g_nullredirs )
1812 #define preverrout_fd (G_var.preverrout_fd)
1813 #define vartab (G_var.vartab )
1814 #define varinit (G_var.varinit )
1815 #define INIT_G_var() do { \
1817 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1819 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1820 varinit[i].flags = varinit_data[i].flags; \
1821 varinit[i].text = varinit_data[i].text; \
1822 varinit[i].func = varinit_data[i].func; \
1826 #define vifs varinit[0]
1828 # define vmail (&vifs)[1]
1829 # define vmpath (&vmail)[1]
1830 # define vpath (&vmpath)[1]
1832 # define vpath (&vifs)[1]
1834 #define vps1 (&vpath)[1]
1835 #define vps2 (&vps1)[1]
1836 #define vps4 (&vps2)[1]
1837 #if ENABLE_ASH_GETOPTS
1838 # define voptind (&vps4)[1]
1839 # if ENABLE_ASH_RANDOM_SUPPORT
1840 # define vrandom (&voptind)[1]
1843 # if ENABLE_ASH_RANDOM_SUPPORT
1844 # define vrandom (&vps4)[1]
1849 * The following macros access the values of the above variables.
1850 * They have to skip over the name. They return the null string
1851 * for unset variables.
1853 #define ifsval() (vifs.text + 4)
1854 #define ifsset() ((vifs.flags & VUNSET) == 0)
1856 # define mailval() (vmail.text + 5)
1857 # define mpathval() (vmpath.text + 9)
1858 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1860 #define pathval() (vpath.text + 5)
1861 #define ps1val() (vps1.text + 4)
1862 #define ps2val() (vps2.text + 4)
1863 #define ps4val() (vps4.text + 4)
1864 #if ENABLE_ASH_GETOPTS
1865 # define optindval() (voptind.text + 7)
1869 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1870 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1872 #if ENABLE_ASH_GETOPTS
1873 static void FAST_FUNC
1874 getoptsreset(const char *value)
1876 shellparam.optind = number(value);
1877 shellparam.optoff = -1;
1882 * Return of a legal variable name (a letter or underscore followed by zero or
1883 * more letters, underscores, and digits).
1886 endofname(const char *name)
1894 if (!is_in_name(*p))
1901 * Compares two strings up to the first = or '\0'. The first
1902 * string must be terminated by '='; the second may be terminated by
1903 * either '=' or '\0'.
1906 varcmp(const char *p, const char *q)
1910 while ((c = *p) == (d = *q)) {
1925 varequal(const char *a, const char *b)
1927 return !varcmp(a, b);
1931 * Find the appropriate entry in the hash table from the name.
1933 static struct var **
1934 hashvar(const char *p)
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1945 vpcmp(const void *a, const void *b)
1947 return varcmp(*(const char **)a, *(const char **)b);
1951 * This routine initializes the builtin variables.
1961 * PS1 depends on uid
1963 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1964 vps1.text = "PS1=\\w \\$ ";
1967 vps1.text = "PS1=# ";
1970 end = vp + ARRAY_SIZE(varinit);
1972 vpp = hashvar(vp->text);
1975 } while (++vp < end);
1978 static struct var **
1979 findvar(struct var **vpp, const char *name)
1981 for (; *vpp; vpp = &(*vpp)->next) {
1982 if (varequal((*vpp)->text, name)) {
1990 * Find the value of a variable. Returns NULL if not set.
1993 lookupvar(const char *name)
1997 v = *findvar(hashvar(name), name);
1999 #if ENABLE_ASH_RANDOM_SUPPORT
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2006 if ((v->flags & VDYNAMIC))
2009 if (!(v->flags & VUNSET))
2010 return strchrnul(v->text, '=') + 1;
2016 * Search the environment of a builtin command.
2019 bltinlookup(const char *name)
2023 for (sp = cmdenviron; sp; sp = sp->next) {
2024 if (varequal(sp->text, name))
2025 return strchrnul(sp->text, '=') + 1;
2027 return lookupvar(name);
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2035 * Called with interrupts off.
2038 setvareq(char *s, int flags)
2040 struct var *vp, **vpp;
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2049 if (flags & VNOSAVE)
2052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2058 if (vp->func && (flags & VNOFUNC) == 0)
2059 (*vp->func)(strchrnul(s, '=') + 1);
2061 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2062 free((char*)vp->text);
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2069 vp = ckzalloc(sizeof(*vp));
2071 /*vp->func = NULL; - ckzalloc did it */
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2085 setvar(const char *name, const char *val, int flags)
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2101 vallen = strlen(val);
2104 nameeq = ckmalloc(namelen + vallen + 2);
2105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2108 p = (char *)memcpy(p, val, vallen) + vallen;
2111 setvareq(nameeq, flags | VNOSAVE);
2115 #if ENABLE_ASH_GETOPTS
2117 * Safe version of setvar, returns 1 on success 0 on failure.
2120 setvarsafe(const char *name, const char *val, int flags)
2123 volatile int saveint;
2124 struct jmploc *volatile savehandler = exception_handler;
2125 struct jmploc jmploc;
2128 if (setjmp(jmploc.loc))
2131 exception_handler = &jmploc;
2132 setvar(name, val, flags);
2135 exception_handler = savehandler;
2136 RESTORE_INT(saveint);
2142 * Unset the specified variable.
2145 unsetvar(const char *s)
2151 vpp = findvar(hashvar(s), s);
2155 int flags = vp->flags;
2158 if (flags & VREADONLY)
2160 #if ENABLE_ASH_RANDOM_SUPPORT
2161 vp->flags &= ~VDYNAMIC;
2165 if ((flags & VSTRFIXED) == 0) {
2167 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2168 free((char*)vp->text);
2174 vp->flags &= ~VEXPORT;
2184 * Process a linked list of variable assignments.
2187 listsetvar(struct strlist *list_set_var, int flags)
2189 struct strlist *lp = list_set_var;
2195 setvareq(lp->text, flags);
2202 * Generate a list of variables satisfying the given conditions.
2205 listvars(int on, int off, char ***end)
2216 for (vp = *vpp; vp; vp = vp->next) {
2217 if ((vp->flags & mask) == on) {
2218 if (ep == stackstrend())
2219 ep = growstackstr();
2220 *ep++ = (char *) vp->text;
2223 } while (++vpp < vartab + VTABSIZE);
2224 if (ep == stackstrend())
2225 ep = growstackstr();
2229 return grabstackstr(ep);
2233 /* ============ Path search helper
2235 * The variable path (passed by reference) should be set to the start
2236 * of the path before the first call; path_advance will update
2237 * this value as it proceeds. Successive calls to path_advance will return
2238 * the possible path expansions in sequence. If an option (indicated by
2239 * a percent sign) appears in the path entry then the global variable
2240 * pathopt will be set to point to it; otherwise pathopt will be set to
2243 static const char *pathopt; /* set by path_advance */
2246 path_advance(const char **path, const char *name)
2256 for (p = start; *p && *p != ':' && *p != '%'; p++)
2258 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2259 while (stackblocksize() < len)
2263 memcpy(q, start, p - start);
2271 while (*p && *p != ':')
2278 return stalloc(len);
2282 /* ============ Prompt */
2284 static smallint doprompt; /* if set, prompt the user */
2285 static smallint needprompt; /* true if interactive and at start of line */
2287 #if ENABLE_FEATURE_EDITING
2288 static line_input_t *line_input_state;
2289 static const char *cmdedit_prompt;
2291 putprompt(const char *s)
2293 if (ENABLE_ASH_EXPAND_PRMT) {
2294 free((char*)cmdedit_prompt);
2295 cmdedit_prompt = ckstrdup(s);
2302 putprompt(const char *s)
2308 #if ENABLE_ASH_EXPAND_PRMT
2309 /* expandstr() needs parsing machinery, so it is far away ahead... */
2310 static const char *expandstr(const char *ps);
2312 #define expandstr(s) s
2316 setprompt(int whichprompt)
2319 #if ENABLE_ASH_EXPAND_PRMT
2320 struct stackmark smark;
2325 switch (whichprompt) {
2335 #if ENABLE_ASH_EXPAND_PRMT
2336 setstackmark(&smark);
2337 stalloc(stackblocksize());
2339 putprompt(expandstr(prompt));
2340 #if ENABLE_ASH_EXPAND_PRMT
2341 popstackmark(&smark);
2346 /* ============ The cd and pwd commands */
2348 #define CD_PHYSICAL 1
2358 while ((i = nextopt("LP")) != '\0') {
2360 flags ^= CD_PHYSICAL;
2369 * Update curdir (the name of the current directory) in response to a
2373 updatepwd(const char *dir)
2380 cdcomppath = ststrdup(dir);
2383 if (curdir == nullstr)
2385 new = stack_putstr(curdir, new);
2387 new = makestrspace(strlen(dir) + 2, new);
2388 lim = (char *)stackblock() + 1;
2392 if (new > lim && *lim == '/')
2397 if (dir[1] == '/' && dir[2] != '/') {
2403 p = strtok(cdcomppath, "/");
2407 if (p[1] == '.' && p[2] == '\0') {
2419 new = stack_putstr(p, new);
2427 return stackblock();
2431 * Find out what the current directory is. If we already know the current
2432 * directory, this routine returns immediately.
2437 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2438 return dir ? dir : nullstr;
2442 setpwd(const char *val, int setold)
2446 oldcur = dir = curdir;
2449 setvar("OLDPWD", oldcur, VEXPORT);
2452 if (physdir != nullstr) {
2453 if (physdir != oldcur)
2457 if (oldcur == val || !val) {
2463 dir = ckstrdup(val);
2464 if (oldcur != dir && oldcur != nullstr) {
2469 setvar("PWD", dir, VEXPORT);
2472 static void hashcd(void);
2475 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2476 * know that the current directory has changed.
2479 docd(const char *dest, int flags)
2481 const char *dir = 0;
2484 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2487 if (!(flags & CD_PHYSICAL)) {
2488 dir = updatepwd(dest);
2502 static int FAST_FUNC
2503 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2515 dest = bltinlookup(homestr);
2516 else if (LONE_DASH(dest)) {
2517 dest = bltinlookup("OLDPWD");
2539 path = bltinlookup("CDPATH");
2548 p = path_advance(&path, dest);
2549 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2553 if (!docd(p, flags))
2558 ash_msg_and_raise_error("can't cd to %s", dest);
2561 if (flags & CD_PRINT)
2562 out1fmt(snlfmt, curdir);
2566 static int FAST_FUNC
2567 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2570 const char *dir = curdir;
2574 if (physdir == nullstr)
2578 out1fmt(snlfmt, dir);
2583 /* ============ ... */
2586 #define IBUFSIZ COMMON_BUFSIZE
2587 /* buffer for top level input file */
2588 #define basebuf bb_common_bufsiz1
2590 /* Syntax classes */
2591 #define CWORD 0 /* character is nothing special */
2592 #define CNL 1 /* newline character */
2593 #define CBACK 2 /* a backslash character */
2594 #define CSQUOTE 3 /* single quote */
2595 #define CDQUOTE 4 /* double quote */
2596 #define CENDQUOTE 5 /* a terminating quote */
2597 #define CBQUOTE 6 /* backwards single quote */
2598 #define CVAR 7 /* a dollar sign */
2599 #define CENDVAR 8 /* a '}' character */
2600 #define CLP 9 /* a left paren in arithmetic */
2601 #define CRP 10 /* a right paren in arithmetic */
2602 #define CENDFILE 11 /* end of file */
2603 #define CCTL 12 /* like CWORD, except it must be escaped */
2604 #define CSPCL 13 /* these terminate a word */
2605 #define CIGN 14 /* character should be ignored */
2608 #if ENABLE_ASH_ALIAS
2612 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2614 #if ENABLE_SH_MATH_SUPPORT
2615 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2617 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2619 static const uint16_t S_I_T[] = {
2620 #if ENABLE_ASH_ALIAS
2621 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2623 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2624 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2625 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2626 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2627 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2628 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2630 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2631 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2632 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2633 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2634 #if !USE_SIT_FUNCTION
2635 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2636 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2637 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2641 /* Constants below must match table above */
2643 #if ENABLE_ASH_ALIAS
2644 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2646 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2647 CNL_CNL_CNL_CNL , /* 2 */
2648 CWORD_CCTL_CCTL_CWORD , /* 3 */
2649 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2650 CVAR_CVAR_CWORD_CVAR , /* 5 */
2651 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2652 CSPCL_CWORD_CWORD_CLP , /* 7 */
2653 CSPCL_CWORD_CWORD_CRP , /* 8 */
2654 CBACK_CBACK_CCTL_CBACK , /* 9 */
2655 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2656 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2657 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2658 CWORD_CWORD_CWORD_CWORD , /* 13 */
2659 CCTL_CCTL_CCTL_CCTL , /* 14 */
2662 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2663 * caller must ensure proper cast on it if c is *char_ptr!
2665 /* Values for syntax param */
2666 #define BASESYNTAX 0 /* not in quotes */
2667 #define DQSYNTAX 1 /* in double quotes */
2668 #define SQSYNTAX 2 /* in single quotes */
2669 #define ARISYNTAX 3 /* in arithmetic */
2670 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2672 #if USE_SIT_FUNCTION
2675 SIT(int c, int syntax)
2677 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2678 # if ENABLE_ASH_ALIAS
2679 static const uint8_t syntax_index_table[] ALIGN1 = {
2680 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2681 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2682 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2686 static const uint8_t syntax_index_table[] ALIGN1 = {
2687 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2688 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2689 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2698 # if ENABLE_ASH_ALIAS
2704 /* Cast is purely for paranoia here,
2705 * just in case someone passed signed char to us */
2706 if ((unsigned char)c >= CTL_FIRST
2707 && (unsigned char)c <= CTL_LAST
2711 s = strchrnul(spec_symbls, c);
2714 indx = syntax_index_table[s - spec_symbls];
2716 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2719 #else /* !USE_SIT_FUNCTION */
2721 static const uint8_t syntax_index_table[] = {
2722 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2723 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2733 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2734 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2756 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2757 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2758 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2759 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2760 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2761 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2762 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2763 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2764 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2765 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2766 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2768 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2769 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2770 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2782 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2783 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2784 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2785 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2786 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2815 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2816 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2817 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2820 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2848 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2849 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2850 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2851 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2853 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2854 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2855 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2856 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2857 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2858 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2859 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2860 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2979 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2980 # if ENABLE_ASH_ALIAS
2981 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2985 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2987 #endif /* !USE_SIT_FUNCTION */
2990 /* ============ Alias handling */
2992 #if ENABLE_ASH_ALIAS
2994 #define ALIASINUSE 1
3005 static struct alias **atab; // [ATABSIZE];
3006 #define INIT_G_alias() do { \
3007 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3011 static struct alias **
3012 __lookupalias(const char *name) {
3013 unsigned int hashval;
3020 ch = (unsigned char)*p;
3024 ch = (unsigned char)*++p;
3026 app = &atab[hashval % ATABSIZE];
3028 for (; *app; app = &(*app)->next) {
3029 if (strcmp(name, (*app)->name) == 0) {
3037 static struct alias *
3038 lookupalias(const char *name, int check)
3040 struct alias *ap = *__lookupalias(name);
3042 if (check && ap && (ap->flag & ALIASINUSE))
3047 static struct alias *
3048 freealias(struct alias *ap)
3052 if (ap->flag & ALIASINUSE) {
3053 ap->flag |= ALIASDEAD;
3065 setalias(const char *name, const char *val)
3067 struct alias *ap, **app;
3069 app = __lookupalias(name);
3073 if (!(ap->flag & ALIASINUSE)) {
3076 ap->val = ckstrdup(val);
3077 ap->flag &= ~ALIASDEAD;
3080 ap = ckzalloc(sizeof(struct alias));
3081 ap->name = ckstrdup(name);
3082 ap->val = ckstrdup(val);
3083 /*ap->flag = 0; - ckzalloc did it */
3084 /*ap->next = NULL;*/
3091 unalias(const char *name)
3095 app = __lookupalias(name);
3099 *app = freealias(*app);
3110 struct alias *ap, **app;
3114 for (i = 0; i < ATABSIZE; i++) {
3116 for (ap = *app; ap; ap = *app) {
3117 *app = freealias(*app);
3127 printalias(const struct alias *ap)
3129 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3133 * TODO - sort output
3135 static int FAST_FUNC
3136 aliascmd(int argc UNUSED_PARAM, char **argv)
3145 for (i = 0; i < ATABSIZE; i++) {
3146 for (ap = atab[i]; ap; ap = ap->next) {
3152 while ((n = *++argv) != NULL) {
3153 v = strchr(n+1, '=');
3154 if (v == NULL) { /* n+1: funny ksh stuff */
3155 ap = *__lookupalias(n);
3157 fprintf(stderr, "%s: %s not found\n", "alias", n);
3170 static int FAST_FUNC
3171 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3175 while ((i = nextopt("a")) != '\0') {
3181 for (i = 0; *argptr; argptr++) {
3182 if (unalias(*argptr)) {
3183 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3191 #endif /* ASH_ALIAS */
3194 /* ============ jobs.c */
3196 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3199 #define FORK_NOJOB 2
3201 /* mode flags for showjob(s) */
3202 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3203 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3204 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3207 * A job structure contains information about a job. A job is either a
3208 * single process or a set of processes contained in a pipeline. In the
3209 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3213 pid_t pid; /* process id */
3214 int status; /* last process status from wait() */
3215 char *cmd; /* text of command being run */
3219 struct procstat ps0; /* status of process */
3220 struct procstat *ps; /* status or processes when more than one */
3222 int stopstatus; /* status of a stopped job */
3225 nprocs: 16, /* number of processes */
3227 #define JOBRUNNING 0 /* at least one proc running */
3228 #define JOBSTOPPED 1 /* all procs are stopped */
3229 #define JOBDONE 2 /* all procs are completed */
3231 sigint: 1, /* job was killed by SIGINT */
3232 jobctl: 1, /* job running under job control */
3234 waited: 1, /* true if this entry has been waited for */
3235 used: 1, /* true if this entry is in used */
3236 changed: 1; /* true if status has changed */
3237 struct job *prev_job; /* previous job */
3240 static struct job *makejob(/*union node *,*/ int);
3241 static int forkshell(struct job *, union node *, int);
3242 static int waitforjob(struct job *);
3245 enum { doing_jobctl = 0 };
3246 #define setjobctl(on) do {} while (0)
3248 static smallint doing_jobctl; //references:8
3249 static void setjobctl(int);
3256 ignoresig(int signo)
3258 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3259 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3260 /* No, need to do it */
3261 signal(signo, SIG_IGN);
3263 sigmode[signo - 1] = S_HARD_IGN;
3267 * Signal handler. Only one usage site - in setsignal()
3272 gotsig[signo - 1] = 1;
3274 if (signo == SIGINT && !trap[SIGINT]) {
3275 if (!suppress_int) {
3277 raise_interrupt(); /* does not return */
3281 pending_sig = signo;
3286 * Set the signal handler for the specified signal. The routine figures
3287 * out what it should be set to.
3290 setsignal(int signo)
3293 char cur_act, new_act;
3294 struct sigaction act;
3298 if (t != NULL) { /* trap for this sig is set */
3300 if (t[0] == '\0') /* trap is "": ignore this sig */
3304 if (rootshell && new_act == S_DFL) {
3307 if (iflag || minusc || sflag == 0)
3316 * "In all cases, bash ignores SIGQUIT. Non-builtin
3317 * commands run by bash have signal handlers
3318 * set to the values inherited by the shell
3319 * from its parent". */
3335 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3336 //whereas we have to restore it to what shell got on entry
3337 //from the parent. See comment above
3339 t = &sigmode[signo - 1];
3342 /* current setting is not yet known */
3343 if (sigaction(signo, NULL, &act)) {
3344 /* pretend it worked; maybe we should give a warning,
3345 * but other shells don't. We don't alter sigmode,
3346 * so we retry every time.
3347 * btw, in Linux it never fails. --vda */
3350 if (act.sa_handler == SIG_IGN) {
3351 cur_act = S_HARD_IGN;
3353 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3355 cur_act = S_IGN; /* don't hard ignore these */
3359 if (cur_act == S_HARD_IGN || cur_act == new_act)
3362 act.sa_handler = SIG_DFL;
3365 act.sa_handler = onsig;
3366 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3367 sigfillset(&act.sa_mask); /* ditto */
3370 act.sa_handler = SIG_IGN;
3373 sigaction_set(signo, &act);
3378 /* mode flags for set_curjob */
3379 #define CUR_DELETE 2
3380 #define CUR_RUNNING 1
3381 #define CUR_STOPPED 0
3383 /* mode flags for dowait */
3384 #define DOWAIT_NONBLOCK WNOHANG
3385 #define DOWAIT_BLOCK 0
3388 /* pgrp of shell on invocation */
3389 static int initialpgrp; //references:2
3390 static int ttyfd = -1; //5
3393 static struct job *jobtab; //5
3395 static unsigned njobs; //4
3397 static struct job *curjob; //lots
3398 /* number of presumed living untracked jobs */
3399 static int jobless; //4
3402 set_curjob(struct job *jp, unsigned mode)
3405 struct job **jpp, **curp;
3407 /* first remove from list */
3408 jpp = curp = &curjob;
3413 jpp = &jp1->prev_job;
3415 *jpp = jp1->prev_job;
3417 /* Then re-insert in correct position */
3425 /* job being deleted */
3428 /* newly created job or backgrounded job,
3429 put after all stopped jobs. */
3433 if (!jp1 || jp1->state != JOBSTOPPED)
3436 jpp = &jp1->prev_job;
3442 /* newly stopped job - becomes curjob */
3443 jp->prev_job = *jpp;
3451 jobno(const struct job *jp)
3453 return jp - jobtab + 1;
3458 * Convert a job name to a job structure.
3461 #define getjob(name, getctl) getjob(name)
3464 getjob(const char *name, int getctl)
3468 const char *err_msg = "%s: no such job";
3472 char *(*match)(const char *, const char *);
3487 if (c == '+' || c == '%') {
3489 err_msg = "No current job";
3495 err_msg = "No previous job";
3506 jp = jobtab + num - 1;
3521 if (match(jp->ps[0].cmd, p)) {
3525 err_msg = "%s: ambiguous";
3535 err_msg = "job %s not created under job control";
3536 if (getctl && jp->jobctl == 0)
3541 ash_msg_and_raise_error(err_msg, name);
3545 * Mark a job structure as unused.
3548 freejob(struct job *jp)
3550 struct procstat *ps;
3554 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3555 if (ps->cmd != nullstr)
3558 if (jp->ps != &jp->ps0)
3561 set_curjob(jp, CUR_DELETE);
3567 xtcsetpgrp(int fd, pid_t pgrp)
3569 if (tcsetpgrp(fd, pgrp))
3570 ash_msg_and_raise_error("can't set tty process group (%m)");
3574 * Turn job control on and off.
3576 * Note: This code assumes that the third arg to ioctl is a character
3577 * pointer, which is true on Berkeley systems but not System V. Since
3578 * System V doesn't have job control yet, this isn't a problem now.
3580 * Called with interrupts off.
3588 if (on == doing_jobctl || rootshell == 0)
3592 ofd = fd = open(_PATH_TTY, O_RDWR);
3594 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3595 * That sometimes helps to acquire controlling tty.
3596 * Obviously, a workaround for bugs when someone
3597 * failed to provide a controlling tty to bash! :) */
3603 fd = fcntl(fd, F_DUPFD, 10);
3608 /* fd is a tty at this point */
3609 close_on_exec_on(fd);
3610 do { /* while we are in the background */
3611 pgrp = tcgetpgrp(fd);
3614 ash_msg("can't access tty; job control turned off");
3618 if (pgrp == getpgrp())
3629 xtcsetpgrp(fd, pgrp);
3631 /* turning job control off */
3634 /* was xtcsetpgrp, but this can make exiting ash
3635 * loop forever if pty is already deleted */
3636 tcsetpgrp(fd, pgrp);
3650 static int FAST_FUNC
3651 killcmd(int argc, char **argv)
3654 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3656 if (argv[i][0] == '%') {
3657 struct job *jp = getjob(argv[i], 0);
3658 unsigned pid = jp->ps[0].pid;
3659 /* Enough space for ' -NNN<nul>' */
3660 argv[i] = alloca(sizeof(int)*3 + 3);
3661 /* kill_main has matching code to expect
3662 * leading space. Needed to not confuse
3663 * negative pids with "kill -SIGNAL_NO" syntax */
3664 sprintf(argv[i], " -%u", pid);
3666 } while (argv[++i]);
3668 return kill_main(argc, argv);
3672 showpipe(struct job *jp, FILE *out)
3674 struct procstat *sp;
3675 struct procstat *spend;
3677 spend = jp->ps + jp->nprocs;
3678 for (sp = jp->ps + 1; sp < spend; sp++)
3679 fprintf(out, " | %s", sp->cmd);
3680 outcslow('\n', out);
3681 flush_stdout_stderr();
3686 restartjob(struct job *jp, int mode)
3688 struct procstat *ps;
3694 if (jp->state == JOBDONE)
3696 jp->state = JOBRUNNING;
3698 if (mode == FORK_FG)
3699 xtcsetpgrp(ttyfd, pgid);
3700 killpg(pgid, SIGCONT);
3704 if (WIFSTOPPED(ps->status)) {
3710 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3715 static int FAST_FUNC
3716 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3723 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3728 jp = getjob(*argv, 1);
3729 if (mode == FORK_BG) {
3730 set_curjob(jp, CUR_RUNNING);
3731 fprintf(out, "[%d] ", jobno(jp));
3733 outstr(jp->ps->cmd, out);
3735 retval = restartjob(jp, mode);
3736 } while (*argv && *++argv);
3742 sprint_status(char *s, int status, int sigonly)
3748 if (!WIFEXITED(status)) {
3750 if (WIFSTOPPED(status))
3751 st = WSTOPSIG(status);
3754 st = WTERMSIG(status);
3756 if (st == SIGINT || st == SIGPIPE)
3759 if (WIFSTOPPED(status))
3764 col = fmtstr(s, 32, strsignal(st));
3765 if (WCOREDUMP(status)) {
3766 col += fmtstr(s + col, 16, " (core dumped)");
3768 } else if (!sigonly) {
3769 st = WEXITSTATUS(status);
3771 col = fmtstr(s, 16, "Done(%d)", st);
3773 col = fmtstr(s, 16, "Done");
3780 dowait(int wait_flags, struct job *job)
3785 struct job *thisjob;
3788 TRACE(("dowait(0x%x) called\n", wait_flags));
3790 /* Do a wait system call. If job control is compiled in, we accept
3791 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3792 * NB: _not_ safe_waitpid, we need to detect EINTR */
3793 pid = waitpid(-1, &status,
3794 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3795 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3796 pid, status, errno, strerror(errno)));
3802 for (jp = curjob; jp; jp = jp->prev_job) {
3803 struct procstat *sp;
3804 struct procstat *spend;
3805 if (jp->state == JOBDONE)
3808 spend = jp->ps + jp->nprocs;
3811 if (sp->pid == pid) {
3812 TRACE(("Job %d: changing status of proc %d "
3813 "from 0x%x to 0x%x\n",
3814 jobno(jp), pid, sp->status, status));
3815 sp->status = status;
3818 if (sp->status == -1)
3821 if (state == JOBRUNNING)
3823 if (WIFSTOPPED(sp->status)) {
3824 jp->stopstatus = sp->status;
3828 } while (++sp < spend);
3833 if (!WIFSTOPPED(status))
3839 if (state != JOBRUNNING) {
3840 thisjob->changed = 1;
3842 if (thisjob->state != state) {
3843 TRACE(("Job %d: changing state from %d to %d\n",
3844 jobno(thisjob), thisjob->state, state));
3845 thisjob->state = state;
3847 if (state == JOBSTOPPED) {
3848 set_curjob(thisjob, CUR_STOPPED);
3857 if (thisjob && thisjob == job) {
3861 len = sprint_status(s, status, 1);
3872 blocking_wait_with_raise_on_sig(struct job *job)
3874 pid_t pid = dowait(DOWAIT_BLOCK, job);
3875 if (pid <= 0 && pending_sig)
3876 raise_exception(EXSIG);
3882 showjob(FILE *out, struct job *jp, int mode)
3884 struct procstat *ps;
3885 struct procstat *psend;
3892 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3893 /* just output process (group) id of pipeline */
3894 fprintf(out, "%d\n", ps->pid);
3898 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3903 else if (curjob && jp == curjob->prev_job)
3906 if (mode & SHOW_PIDS)
3907 col += fmtstr(s + col, 16, "%d ", ps->pid);
3909 psend = ps + jp->nprocs;
3911 if (jp->state == JOBRUNNING) {
3912 strcpy(s + col, "Running");
3913 col += sizeof("Running") - 1;
3915 int status = psend[-1].status;
3916 if (jp->state == JOBSTOPPED)
3917 status = jp->stopstatus;
3918 col += sprint_status(s + col, status, 0);
3920 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3922 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3923 * or prints several "PID | <cmdN>" lines,
3924 * depending on SHOW_PIDS bit.
3925 * We do not print status of individual processes
3926 * between PID and <cmdN>. bash does it, but not very well:
3927 * first line shows overall job status, not process status,
3928 * making it impossible to know 1st process status.
3932 /* for each process */
3935 if (mode & SHOW_PIDS)
3936 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3938 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3941 fprintf(out, "%s", ps->cmd);
3945 outcslow('\n', out);
3949 if (jp->state == JOBDONE) {
3950 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3956 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3957 * statuses have changed since the last call to showjobs.
3960 showjobs(FILE *out, int mode)
3964 TRACE(("showjobs(0x%x) called\n", mode));
3966 /* Handle all finished jobs */
3967 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3970 for (jp = curjob; jp; jp = jp->prev_job) {
3971 if (!(mode & SHOW_CHANGED) || jp->changed) {
3972 showjob(out, jp, mode);
3977 static int FAST_FUNC
3978 jobscmd(int argc UNUSED_PARAM, char **argv)
3983 while ((m = nextopt("lp")) != '\0') {
3987 mode |= SHOW_ONLY_PGID;
3993 showjob(stdout, getjob(*argv, 0), mode);
3996 showjobs(stdout, mode);
4003 getstatus(struct job *job)
4008 status = job->ps[job->nprocs - 1].status;
4009 retval = WEXITSTATUS(status);
4010 if (!WIFEXITED(status)) {
4012 retval = WSTOPSIG(status);
4013 if (!WIFSTOPPED(status))
4016 /* XXX: limits number of signals */
4017 retval = WTERMSIG(status);
4019 if (retval == SIGINT)
4025 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4026 jobno(job), job->nprocs, status, retval));
4030 static int FAST_FUNC
4031 waitcmd(int argc UNUSED_PARAM, char **argv)
4038 raise_exception(EXSIG);
4045 /* wait for all jobs */
4049 if (!jp) /* no running procs */
4051 if (jp->state == JOBRUNNING)
4057 * "When bash is waiting for an asynchronous command via
4058 * the wait builtin, the reception of a signal for which a trap
4059 * has been set will cause the wait builtin to return immediately
4060 * with an exit status greater than 128, immediately after which
4061 * the trap is executed."
4062 * Do we do it that way? */
4063 blocking_wait_with_raise_on_sig(NULL);
4069 if (**argv != '%') {
4070 pid_t pid = number(*argv);
4075 if (job->ps[job->nprocs - 1].pid == pid)
4077 job = job->prev_job;
4080 job = getjob(*argv, 0);
4081 /* loop until process terminated or stopped */
4082 while (job->state == JOBRUNNING)
4083 blocking_wait_with_raise_on_sig(NULL);
4085 retval = getstatus(job);
4098 struct job *jp, *jq;
4100 len = njobs * sizeof(*jp);
4102 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4104 offset = (char *)jp - (char *)jq;
4106 /* Relocate pointers */
4109 jq = (struct job *)((char *)jq + l);
4113 #define joff(p) ((struct job *)((char *)(p) + l))
4114 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4115 if (joff(jp)->ps == &jq->ps0)
4116 jmove(joff(jp)->ps);
4117 if (joff(jp)->prev_job)
4118 jmove(joff(jp)->prev_job);
4128 jp = (struct job *)((char *)jp + len);
4132 } while (--jq >= jp);
4137 * Return a new job structure.
4138 * Called with interrupts off.
4141 makejob(/*union node *node,*/ int nprocs)
4146 for (i = njobs, jp = jobtab; ; jp++) {
4153 if (jp->state != JOBDONE || !jp->waited)
4162 memset(jp, 0, sizeof(*jp));
4164 /* jp->jobctl is a bitfield.
4165 * "jp->jobctl |= jobctl" likely to give awful code */
4169 jp->prev_job = curjob;
4174 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4176 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4183 * Return a string identifying a command (to be printed by the
4186 static char *cmdnextc;
4189 cmdputs(const char *s)
4191 static const char vstype[VSTYPE + 1][3] = {
4192 "", "}", "-", "+", "?", "=",
4193 "%", "%%", "#", "##"
4194 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4197 const char *p, *str;
4201 unsigned char subtype = 0;
4204 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4206 while ((c = *p++) != 0) {
4214 if ((subtype & VSTYPE) == VSLENGTH)
4218 if (!(subtype & VSQUOTE) == !(quoted & 1))
4224 str = "\"}" + !(quoted & 1);
4231 case CTLBACKQ+CTLQUOTE:
4234 #if ENABLE_SH_MATH_SUPPORT
4249 if ((subtype & VSTYPE) != VSNORMAL)
4251 str = vstype[subtype & VSTYPE];
4252 if (subtype & VSNUL)
4261 /* These can only happen inside quotes */
4274 while ((c = *str++) != '\0') {
4279 USTPUTC('"', nextc);
4285 /* cmdtxt() and cmdlist() call each other */
4286 static void cmdtxt(union node *n);
4289 cmdlist(union node *np, int sep)
4291 for (; np; np = np->narg.next) {
4295 if (sep && np->narg.next)
4301 cmdtxt(union node *n)
4304 struct nodelist *lp;
4315 lp = n->npipe.cmdlist;
4333 cmdtxt(n->nbinary.ch1);
4349 cmdtxt(n->nif.test);
4351 if (n->nif.elsepart) {
4352 cmdtxt(n->nif.ifpart);
4354 n = n->nif.elsepart;
4372 cmdtxt(n->nbinary.ch1);
4382 cmdputs(n->nfor.var);
4384 cmdlist(n->nfor.args, 1);
4389 cmdputs(n->narg.text);
4393 cmdlist(n->ncmd.args, 1);
4394 cmdlist(n->ncmd.redirect, 0);
4407 cmdputs(n->ncase.expr->narg.text);
4409 for (np = n->ncase.cases; np; np = np->nclist.next) {
4410 cmdtxt(np->nclist.pattern);
4412 cmdtxt(np->nclist.body);
4426 #if ENABLE_ASH_BASH_COMPAT
4441 cmdputs(utoa(n->nfile.fd));
4443 if (n->type == NTOFD || n->type == NFROMFD) {
4444 cmdputs(utoa(n->ndup.dupfd));
4453 commandtext(union node *n)
4457 STARTSTACKSTR(cmdnextc);
4459 name = stackblock();
4460 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4461 name, cmdnextc, cmdnextc));
4462 return ckstrdup(name);
4467 * Fork off a subshell. If we are doing job control, give the subshell its
4468 * own process group. Jp is a job structure that the job is to be added to.
4469 * N is the command that will be evaluated by the child. Both jp and n may
4470 * be NULL. The mode parameter can be one of the following:
4471 * FORK_FG - Fork off a foreground process.
4472 * FORK_BG - Fork off a background process.
4473 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4474 * process group even if job control is on.
4476 * When job control is turned off, background processes have their standard
4477 * input redirected to /dev/null (except for the second and later processes
4480 * Called with interrupts off.
4483 * Clear traps on a fork.
4490 for (tp = trap; tp < &trap[NSIG]; tp++) {
4491 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4493 if (trap_ptr == trap)
4495 /* else: it "belongs" to trap_ptr vector, don't free */
4497 if ((tp - trap) != 0)
4498 setsignal(tp - trap);
4504 /* Lives far away from here, needed for forkchild */
4505 static void closescript(void);
4507 /* Called after fork(), in child */
4508 static NOINLINE void
4509 forkchild(struct job *jp, union node *n, int mode)
4513 TRACE(("Child shell %d\n", getpid()));
4517 /* man bash: "Non-builtin commands run by bash have signal handlers
4518 * set to the values inherited by the shell from its parent".
4519 * Do we do it correctly? */
4523 if (mode == FORK_NOJOB /* is it `xxx` ? */
4524 && n && n->type == NCMD /* is it single cmd? */
4525 /* && n->ncmd.args->type == NARG - always true? */
4526 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4527 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4528 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4530 TRACE(("Trap hack\n"));
4531 /* Awful hack for `trap` or $(trap).
4533 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4534 * contains an example where "trap" is executed in a subshell:
4536 * save_traps=$(trap)
4538 * eval "$save_traps"
4540 * Standard does not say that "trap" in subshell shall print
4541 * parent shell's traps. It only says that its output
4542 * must have suitable form, but then, in the above example
4543 * (which is not supposed to be normative), it implies that.
4545 * bash (and probably other shell) does implement it
4546 * (traps are reset to defaults, but "trap" still shows them),
4547 * but as a result, "trap" logic is hopelessly messed up:
4550 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4551 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4552 * # true | trap <--- trap is in subshell - no output (ditto)
4553 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4554 * trap -- 'echo Ho' SIGWINCH
4555 * # echo `(trap)` <--- in subshell in subshell - output
4556 * trap -- 'echo Ho' SIGWINCH
4557 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4558 * trap -- 'echo Ho' SIGWINCH
4560 * The rules when to forget and when to not forget traps
4561 * get really complex and nonsensical.
4563 * Our solution: ONLY bare $(trap) or `trap` is special.
4565 /* Save trap handler strings for trap builtin to print */
4566 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4567 /* Fall through into clearing traps */
4571 /* do job control only in root shell */
4573 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4576 if (jp->nprocs == 0)
4579 pgrp = jp->ps[0].pid;
4580 /* this can fail because we are doing it in the parent also */
4582 if (mode == FORK_FG)
4583 xtcsetpgrp(ttyfd, pgrp);
4588 if (mode == FORK_BG) {
4589 /* man bash: "When job control is not in effect,
4590 * asynchronous commands ignore SIGINT and SIGQUIT" */
4593 if (jp->nprocs == 0) {
4595 if (open(bb_dev_null, O_RDONLY) != 0)
4596 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4600 if (iflag) { /* why if iflag only? */
4605 * "In all cases, bash ignores SIGQUIT. Non-builtin
4606 * commands run by bash have signal handlers
4607 * set to the values inherited by the shell
4609 * Take care of the second rule: */
4613 if (n && n->type == NCMD
4614 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4616 TRACE(("Job hack\n"));
4617 /* "jobs": we do not want to clear job list for it,
4618 * instead we remove only _its_ own_ job from job list.
4619 * This makes "jobs .... | cat" more useful.
4625 for (jp = curjob; jp; jp = jp->prev_job)
4630 /* Called after fork(), in parent */
4632 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4635 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4637 TRACE(("In parent shell: child = %d\n", pid));
4639 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4645 if (mode != FORK_NOJOB && jp->jobctl) {
4648 if (jp->nprocs == 0)
4651 pgrp = jp->ps[0].pid;
4652 /* This can fail because we are doing it in the child also */
4656 if (mode == FORK_BG) {
4657 backgndpid = pid; /* set $! */
4658 set_curjob(jp, CUR_RUNNING);
4661 struct procstat *ps = &jp->ps[jp->nprocs++];
4666 if (doing_jobctl && n)
4667 ps->cmd = commandtext(n);
4673 forkshell(struct job *jp, union node *n, int mode)
4677 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4680 TRACE(("Fork failed, errno=%d", errno));
4683 ash_msg_and_raise_error("can't fork");
4686 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4687 forkchild(jp, n, mode);
4689 forkparent(jp, n, mode, pid);
4695 * Wait for job to finish.
4697 * Under job control we have the problem that while a child process
4698 * is running interrupts generated by the user are sent to the child
4699 * but not to the shell. This means that an infinite loop started by
4700 * an interactive user may be hard to kill. With job control turned off,
4701 * an interactive user may place an interactive program inside a loop.
4702 * If the interactive program catches interrupts, the user doesn't want
4703 * these interrupts to also abort the loop. The approach we take here
4704 * is to have the shell ignore interrupt signals while waiting for a
4705 * foreground process to terminate, and then send itself an interrupt
4706 * signal if the child process was terminated by an interrupt signal.
4707 * Unfortunately, some programs want to do a bit of cleanup and then
4708 * exit on interrupt; unless these processes terminate themselves by
4709 * sending a signal to themselves (instead of calling exit) they will
4710 * confuse this approach.
4712 * Called with interrupts off.
4715 waitforjob(struct job *jp)
4719 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4722 while (jp->state == JOBRUNNING) {
4723 /* In non-interactive shells, we _can_ get
4724 * a keyboard signal here and be EINTRed,
4725 * but we just loop back, waiting for command to complete.
4728 * "If bash is waiting for a command to complete and receives
4729 * a signal for which a trap has been set, the trap
4730 * will not be executed until the command completes."
4732 * Reality is that even if trap is not set, bash
4733 * will not act on the signal until command completes.
4734 * Try this. sleep5intoff.c:
4735 * #include <signal.h>
4736 * #include <unistd.h>
4739 * sigemptyset(&set);
4740 * sigaddset(&set, SIGINT);
4741 * sigaddset(&set, SIGQUIT);
4742 * sigprocmask(SIG_BLOCK, &set, NULL);
4746 * $ bash -c './sleep5intoff; echo hi'
4747 * ^C^C^C^C <--- pressing ^C once a second
4749 * $ bash -c './sleep5intoff; echo hi'
4750 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4753 dowait(DOWAIT_BLOCK, jp);
4760 xtcsetpgrp(ttyfd, rootpid);
4762 * This is truly gross.
4763 * If we're doing job control, then we did a TIOCSPGRP which
4764 * caused us (the shell) to no longer be in the controlling
4765 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4766 * intuit from the subprocess exit status whether a SIGINT
4767 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4769 if (jp->sigint) /* TODO: do the same with all signals */
4770 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4772 if (jp->state == JOBDONE)
4779 * return 1 if there are stopped jobs, otherwise 0
4791 if (jp && jp->state == JOBSTOPPED) {
4792 out2str("You have stopped jobs.\n");
4801 /* ============ redir.c
4803 * Code for dealing with input/output redirection.
4806 #define EMPTY -2 /* marks an unused slot in redirtab */
4807 #define CLOSED -3 /* marks a slot of previously-closed fd */
4810 * Open a file in noclobber mode.
4811 * The code was copied from bash.
4814 noclobberopen(const char *fname)
4817 struct stat finfo, finfo2;
4820 * If the file exists and is a regular file, return an error
4823 r = stat(fname, &finfo);
4824 if (r == 0 && S_ISREG(finfo.st_mode)) {
4830 * If the file was not present (r != 0), make sure we open it
4831 * exclusively so that if it is created before we open it, our open
4832 * will fail. Make sure that we do not truncate an existing file.
4833 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4834 * file was not a regular file, we leave O_EXCL off.
4837 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4838 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4840 /* If the open failed, return the file descriptor right away. */
4845 * OK, the open succeeded, but the file may have been changed from a
4846 * non-regular file to a regular file between the stat and the open.
4847 * We are assuming that the O_EXCL open handles the case where FILENAME
4848 * did not exist and is symlinked to an existing file between the stat
4853 * If we can open it and fstat the file descriptor, and neither check
4854 * revealed that it was a regular file, and the file has not been
4855 * replaced, return the file descriptor.
4857 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4858 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4861 /* The file has been replaced. badness. */
4868 * Handle here documents. Normally we fork off a process to write the
4869 * data to a pipe. If the document is short, we can stuff the data in
4870 * the pipe without forking.
4872 /* openhere needs this forward reference */
4873 static void expandhere(union node *arg, int fd);
4875 openhere(union node *redir)
4881 ash_msg_and_raise_error("pipe call failed");
4882 if (redir->type == NHERE) {
4883 len = strlen(redir->nhere.doc->narg.text);
4884 if (len <= PIPE_BUF) {
4885 full_write(pip[1], redir->nhere.doc->narg.text, len);
4889 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4892 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4893 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4894 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4895 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4896 signal(SIGPIPE, SIG_DFL);
4897 if (redir->type == NHERE)
4898 full_write(pip[1], redir->nhere.doc->narg.text, len);
4900 expandhere(redir->nhere.doc, pip[1]);
4901 _exit(EXIT_SUCCESS);
4909 openredirect(union node *redir)
4914 switch (redir->nfile.type) {
4916 fname = redir->nfile.expfname;
4917 f = open(fname, O_RDONLY);
4922 fname = redir->nfile.expfname;
4923 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4928 #if ENABLE_ASH_BASH_COMPAT
4931 /* Take care of noclobber mode. */
4933 fname = redir->nfile.expfname;
4934 f = noclobberopen(fname);
4941 fname = redir->nfile.expfname;
4942 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4947 fname = redir->nfile.expfname;
4948 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4956 /* Fall through to eliminate warning. */
4957 /* Our single caller does this itself */
4964 f = openhere(redir);
4970 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4972 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4976 * Copy a file descriptor to be >= to. Returns -1
4977 * if the source file descriptor is closed, EMPTY if there are no unused
4978 * file descriptors left.
4980 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4981 * old code was doing close(to) prior to copyfd() to achieve the same */
4983 COPYFD_EXACT = (int)~(INT_MAX),
4984 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4987 copyfd(int from, int to)
4991 if (to & COPYFD_EXACT) {
4992 to &= ~COPYFD_EXACT;
4994 newfd = dup2(from, to);
4996 newfd = fcntl(from, F_DUPFD, to);
4999 if (errno == EMFILE)
5001 /* Happens when source fd is not open: try "echo >&99" */
5002 ash_msg_and_raise_error("%d: %m", from);
5007 /* Struct def and variable are moved down to the first usage site */
5012 struct redirtab *next;
5015 struct two_fd_t two_fd[];
5017 #define redirlist (G_var.redirlist)
5019 static int need_to_remember(struct redirtab *rp, int fd)
5023 if (!rp) /* remembering was not requested */
5026 for (i = 0; i < rp->pair_count; i++) {
5027 if (rp->two_fd[i].orig == fd) {
5028 /* already remembered */
5035 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5036 static int is_hidden_fd(struct redirtab *rp, int fd)
5039 struct parsefile *pf;
5052 fd |= COPYFD_RESTORE;
5053 for (i = 0; i < rp->pair_count; i++) {
5054 if (rp->two_fd[i].copy == fd) {
5062 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5063 * old file descriptors are stashed away so that the redirection can be
5064 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5065 * standard output, and the standard error if it becomes a duplicate of
5066 * stdout, is saved in memory.
5068 /* flags passed to redirect */
5069 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5070 #define REDIR_SAVEFD2 03 /* set preverrout */
5072 redirect(union node *redir, int flags)
5074 struct redirtab *sv;
5079 int copied_fd2 = -1;
5089 if (flags & REDIR_PUSH) {
5090 union node *tmp = redir;
5093 #if ENABLE_ASH_BASH_COMPAT
5094 if (redir->nfile.type == NTO2)
5097 tmp = tmp->nfile.next;
5099 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5100 sv->next = redirlist;
5101 sv->pair_count = sv_pos;
5103 sv->nullredirs = g_nullredirs - 1;
5105 while (sv_pos > 0) {
5107 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5112 fd = redir->nfile.fd;
5113 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5114 int right_fd = redir->ndup.dupfd;
5115 /* redirect from/to same file descriptor? */
5118 /* echo >&10 and 10 is a fd opened to the sh script? */
5119 if (is_hidden_fd(sv, right_fd)) {
5120 errno = EBADF; /* as if it is closed */
5121 ash_msg_and_raise_error("%d: %m", right_fd);
5125 newfd = openredirect(redir); /* always >= 0 */
5127 /* Descriptor wasn't open before redirect.
5128 * Mark it for close in the future */
5129 if (need_to_remember(sv, fd)) {
5130 goto remember_to_close;
5135 #if ENABLE_ASH_BASH_COMPAT
5138 if (need_to_remember(sv, fd)) {
5139 /* Copy old descriptor */
5140 i = fcntl(fd, F_DUPFD, 10);
5141 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5142 * are closed in popredir() in the child, preventing them from leaking
5143 * into child. (popredir() also cleans up the mess in case of failures)
5148 /* Strange error (e.g. "too many files" EMFILE?) */
5152 ash_msg_and_raise_error("%d: %m", fd);
5155 /* EBADF: it is not open - good, remember to close it */
5158 } else { /* fd is open, save its copy */
5159 /* "exec fd>&-" should not close fds
5160 * which point to script file(s).
5161 * Force them to be restored afterwards */
5162 if (is_hidden_fd(sv, fd))
5163 i |= COPYFD_RESTORE;
5167 sv->two_fd[sv_pos].orig = fd;
5168 sv->two_fd[sv_pos].copy = i;
5172 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5173 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5174 /* Don't want to trigger debugging */
5178 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5180 } else if (fd != newfd) { /* move newfd to fd */
5181 copyfd(newfd, fd | COPYFD_EXACT);
5182 #if ENABLE_ASH_BASH_COMPAT
5183 if (!(redir->nfile.type == NTO2 && fd == 2))
5187 #if ENABLE_ASH_BASH_COMPAT
5188 if (redir->nfile.type == NTO2 && fd == 1) {
5189 /* We already redirected it to fd 1, now copy it to 2 */
5195 } while ((redir = redir->nfile.next) != NULL);
5198 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5199 preverrout_fd = copied_fd2;
5203 * Undo the effects of the last redirection.
5206 popredir(int drop, int restore)
5208 struct redirtab *rp;
5211 if (--g_nullredirs >= 0)
5215 for (i = 0; i < rp->pair_count; i++) {
5216 int fd = rp->two_fd[i].orig;
5217 int copy = rp->two_fd[i].copy;
5218 if (copy == CLOSED) {
5223 if (copy != EMPTY) {
5224 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5225 copy &= ~COPYFD_RESTORE;
5227 copyfd(copy, fd | COPYFD_EXACT);
5229 close(copy & ~COPYFD_RESTORE);
5232 redirlist = rp->next;
5233 g_nullredirs = rp->nullredirs;
5239 * Undo all redirections. Called on error or interrupt.
5243 * Discard all saved file descriptors.
5246 clearredir(int drop)
5252 popredir(drop, /*restore:*/ 0);
5257 redirectsafe(union node *redir, int flags)
5260 volatile int saveint;
5261 struct jmploc *volatile savehandler = exception_handler;
5262 struct jmploc jmploc;
5265 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5266 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5268 exception_handler = &jmploc;
5269 redirect(redir, flags);
5271 exception_handler = savehandler;
5272 if (err && exception_type != EXERROR)
5273 longjmp(exception_handler->loc, 1);
5274 RESTORE_INT(saveint);
5279 /* ============ Routines to expand arguments to commands
5281 * We have to deal with backquotes, shell variables, and file metacharacters.
5284 #if ENABLE_SH_MATH_SUPPORT
5286 ash_arith(const char *s)
5288 arith_eval_hooks_t math_hooks;
5292 math_hooks.lookupvar = lookupvar;
5293 math_hooks.setvar = setvar;
5294 math_hooks.endofname = endofname;
5297 result = arith(s, &errcode, &math_hooks);
5300 ash_msg_and_raise_error("exponent less than 0");
5302 ash_msg_and_raise_error("divide by zero");
5304 ash_msg_and_raise_error("expression recursion loop detected");
5305 raise_error_syntax(s);
5316 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5317 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5318 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5319 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5320 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5321 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5322 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5323 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5324 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5328 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5329 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5330 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5331 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5332 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5335 * Structure specifying which parts of the string should be searched
5336 * for IFS characters.
5339 struct ifsregion *next; /* next region in list */
5340 int begoff; /* offset of start of region */
5341 int endoff; /* offset of end of region */
5342 int nulonly; /* search for nul bytes only */
5346 struct strlist *list;
5347 struct strlist **lastp;
5350 /* output of current string */
5351 static char *expdest;
5352 /* list of back quote expressions */
5353 static struct nodelist *argbackq;
5354 /* first struct in list of ifs regions */
5355 static struct ifsregion ifsfirst;
5356 /* last struct in list */
5357 static struct ifsregion *ifslastp;
5358 /* holds expanded arg list */
5359 static struct arglist exparg;
5369 expdest = makestrspace(32, expdest);
5370 len = fmtstr(expdest, 32, arith_t_fmt, num);
5371 STADJUST(len, expdest);
5376 esclen(const char *start, const char *p)
5380 while (p > start && (unsigned char)*--p == CTLESC) {
5387 * Remove any CTLESC characters from a string.
5390 rmescapes(char *str, int flag)
5392 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5396 unsigned protect_against_glob;
5399 p = strpbrk(str, qchars);
5405 if (flag & RMESCAPE_ALLOC) {
5406 size_t len = p - str;
5407 size_t fulllen = len + strlen(p) + 1;
5409 if (flag & RMESCAPE_GROW) {
5410 r = makestrspace(fulllen, expdest);
5411 } else if (flag & RMESCAPE_HEAP) {
5412 r = ckmalloc(fulllen);
5414 r = stalloc(fulllen);
5418 q = (char *)memcpy(q, str, len) + len;
5422 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5423 globbing = flag & RMESCAPE_GLOB;
5424 protect_against_glob = globbing;
5426 if ((unsigned char)*p == CTLQUOTEMARK) {
5427 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5428 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5429 // Note: both inquotes and protect_against_glob only affect whether
5430 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5431 inquotes = ~inquotes;
5433 protect_against_glob = globbing;
5437 /* naked back slash */
5438 protect_against_glob = 0;
5441 if ((unsigned char)*p == CTLESC) {
5443 if (protect_against_glob && inquotes && *p != '/') {
5447 protect_against_glob = globbing;
5452 if (flag & RMESCAPE_GROW) {
5454 STADJUST(q - r + 1, expdest);
5458 #define pmatch(a, b) !fnmatch((a), (b), 0)
5461 * Prepare a pattern for a expmeta (internal glob(3)) call.
5463 * Returns an stalloced string.
5466 preglob(const char *pattern, int quoted, int flag)
5468 flag |= RMESCAPE_GLOB;
5470 flag |= RMESCAPE_QUOTED;
5472 return rmescapes((char *)pattern, flag);
5476 * Put a string on the stack.
5479 memtodest(const char *p, size_t len, int syntax, int quotes)
5483 q = makestrspace(quotes ? len * 2 : len, q);
5486 unsigned char c = *p++;
5490 int n = SIT(c, syntax);
5491 if (n == CCTL || n == CBACK)
5501 strtodest(const char *p, int syntax, int quotes)
5503 memtodest(p, strlen(p), syntax, quotes);
5507 * Record the fact that we have to scan this region of the
5508 * string for IFS characters.
5511 recordregion(int start, int end, int nulonly)
5513 struct ifsregion *ifsp;
5515 if (ifslastp == NULL) {
5519 ifsp = ckzalloc(sizeof(*ifsp));
5520 /*ifsp->next = NULL; - ckzalloc did it */
5521 ifslastp->next = ifsp;
5525 ifslastp->begoff = start;
5526 ifslastp->endoff = end;
5527 ifslastp->nulonly = nulonly;
5531 removerecordregions(int endoff)
5533 if (ifslastp == NULL)
5536 if (ifsfirst.endoff > endoff) {
5537 while (ifsfirst.next != NULL) {
5538 struct ifsregion *ifsp;
5540 ifsp = ifsfirst.next->next;
5541 free(ifsfirst.next);
5542 ifsfirst.next = ifsp;
5545 if (ifsfirst.begoff > endoff)
5548 ifslastp = &ifsfirst;
5549 ifsfirst.endoff = endoff;
5554 ifslastp = &ifsfirst;
5555 while (ifslastp->next && ifslastp->next->begoff < endoff)
5556 ifslastp=ifslastp->next;
5557 while (ifslastp->next != NULL) {
5558 struct ifsregion *ifsp;
5560 ifsp = ifslastp->next->next;
5561 free(ifslastp->next);
5562 ifslastp->next = ifsp;
5565 if (ifslastp->endoff > endoff)
5566 ifslastp->endoff = endoff;
5570 exptilde(char *startp, char *p, int flags)
5576 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5581 while ((c = *++p) != '\0') {
5588 if (flags & EXP_VARTILDE)
5598 if (*name == '\0') {
5599 home = lookupvar(homestr);
5601 pw = getpwnam(name);
5606 if (!home || !*home)
5609 startloc = expdest - (char *)stackblock();
5610 strtodest(home, SQSYNTAX, quotes);
5611 recordregion(startloc, expdest - (char *)stackblock(), 0);
5619 * Execute a command inside back quotes. If it's a builtin command, we
5620 * want to save its output in a block obtained from malloc. Otherwise
5621 * we fork off a subprocess and get the output of the command via a pipe.
5622 * Should be called with interrupts off.
5624 struct backcmd { /* result of evalbackcmd */
5625 int fd; /* file descriptor to read from */
5626 int nleft; /* number of chars in buffer */
5627 char *buf; /* buffer */
5628 struct job *jp; /* job structure for command */
5631 /* These forward decls are needed to use "eval" code for backticks handling: */
5632 static uint8_t back_exitstatus; /* exit status of backquoted command */
5633 #define EV_EXIT 01 /* exit after evaluating tree */
5634 static void evaltree(union node *, int);
5636 static void FAST_FUNC
5637 evalbackcmd(union node *n, struct backcmd *result)
5648 saveherefd = herefd;
5656 ash_msg_and_raise_error("pipe call failed");
5657 jp = makejob(/*n,*/ 1);
5658 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5663 copyfd(pip[1], 1 | COPYFD_EXACT);
5667 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5671 result->fd = pip[0];
5674 herefd = saveherefd;
5676 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5677 result->fd, result->buf, result->nleft, result->jp));
5681 * Expand stuff in backwards quotes.
5684 expbackq(union node *cmd, int quoted, int quotes)
5692 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5693 struct stackmark smark;
5696 setstackmark(&smark);
5698 startloc = dest - (char *)stackblock();
5700 evalbackcmd(cmd, &in);
5701 popstackmark(&smark);
5708 memtodest(p, i, syntax, quotes);
5712 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5713 TRACE(("expbackq: read returns %d\n", i));
5722 back_exitstatus = waitforjob(in.jp);
5726 /* Eat all trailing newlines */
5728 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5733 recordregion(startloc, dest - (char *)stackblock(), 0);
5734 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5735 (dest - (char *)stackblock()) - startloc,
5736 (dest - (char *)stackblock()) - startloc,
5737 stackblock() + startloc));
5740 #if ENABLE_SH_MATH_SUPPORT
5742 * Expand arithmetic expression. Backup to start of expression,
5743 * evaluate, place result in (backed up) result, adjust string position.
5756 * This routine is slightly over-complicated for
5757 * efficiency. Next we scan backwards looking for the
5758 * start of arithmetic.
5760 start = stackblock();
5767 while ((unsigned char)*p != CTLARI) {
5771 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5776 esc = esclen(start, p);
5786 removerecordregions(begoff);
5793 rmescapes(p + 2, 0);
5795 len = cvtnum(ash_arith(p + 2));
5798 recordregion(begoff, begoff + len, 0);
5802 /* argstr needs it */
5803 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5806 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5807 * characters to allow for further processing. Otherwise treat
5808 * $@ like $* since no splitting will be performed.
5810 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5811 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5812 * for correct expansion of "B=$A" word.
5815 argstr(char *p, int flags, struct strlist *var_str_list)
5817 static const char spclchars[] ALIGN1 = {
5825 CTLBACKQ | CTLQUOTE,
5826 #if ENABLE_SH_MATH_SUPPORT
5831 const char *reject = spclchars;
5832 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5833 int breakall = flags & EXP_WORD;
5838 if (!(flags & EXP_VARTILDE)) {
5840 } else if (flags & EXP_VARTILDE2) {
5845 if (flags & EXP_TILDE) {
5848 flags &= ~EXP_TILDE;
5851 if (*q == CTLESC && (flags & EXP_QWORD))
5854 p = exptilde(p, q, flags);
5857 startloc = expdest - (char *)stackblock();
5861 length += strcspn(p + length, reject);
5865 #if ENABLE_SH_MATH_SUPPORT
5869 /* c == '=' || c == ':' || c == CTLENDARI */
5875 expdest = stack_nputstr(p, length, expdest);
5876 newloc = expdest - (char *)stackblock();
5877 if (breakall && !inquotes && newloc > startloc) {
5878 recordregion(startloc, newloc, 0);
5889 if (flags & EXP_VARTILDE2) {
5893 flags |= EXP_VARTILDE2;
5898 * sort of a hack - expand tildes in variable
5899 * assignments (after the first '=' and after ':'s).
5908 case CTLENDVAR: /* ??? */
5911 /* "$@" syntax adherence hack */
5913 && memcmp(p, dolatstr, 4) == 0
5914 && ( p[4] == CTLQUOTEMARK
5915 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5918 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5921 inquotes = !inquotes;
5934 p = evalvar(p, flags, var_str_list);
5938 case CTLBACKQ|CTLQUOTE:
5939 expbackq(argbackq->n, c, quotes);
5940 argbackq = argbackq->next;
5942 #if ENABLE_SH_MATH_SUPPORT
5955 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5958 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5959 // as part of a larger change when he added support for ${var/a/b}.
5960 // However, it broke # and % operators:
5964 //echo ${var#ab} abcdcd abcdcd
5965 //echo ${var##ab} abcdcd abcdcd
5966 //echo ${var#a*b} abcdcd ababcdcd (!)
5967 //echo ${var##a*b} cdcd cdcd
5968 //echo ${var#?} babcdcd ababcdcd (!)
5969 //echo ${var##?} babcdcd babcdcd
5970 //echo ${var#*} ababcdcd babcdcd (!)
5972 //echo ${var%cd} ababcd ababcd
5973 //echo ${var%%cd} ababcd abab (!)
5974 //echo ${var%c*d} ababcd ababcd
5975 //echo ${var%%c*d} abab ababcdcd (!)
5976 //echo ${var%?} ababcdc ababcdc
5977 //echo ${var%%?} ababcdc ababcdcd (!)
5978 //echo ${var%*} ababcdcd ababcdcd
5981 // Commenting it back out helped. Remove it completely if it really
5984 char *loc, *loc2; //, *full;
5990 int match; // = strlen(str);
5991 const char *s = loc2;
5998 match = pmatch(str, s); // this line was deleted
6000 // // chop off end if its '*'
6001 // full = strrchr(str, '*');
6002 // if (full && full != str)
6005 // // If str starts with '*' replace with s.
6006 // if ((*str == '*') && strlen(s) >= match) {
6007 // full = xstrdup(s);
6008 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6010 // full = xstrndup(str, match);
6011 // match = strncmp(s, full, strlen(full));
6015 if (match) // if (!match)
6017 if (quotes && (unsigned char)*loc == CTLESC)
6026 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6033 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6036 const char *s = loc2;
6041 match = pmatch(str, s);
6048 esc = esclen(startp, loc);
6059 static void varunset(const char *, const char *, const char *, int) NORETURN;
6061 varunset(const char *end, const char *var, const char *umsg, int varflags)
6067 msg = "parameter not set";
6069 if ((unsigned char)*end == CTLENDVAR) {
6070 if (varflags & VSNUL)
6076 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6079 #if ENABLE_ASH_BASH_COMPAT
6081 parse_sub_pattern(char *arg, int inquotes)
6083 char *idx, *repl = NULL;
6092 /* Only the first '/' seen is our separator */
6099 if (!inquotes && c == '\\' && arg[1] == '\\')
6100 arg++; /* skip both \\, not just first one */
6107 #endif /* ENABLE_ASH_BASH_COMPAT */
6110 subevalvar(char *p, char *str, int strloc, int subtype,
6111 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6113 struct nodelist *saveargbackq = argbackq;
6116 char *rmesc, *rmescend;
6117 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6118 IF_ASH_BASH_COMPAT(char null = '\0';)
6119 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6120 int saveherefd = herefd;
6121 int amount, workloc, resetloc;
6123 char *(*scan)(char*, char*, char*, char*, int, int);
6126 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6128 STPUTC('\0', expdest);
6129 herefd = saveherefd;
6130 argbackq = saveargbackq;
6131 startp = (char *)stackblock() + startloc;
6135 setvar(str, startp, 0);
6136 amount = startp - expdest;
6137 STADJUST(amount, expdest);
6140 #if ENABLE_ASH_BASH_COMPAT
6142 loc = str = stackblock() + strloc;
6143 /* Read POS in ${var:POS:LEN} */
6144 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6145 len = str - startp - 1;
6147 /* *loc != '\0', guaranteed by parser */
6151 /* Adjust the length by the number of escapes */
6152 for (ptr = startp; ptr < (str - 1); ptr++) {
6153 if ((unsigned char)*ptr == CTLESC) {
6161 if (*loc++ == ':') {
6165 /* Skip POS in ${var:POS:LEN} */
6167 while (*loc && *loc != ':') {
6169 * bash complains on: var=qwe; echo ${var:1a:123}
6171 ash_msg_and_raise_error(msg_illnum, str);
6175 if (*loc++ == ':') {
6179 if (pos >= orig_len) {
6183 if (len > (orig_len - pos))
6184 len = orig_len - pos;
6186 for (str = startp; pos; str++, pos--) {
6187 if (quotes && (unsigned char)*str == CTLESC)
6190 for (loc = startp; len; len--) {
6191 if (quotes && (unsigned char)*str == CTLESC)
6196 amount = loc - expdest;
6197 STADJUST(amount, expdest);
6202 varunset(p, str, startp, varflags);
6205 resetloc = expdest - (char *)stackblock();
6207 /* We'll comeback here if we grow the stack while handling
6208 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6209 * stack will need rebasing, and we'll need to remove our work
6212 IF_ASH_BASH_COMPAT(restart:)
6214 amount = expdest - ((char *)stackblock() + resetloc);
6215 STADJUST(-amount, expdest);
6216 startp = (char *)stackblock() + startloc;
6219 rmescend = (char *)stackblock() + strloc;
6221 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6222 if (rmesc != startp) {
6224 startp = (char *)stackblock() + startloc;
6228 str = (char *)stackblock() + strloc;
6229 preglob(str, varflags & VSQUOTE, 0);
6230 workloc = expdest - (char *)stackblock();
6232 #if ENABLE_ASH_BASH_COMPAT
6233 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6234 char *idx, *end, *restart_detect;
6237 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6242 /* If there's no pattern to match, return the expansion unmolested */
6250 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6252 /* No match, advance */
6253 restart_detect = stackblock();
6254 STPUTC(*idx, expdest);
6255 if (quotes && (unsigned char)*idx == CTLESC) {
6258 STPUTC(*idx, expdest);
6260 if (stackblock() != restart_detect)
6268 if (subtype == VSREPLACEALL) {
6270 if (quotes && (unsigned char)*idx == CTLESC)
6279 for (loc = repl; *loc; loc++) {
6280 restart_detect = stackblock();
6281 STPUTC(*loc, expdest);
6282 if (stackblock() != restart_detect)
6287 if (subtype == VSREPLACE) {
6289 restart_detect = stackblock();
6290 STPUTC(*idx, expdest);
6291 if (stackblock() != restart_detect)
6300 /* We've put the replaced text into a buffer at workloc, now
6301 * move it to the right place and adjust the stack.
6303 startp = stackblock() + startloc;
6304 STPUTC('\0', expdest);
6305 memmove(startp, stackblock() + workloc, len);
6306 startp[len++] = '\0';
6307 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6308 STADJUST(-amount, expdest);
6311 #endif /* ENABLE_ASH_BASH_COMPAT */
6313 subtype -= VSTRIMRIGHT;
6315 if (subtype < 0 || subtype > 7)
6318 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6319 zero = subtype >> 1;
6320 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6321 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6323 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6326 memmove(startp, loc, str - loc);
6327 loc = startp + (str - loc) - 1;
6330 amount = loc - expdest;
6331 STADJUST(amount, expdest);
6337 * Add the value of a specialized variable to the stack string.
6338 * name parameter (examples):
6339 * ash -c 'echo $1' name:'1='
6340 * ash -c 'echo $qwe' name:'qwe='
6341 * ash -c 'echo $$' name:'$='
6342 * ash -c 'echo ${$}' name:'$='
6343 * ash -c 'echo ${$##q}' name:'$=q'
6344 * ash -c 'echo ${#$}' name:'$='
6345 * note: examples with bad shell syntax:
6346 * ash -c 'echo ${#$1}' name:'$=1'
6347 * ash -c 'echo ${#1#}' name:'1=#'
6349 static NOINLINE ssize_t
6350 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6357 int subtype = varflags & VSTYPE;
6358 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6359 int quoted = varflags & VSQUOTE;
6360 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6370 num = shellparam.nparam;
6378 goto check_1char_name;
6380 expdest = makestrspace(NOPTS, expdest);
6381 for (i = NOPTS - 1; i >= 0; i--) {
6383 USTPUTC(optletters(i), expdest);
6389 /* handles cases similar to ${#$1} */
6390 if (name[2] != '\0')
6391 raise_error_syntax("bad substitution");
6398 if (quoted && (flags & EXP_FULL)) {
6399 /* note: this is not meant as PEOF value */
6400 sep = 1 << CHAR_BIT;
6405 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6406 i = SIT(sep, syntax);
6407 if (quotes && (i == CCTL || i == CBACK))
6413 while ((p = *ap++) != NULL) {
6416 partlen = strlen(p);
6419 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6420 memtodest(p, partlen, syntax, quotes);
6426 if (subtype == VSPLUS || subtype == VSLENGTH) {
6432 /* note: may put NUL despite sep != 0
6433 * (see sep = 1 << CHAR_BIT above) */
6439 } /* case '@' and '*' */
6450 num = atoi(name); /* number(name) fails on ${N#str} etc */
6451 if (num < 0 || num > shellparam.nparam)
6453 p = num ? shellparam.p[num - 1] : arg0;
6456 /* NB: name has form "VAR=..." */
6458 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6459 * which should be considered before we check variables. */
6461 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6465 str = var_str_list->text;
6466 eq = strchr(str, '=');
6467 if (!eq) /* stop at first non-assignment */
6470 if (name_len == (unsigned)(eq - str)
6471 && strncmp(str, name, name_len) == 0
6474 /* goto value; - WRONG! */
6475 /* think "A=1 A=2 B=$A" */
6477 var_str_list = var_str_list->next;
6478 } while (var_str_list);
6482 p = lookupvar(name);
6488 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6489 memtodest(p, len, syntax, quotes);
6493 if (subtype == VSPLUS || subtype == VSLENGTH)
6494 STADJUST(-len, expdest);
6499 * Expand a variable, and return a pointer to the next character in the
6503 evalvar(char *p, int flags, struct strlist *var_str_list)
6514 varflags = (unsigned char) *p++;
6515 subtype = varflags & VSTYPE;
6516 quoted = varflags & VSQUOTE;
6518 easy = (!quoted || (*var == '@' && shellparam.nparam));
6519 startloc = expdest - (char *)stackblock();
6520 p = strchr(p, '=') + 1;
6523 varlen = varvalue(var, varflags, flags, var_str_list);
6524 if (varflags & VSNUL)
6527 if (subtype == VSPLUS) {
6528 varlen = -1 - varlen;
6532 if (subtype == VSMINUS) {
6536 p, flags | EXP_TILDE |
6537 (quoted ? EXP_QWORD : EXP_WORD),
6547 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6549 if (subevalvar(p, var, /* strloc: */ 0,
6550 subtype, startloc, varflags,
6556 * Remove any recorded regions beyond
6559 removerecordregions(startloc);
6569 if (varlen < 0 && uflag)
6570 varunset(p, var, 0, 0);
6572 if (subtype == VSLENGTH) {
6573 cvtnum(varlen > 0 ? varlen : 0);
6577 if (subtype == VSNORMAL) {
6588 case VSTRIMRIGHTMAX:
6589 #if ENABLE_ASH_BASH_COMPAT
6602 * Terminate the string and start recording the pattern
6605 STPUTC('\0', expdest);
6606 patloc = expdest - (char *)stackblock();
6607 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6609 //TODO: | EXP_REDIR too? All other such places do it too
6610 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6613 int amount = expdest - (
6614 (char *)stackblock() + patloc - 1
6616 STADJUST(-amount, expdest);
6618 /* Remove any recorded regions beyond start of variable */
6619 removerecordregions(startloc);
6621 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6625 if (subtype != VSNORMAL) { /* skip to end of alternative */
6628 unsigned char c = *p++;
6631 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6633 argbackq = argbackq->next;
6634 } else if (c == CTLVAR) {
6635 if ((*p++ & VSTYPE) != VSNORMAL)
6637 } else if (c == CTLENDVAR) {
6647 * Break the argument string into pieces based upon IFS and add the
6648 * strings to the argument list. The regions of the string to be
6649 * searched for IFS characters have been stored by recordregion.
6652 ifsbreakup(char *string, struct arglist *arglist)
6654 struct ifsregion *ifsp;
6659 const char *ifs, *realifs;
6664 if (ifslastp != NULL) {
6667 realifs = ifsset() ? ifsval() : defifs;
6670 p = string + ifsp->begoff;
6671 nulonly = ifsp->nulonly;
6672 ifs = nulonly ? nullstr : realifs;
6674 while (p < string + ifsp->endoff) {
6676 if ((unsigned char)*p == CTLESC)
6678 if (!strchr(ifs, *p)) {
6683 ifsspc = (strchr(defifs, *p) != NULL);
6684 /* Ignore IFS whitespace at start */
6685 if (q == start && ifsspc) {
6691 sp = stzalloc(sizeof(*sp));
6693 *arglist->lastp = sp;
6694 arglist->lastp = &sp->next;
6698 if (p >= string + ifsp->endoff) {
6702 if ((unsigned char)*p == CTLESC)
6704 if (strchr(ifs, *p) == NULL) {
6708 if (strchr(defifs, *p) == NULL) {
6723 } while (ifsp != NULL);
6732 sp = stzalloc(sizeof(*sp));
6734 *arglist->lastp = sp;
6735 arglist->lastp = &sp->next;
6741 struct ifsregion *p;
6746 struct ifsregion *ifsp;
6752 ifsfirst.next = NULL;
6757 * Add a file name to the list.
6760 addfname(const char *name)
6764 sp = stzalloc(sizeof(*sp));
6765 sp->text = ststrdup(name);
6767 exparg.lastp = &sp->next;
6770 static char *expdir;
6773 * Do metacharacter (i.e. *, ?, [...]) expansion.
6776 expmeta(char *enddir, char *name)
6791 for (p = name; *p; p++) {
6792 if (*p == '*' || *p == '?')
6794 else if (*p == '[') {
6801 if (*q == '/' || *q == '\0')
6808 } else if (*p == '\\')
6810 else if (*p == '/') {
6817 if (metaflag == 0) { /* we've reached the end of the file name */
6818 if (enddir != expdir)
6826 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6837 } while (p < start);
6839 if (enddir == expdir) {
6841 } else if (enddir == expdir + 1 && *expdir == '/') {
6850 if (enddir != expdir)
6852 if (*endname == 0) {
6864 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6865 if (dp->d_name[0] == '.' && !matchdot)
6867 if (pmatch(start, dp->d_name)) {
6869 strcpy(enddir, dp->d_name);
6872 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6875 expmeta(p, endname);
6884 static struct strlist *
6885 msort(struct strlist *list, int len)
6887 struct strlist *p, *q = NULL;
6888 struct strlist **lpp;
6896 for (n = half; --n >= 0;) {
6900 q->next = NULL; /* terminate first half of list */
6901 q = msort(list, half); /* sort first half of list */
6902 p = msort(p, len - half); /* sort second half */
6905 #if ENABLE_LOCALE_SUPPORT
6906 if (strcoll(p->text, q->text) < 0)
6908 if (strcmp(p->text, q->text) < 0)
6932 * Sort the results of file name expansion. It calculates the number of
6933 * strings to sort and then calls msort (short for merge sort) to do the
6936 static struct strlist *
6937 expsort(struct strlist *str)
6943 for (sp = str; sp; sp = sp->next)
6945 return msort(str, len);
6949 expandmeta(struct strlist *str /*, int flag*/)
6951 static const char metachars[] ALIGN1 = {
6954 /* TODO - EXP_REDIR */
6957 struct strlist **savelastp;
6963 if (!strpbrk(str->text, metachars))
6965 savelastp = exparg.lastp;
6968 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6970 int i = strlen(str->text);
6971 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6979 if (exparg.lastp == savelastp) {
6984 *exparg.lastp = str;
6985 rmescapes(str->text, 0);
6986 exparg.lastp = &str->next;
6988 *exparg.lastp = NULL;
6989 *savelastp = sp = expsort(*savelastp);
6990 while (sp->next != NULL)
6992 exparg.lastp = &sp->next;
6999 * Perform variable substitution and command substitution on an argument,
7000 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7001 * perform splitting and file name expansion. When arglist is NULL, perform
7002 * here document expansion.
7005 expandarg(union node *arg, struct arglist *arglist, int flag)
7010 argbackq = arg->narg.backquote;
7011 STARTSTACKSTR(expdest);
7012 ifsfirst.next = NULL;
7014 argstr(arg->narg.text, flag,
7015 /* var_str_list: */ arglist ? arglist->list : NULL);
7016 p = _STPUTC('\0', expdest);
7018 if (arglist == NULL) {
7019 return; /* here document expanded */
7021 p = grabstackstr(p);
7022 exparg.lastp = &exparg.list;
7026 if (flag & EXP_FULL) {
7027 ifsbreakup(p, &exparg);
7028 *exparg.lastp = NULL;
7029 exparg.lastp = &exparg.list;
7030 expandmeta(exparg.list /*, flag*/);
7032 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7034 sp = stzalloc(sizeof(*sp));
7037 exparg.lastp = &sp->next;
7041 *exparg.lastp = NULL;
7043 *arglist->lastp = exparg.list;
7044 arglist->lastp = exparg.lastp;
7049 * Expand shell variables and backquotes inside a here document.
7052 expandhere(union node *arg, int fd)
7055 expandarg(arg, (struct arglist *)NULL, 0);
7056 full_write(fd, stackblock(), expdest - (char *)stackblock());
7060 * Returns true if the pattern matches the string.
7063 patmatch(char *pattern, const char *string)
7065 return pmatch(preglob(pattern, 0, 0), string);
7069 * See if a pattern matches in a case statement.
7072 casematch(union node *pattern, char *val)
7074 struct stackmark smark;
7077 setstackmark(&smark);
7078 argbackq = pattern->narg.backquote;
7079 STARTSTACKSTR(expdest);
7081 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7082 /* var_str_list: */ NULL);
7083 STACKSTRNUL(expdest);
7084 result = patmatch(stackblock(), val);
7085 popstackmark(&smark);
7090 /* ============ find_command */
7094 int (*builtin)(int, char **) FAST_FUNC;
7095 /* unsigned flags; */
7097 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7098 /* "regular" builtins always take precedence over commands,
7099 * regardless of PATH=....%builtin... position */
7100 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7101 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7104 smallint cmdtype; /* CMDxxx */
7107 /* index >= 0 for commands without path (slashes) */
7108 /* (TODO: what exactly does the value mean? PATH position?) */
7109 /* index == -1 for commands with slashes */
7110 /* index == (-2 - applet_no) for NOFORK applets */
7111 const struct builtincmd *cmd;
7112 struct funcnode *func;
7115 /* values of cmdtype */
7116 #define CMDUNKNOWN -1 /* no entry in table for command */
7117 #define CMDNORMAL 0 /* command is an executable program */
7118 #define CMDFUNCTION 1 /* command is a shell function */
7119 #define CMDBUILTIN 2 /* command is a shell builtin */
7121 /* action to find_command() */
7122 #define DO_ERR 0x01 /* prints errors */
7123 #define DO_ABS 0x02 /* checks absolute paths */
7124 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7125 #define DO_ALTPATH 0x08 /* using alternate path */
7126 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7128 static void find_command(char *, struct cmdentry *, int, const char *);
7131 /* ============ Hashing commands */
7134 * When commands are first encountered, they are entered in a hash table.
7135 * This ensures that a full path search will not have to be done for them
7136 * on each invocation.
7138 * We should investigate converting to a linear search, even though that
7139 * would make the command name "hash" a misnomer.
7143 struct tblentry *next; /* next entry in hash chain */
7144 union param param; /* definition of builtin function */
7145 smallint cmdtype; /* CMDxxx */
7146 char rehash; /* if set, cd done since entry created */
7147 char cmdname[1]; /* name of command */
7150 static struct tblentry **cmdtable;
7151 #define INIT_G_cmdtable() do { \
7152 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7155 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7159 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7163 #if ENABLE_FEATURE_SH_STANDALONE
7164 if (applet_no >= 0) {
7165 if (APPLET_IS_NOEXEC(applet_no)) {
7168 run_applet_no_and_exit(applet_no, argv);
7170 /* re-exec ourselves with the new arguments */
7171 execve(bb_busybox_exec_path, argv, envp);
7172 /* If they called chroot or otherwise made the binary no longer
7173 * executable, fall through */
7180 execve(cmd, argv, envp);
7181 } while (errno == EINTR);
7183 execve(cmd, argv, envp);
7189 if (errno == ENOEXEC) {
7193 for (ap = argv; *ap; ap++)
7195 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7197 ap[0] = cmd = (char *)DEFAULT_SHELL;
7200 while ((*ap++ = *argv++) != NULL)
7209 * Exec a program. Never returns. If you change this routine, you may
7210 * have to change the find_command routine as well.
7212 static void shellexec(char **, const char *, int) NORETURN;
7214 shellexec(char **argv, const char *path, int idx)
7220 #if ENABLE_FEATURE_SH_STANDALONE
7224 clearredir(/*drop:*/ 1);
7225 envp = listvars(VEXPORT, VUNSET, 0);
7226 if (strchr(argv[0], '/') != NULL
7227 #if ENABLE_FEATURE_SH_STANDALONE
7228 || (applet_no = find_applet_by_name(argv[0])) >= 0
7231 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7235 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7236 if (--idx < 0 && pathopt == NULL) {
7237 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7238 if (errno != ENOENT && errno != ENOTDIR)
7245 /* Map to POSIX errors */
7257 exitstatus = exerrno;
7258 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7259 argv[0], e, suppress_int));
7260 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7265 printentry(struct tblentry *cmdp)
7271 idx = cmdp->param.index;
7274 name = path_advance(&path, cmdp->cmdname);
7276 } while (--idx >= 0);
7277 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7281 * Clear out command entries. The argument specifies the first entry in
7282 * PATH which has changed.
7285 clearcmdentry(int firstchange)
7287 struct tblentry **tblp;
7288 struct tblentry **pp;
7289 struct tblentry *cmdp;
7292 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7294 while ((cmdp = *pp) != NULL) {
7295 if ((cmdp->cmdtype == CMDNORMAL &&
7296 cmdp->param.index >= firstchange)
7297 || (cmdp->cmdtype == CMDBUILTIN &&
7298 builtinloc >= firstchange)
7311 * Locate a command in the command hash table. If "add" is nonzero,
7312 * add the command to the table if it is not already present. The
7313 * variable "lastcmdentry" is set to point to the address of the link
7314 * pointing to the entry, so that delete_cmd_entry can delete the
7317 * Interrupts must be off if called with add != 0.
7319 static struct tblentry **lastcmdentry;
7321 static struct tblentry *
7322 cmdlookup(const char *name, int add)
7324 unsigned int hashval;
7326 struct tblentry *cmdp;
7327 struct tblentry **pp;
7330 hashval = (unsigned char)*p << 4;
7332 hashval += (unsigned char)*p++;
7334 pp = &cmdtable[hashval % CMDTABLESIZE];
7335 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7336 if (strcmp(cmdp->cmdname, name) == 0)
7340 if (add && cmdp == NULL) {
7341 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7343 /* + 1 - already done because
7344 * tblentry::cmdname is char[1] */);
7345 /*cmdp->next = NULL; - ckzalloc did it */
7346 cmdp->cmdtype = CMDUNKNOWN;
7347 strcpy(cmdp->cmdname, name);
7354 * Delete the command entry returned on the last lookup.
7357 delete_cmd_entry(void)
7359 struct tblentry *cmdp;
7362 cmdp = *lastcmdentry;
7363 *lastcmdentry = cmdp->next;
7364 if (cmdp->cmdtype == CMDFUNCTION)
7365 freefunc(cmdp->param.func);
7371 * Add a new command entry, replacing any existing command entry for
7372 * the same name - except special builtins.
7375 addcmdentry(char *name, struct cmdentry *entry)
7377 struct tblentry *cmdp;
7379 cmdp = cmdlookup(name, 1);
7380 if (cmdp->cmdtype == CMDFUNCTION) {
7381 freefunc(cmdp->param.func);
7383 cmdp->cmdtype = entry->cmdtype;
7384 cmdp->param = entry->u;
7388 static int FAST_FUNC
7389 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7391 struct tblentry **pp;
7392 struct tblentry *cmdp;
7394 struct cmdentry entry;
7397 if (nextopt("r") != '\0') {
7402 if (*argptr == NULL) {
7403 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7404 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7405 if (cmdp->cmdtype == CMDNORMAL)
7413 while ((name = *argptr) != NULL) {
7414 cmdp = cmdlookup(name, 0);
7416 && (cmdp->cmdtype == CMDNORMAL
7417 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7421 find_command(name, &entry, DO_ERR, pathval());
7422 if (entry.cmdtype == CMDUNKNOWN)
7430 * Called when a cd is done. Marks all commands so the next time they
7431 * are executed they will be rehashed.
7436 struct tblentry **pp;
7437 struct tblentry *cmdp;
7439 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7440 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7441 if (cmdp->cmdtype == CMDNORMAL
7442 || (cmdp->cmdtype == CMDBUILTIN
7443 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7453 * Fix command hash table when PATH changed.
7454 * Called before PATH is changed. The argument is the new value of PATH;
7455 * pathval() still returns the old value at this point.
7456 * Called with interrupts off.
7458 static void FAST_FUNC
7459 changepath(const char *new)
7467 firstchange = 9999; /* assume no change */
7473 if ((*old == '\0' && *new == ':')
7474 || (*old == ':' && *new == '\0'))
7476 old = new; /* ignore subsequent differences */
7480 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7486 if (builtinloc < 0 && idx_bltin >= 0)
7487 builtinloc = idx_bltin; /* zap builtins */
7488 if (builtinloc >= 0 && idx_bltin < 0)
7490 clearcmdentry(firstchange);
7491 builtinloc = idx_bltin;
7506 #define TENDBQUOTE 12
7523 typedef smallint token_id_t;
7525 /* first char is indicating which tokens mark the end of a list */
7526 static const char *const tokname_array[] = {
7540 #define KWDOFFSET 13
7541 /* the following are keywords */
7563 static char buf[16];
7566 //if (tok < TSEMI) return tokname_array[tok] + 1;
7567 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7572 sprintf(buf + (tok >= TSEMI), "%s%c",
7573 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7577 /* Wrapper around strcmp for qsort/bsearch/... */
7579 pstrcmp(const void *a, const void *b)
7581 return strcmp((char*) a, (*(char**) b) + 1);
7584 static const char *const *
7585 findkwd(const char *s)
7587 return bsearch(s, tokname_array + KWDOFFSET,
7588 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7589 sizeof(tokname_array[0]), pstrcmp);
7593 * Locate and print what a word is...
7596 describe_command(char *command, int describe_command_verbose)
7598 struct cmdentry entry;
7599 struct tblentry *cmdp;
7600 #if ENABLE_ASH_ALIAS
7601 const struct alias *ap;
7603 const char *path = pathval();
7605 if (describe_command_verbose) {
7609 /* First look at the keywords */
7610 if (findkwd(command)) {
7611 out1str(describe_command_verbose ? " is a shell keyword" : command);
7615 #if ENABLE_ASH_ALIAS
7616 /* Then look at the aliases */
7617 ap = lookupalias(command, 0);
7619 if (!describe_command_verbose) {
7624 out1fmt(" is an alias for %s", ap->val);
7628 /* Then check if it is a tracked alias */
7629 cmdp = cmdlookup(command, 0);
7631 entry.cmdtype = cmdp->cmdtype;
7632 entry.u = cmdp->param;
7634 /* Finally use brute force */
7635 find_command(command, &entry, DO_ABS, path);
7638 switch (entry.cmdtype) {
7640 int j = entry.u.index;
7646 p = path_advance(&path, command);
7650 if (describe_command_verbose) {
7652 (cmdp ? " a tracked alias for" : nullstr), p
7661 if (describe_command_verbose) {
7662 out1str(" is a shell function");
7669 if (describe_command_verbose) {
7670 out1fmt(" is a %sshell builtin",
7671 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7672 "special " : nullstr
7680 if (describe_command_verbose) {
7681 out1str(": not found\n");
7686 outstr("\n", stdout);
7690 static int FAST_FUNC
7691 typecmd(int argc UNUSED_PARAM, char **argv)
7697 /* type -p ... ? (we don't bother checking for 'p') */
7698 if (argv[1] && argv[1][0] == '-') {
7703 err |= describe_command(argv[i++], verbose);
7708 #if ENABLE_ASH_CMDCMD
7709 static int FAST_FUNC
7710 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7718 while ((c = nextopt("pvV")) != '\0')
7720 verify |= VERIFY_VERBOSE;
7722 verify |= VERIFY_BRIEF;
7727 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7728 if (verify && (*argptr != NULL)) {
7729 return describe_command(*argptr, verify - VERIFY_BRIEF);
7737 /* ============ eval.c */
7739 static int funcblocksize; /* size of structures in function */
7740 static int funcstringsize; /* size of strings in node */
7741 static void *funcblock; /* block to allocate function from */
7742 static char *funcstring; /* block to allocate strings from */
7744 /* flags in argument to evaltree */
7745 #define EV_EXIT 01 /* exit after evaluating tree */
7746 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7747 #define EV_BACKCMD 04 /* command executing within back quotes */
7749 static const uint8_t nodesize[N_NUMBER] = {
7750 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7751 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7752 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7753 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7754 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7755 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7756 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7757 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7758 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7759 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7760 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7761 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7762 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7763 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7764 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7765 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7766 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7767 #if ENABLE_ASH_BASH_COMPAT
7768 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7770 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7771 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7772 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7773 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7774 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7775 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7776 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7777 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7778 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7781 static void calcsize(union node *n);
7784 sizenodelist(struct nodelist *lp)
7787 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7794 calcsize(union node *n)
7798 funcblocksize += nodesize[n->type];
7801 calcsize(n->ncmd.redirect);
7802 calcsize(n->ncmd.args);
7803 calcsize(n->ncmd.assign);
7806 sizenodelist(n->npipe.cmdlist);
7811 calcsize(n->nredir.redirect);
7812 calcsize(n->nredir.n);
7819 calcsize(n->nbinary.ch2);
7820 calcsize(n->nbinary.ch1);
7823 calcsize(n->nif.elsepart);
7824 calcsize(n->nif.ifpart);
7825 calcsize(n->nif.test);
7828 funcstringsize += strlen(n->nfor.var) + 1;
7829 calcsize(n->nfor.body);
7830 calcsize(n->nfor.args);
7833 calcsize(n->ncase.cases);
7834 calcsize(n->ncase.expr);
7837 calcsize(n->nclist.body);
7838 calcsize(n->nclist.pattern);
7839 calcsize(n->nclist.next);
7843 sizenodelist(n->narg.backquote);
7844 funcstringsize += strlen(n->narg.text) + 1;
7845 calcsize(n->narg.next);
7848 #if ENABLE_ASH_BASH_COMPAT
7855 calcsize(n->nfile.fname);
7856 calcsize(n->nfile.next);
7860 calcsize(n->ndup.vname);
7861 calcsize(n->ndup.next);
7865 calcsize(n->nhere.doc);
7866 calcsize(n->nhere.next);
7869 calcsize(n->nnot.com);
7875 nodeckstrdup(char *s)
7877 char *rtn = funcstring;
7879 strcpy(funcstring, s);
7880 funcstring += strlen(s) + 1;
7884 static union node *copynode(union node *);
7886 static struct nodelist *
7887 copynodelist(struct nodelist *lp)
7889 struct nodelist *start;
7890 struct nodelist **lpp;
7895 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7896 (*lpp)->n = copynode(lp->n);
7898 lpp = &(*lpp)->next;
7905 copynode(union node *n)
7912 funcblock = (char *) funcblock + nodesize[n->type];
7916 new->ncmd.redirect = copynode(n->ncmd.redirect);
7917 new->ncmd.args = copynode(n->ncmd.args);
7918 new->ncmd.assign = copynode(n->ncmd.assign);
7921 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7922 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7927 new->nredir.redirect = copynode(n->nredir.redirect);
7928 new->nredir.n = copynode(n->nredir.n);
7935 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7936 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7939 new->nif.elsepart = copynode(n->nif.elsepart);
7940 new->nif.ifpart = copynode(n->nif.ifpart);
7941 new->nif.test = copynode(n->nif.test);
7944 new->nfor.var = nodeckstrdup(n->nfor.var);
7945 new->nfor.body = copynode(n->nfor.body);
7946 new->nfor.args = copynode(n->nfor.args);
7949 new->ncase.cases = copynode(n->ncase.cases);
7950 new->ncase.expr = copynode(n->ncase.expr);
7953 new->nclist.body = copynode(n->nclist.body);
7954 new->nclist.pattern = copynode(n->nclist.pattern);
7955 new->nclist.next = copynode(n->nclist.next);
7959 new->narg.backquote = copynodelist(n->narg.backquote);
7960 new->narg.text = nodeckstrdup(n->narg.text);
7961 new->narg.next = copynode(n->narg.next);
7964 #if ENABLE_ASH_BASH_COMPAT
7971 new->nfile.fname = copynode(n->nfile.fname);
7972 new->nfile.fd = n->nfile.fd;
7973 new->nfile.next = copynode(n->nfile.next);
7977 new->ndup.vname = copynode(n->ndup.vname);
7978 new->ndup.dupfd = n->ndup.dupfd;
7979 new->ndup.fd = n->ndup.fd;
7980 new->ndup.next = copynode(n->ndup.next);
7984 new->nhere.doc = copynode(n->nhere.doc);
7985 new->nhere.fd = n->nhere.fd;
7986 new->nhere.next = copynode(n->nhere.next);
7989 new->nnot.com = copynode(n->nnot.com);
7992 new->type = n->type;
7997 * Make a copy of a parse tree.
7999 static struct funcnode *
8000 copyfunc(union node *n)
8005 funcblocksize = offsetof(struct funcnode, n);
8008 blocksize = funcblocksize;
8009 f = ckmalloc(blocksize + funcstringsize);
8010 funcblock = (char *) f + offsetof(struct funcnode, n);
8011 funcstring = (char *) f + blocksize;
8018 * Define a shell function.
8021 defun(char *name, union node *func)
8023 struct cmdentry entry;
8026 entry.cmdtype = CMDFUNCTION;
8027 entry.u.func = copyfunc(func);
8028 addcmdentry(name, &entry);
8032 /* Reasons for skipping commands (see comment on breakcmd routine) */
8033 #define SKIPBREAK (1 << 0)
8034 #define SKIPCONT (1 << 1)
8035 #define SKIPFUNC (1 << 2)
8036 #define SKIPFILE (1 << 3)
8037 #define SKIPEVAL (1 << 4)
8038 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8039 static int skipcount; /* number of levels to skip */
8040 static int funcnest; /* depth of function calls */
8041 static int loopnest; /* current loop nesting level */
8043 /* Forward decl way out to parsing code - dotrap needs it */
8044 static int evalstring(char *s, int mask);
8046 /* Called to execute a trap.
8047 * Single callsite - at the end of evaltree().
8048 * If we return non-zero, exaltree raises EXEXIT exception.
8050 * Perhaps we should avoid entering new trap handlers
8051 * while we are executing a trap handler. [is it a TODO?]
8060 savestatus = exitstatus;
8064 TRACE(("dotrap entered\n"));
8065 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8072 /* non-trapped SIGINT is handled separately by raise_interrupt,
8073 * don't upset it by resetting gotsig[SIGINT-1] */
8074 if (sig == SIGINT && !t)
8077 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8081 want_exexit = evalstring(t, SKIPEVAL);
8082 exitstatus = savestatus;
8084 TRACE(("dotrap returns %d\n", want_exexit));
8089 TRACE(("dotrap returns 0\n"));
8093 /* forward declarations - evaluation is fairly recursive business... */
8094 static void evalloop(union node *, int);
8095 static void evalfor(union node *, int);
8096 static void evalcase(union node *, int);
8097 static void evalsubshell(union node *, int);
8098 static void expredir(union node *);
8099 static void evalpipe(union node *, int);
8100 static void evalcommand(union node *, int);
8101 static int evalbltin(const struct builtincmd *, int, char **);
8102 static void prehash(union node *);
8105 * Evaluate a parse tree. The value is left in the global variable
8109 evaltree(union node *n, int flags)
8111 struct jmploc *volatile savehandler = exception_handler;
8112 struct jmploc jmploc;
8114 void (*evalfn)(union node *, int);
8118 SAVE_INT(int_level);
8121 TRACE(("evaltree(NULL) called\n"));
8124 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8126 exception_handler = &jmploc;
8128 int err = setjmp(jmploc.loc);
8130 /* if it was a signal, check for trap handlers */
8131 if (exception_type == EXSIG) {
8132 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8133 exception_type, err));
8136 /* continue on the way out */
8137 TRACE(("exception %d in evaltree, propagating err=%d\n",
8138 exception_type, err));
8139 exception_handler = savehandler;
8140 longjmp(exception_handler->loc, err);
8147 out1fmt("Node type = %d\n", n->type);
8152 evaltree(n->nnot.com, EV_TESTED);
8153 status = !exitstatus;
8156 expredir(n->nredir.redirect);
8157 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8159 evaltree(n->nredir.n, flags & EV_TESTED);
8160 status = exitstatus;
8162 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8165 evalfn = evalcommand;
8167 if (eflag && !(flags & EV_TESTED))
8179 evalfn = evalsubshell;
8192 #error NAND + 1 != NOR
8194 #if NOR + 1 != NSEMI
8195 #error NOR + 1 != NSEMI
8197 unsigned is_or = n->type - NAND;
8200 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8202 if (!exitstatus == is_or)
8215 evaltree(n->nif.test, EV_TESTED);
8218 if (exitstatus == 0) {
8222 if (n->nif.elsepart) {
8223 n = n->nif.elsepart;
8228 defun(n->narg.text, n->narg.next);
8232 exitstatus = status;
8237 exception_handler = savehandler;
8239 if (checkexit & exitstatus)
8240 evalskip |= SKIPEVAL;
8241 else if (pending_sig && dotrap())
8244 if (flags & EV_EXIT) {
8246 raise_exception(EXEXIT);
8249 RESTORE_INT(int_level);
8250 TRACE(("leaving evaltree (no interrupts)\n"));
8253 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8256 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8259 evalloop(union node *n, int flags)
8269 evaltree(n->nbinary.ch1, EV_TESTED);
8272 if (evalskip == SKIPCONT && --skipcount <= 0) {
8276 if (evalskip == SKIPBREAK && --skipcount <= 0)
8281 if (n->type != NWHILE)
8285 evaltree(n->nbinary.ch2, flags);
8286 status = exitstatus;
8291 exitstatus = status;
8295 evalfor(union node *n, int flags)
8297 struct arglist arglist;
8300 struct stackmark smark;
8302 setstackmark(&smark);
8303 arglist.list = NULL;
8304 arglist.lastp = &arglist.list;
8305 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8306 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8311 *arglist.lastp = NULL;
8316 for (sp = arglist.list; sp; sp = sp->next) {
8317 setvar(n->nfor.var, sp->text, 0);
8318 evaltree(n->nfor.body, flags);
8320 if (evalskip == SKIPCONT && --skipcount <= 0) {
8324 if (evalskip == SKIPBREAK && --skipcount <= 0)
8331 popstackmark(&smark);
8335 evalcase(union node *n, int flags)
8339 struct arglist arglist;
8340 struct stackmark smark;
8342 setstackmark(&smark);
8343 arglist.list = NULL;
8344 arglist.lastp = &arglist.list;
8345 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8347 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8348 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8349 if (casematch(patp, arglist.list->text)) {
8350 if (evalskip == 0) {
8351 evaltree(cp->nclist.body, flags);
8358 popstackmark(&smark);
8362 * Kick off a subshell to evaluate a tree.
8365 evalsubshell(union node *n, int flags)
8368 int backgnd = (n->type == NBACKGND);
8371 expredir(n->nredir.redirect);
8372 if (!backgnd && flags & EV_EXIT && !trap[0])
8375 jp = makejob(/*n,*/ 1);
8376 if (forkshell(jp, n, backgnd) == 0) {
8380 flags &=~ EV_TESTED;
8382 redirect(n->nredir.redirect, 0);
8383 evaltreenr(n->nredir.n, flags);
8388 status = waitforjob(jp);
8389 exitstatus = status;
8394 * Compute the names of the files in a redirection list.
8396 static void fixredir(union node *, const char *, int);
8398 expredir(union node *n)
8402 for (redir = n; redir; redir = redir->nfile.next) {
8406 fn.lastp = &fn.list;
8407 switch (redir->type) {
8411 #if ENABLE_ASH_BASH_COMPAT
8416 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8417 #if ENABLE_ASH_BASH_COMPAT
8420 redir->nfile.expfname = fn.list->text;
8423 case NTOFD: /* >& */
8424 if (redir->ndup.vname) {
8425 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8426 if (fn.list == NULL)
8427 ash_msg_and_raise_error("redir error");
8428 #if ENABLE_ASH_BASH_COMPAT
8429 //FIXME: we used expandarg with different args!
8430 if (!isdigit_str9(fn.list->text)) {
8431 /* >&file, not >&fd */
8432 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8433 ash_msg_and_raise_error("redir error");
8435 goto store_expfname;
8438 fixredir(redir, fn.list->text, 1);
8446 * Evaluate a pipeline. All the processes in the pipeline are children
8447 * of the process creating the pipeline. (This differs from some versions
8448 * of the shell, which make the last process in a pipeline the parent
8452 evalpipe(union node *n, int flags)
8455 struct nodelist *lp;
8460 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8462 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8466 jp = makejob(/*n,*/ pipelen);
8468 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8472 if (pipe(pip) < 0) {
8474 ash_msg_and_raise_error("pipe call failed");
8477 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8490 evaltreenr(lp->n, flags);
8496 /* Don't want to trigger debugging */
8500 if (n->npipe.pipe_backgnd == 0) {
8501 exitstatus = waitforjob(jp);
8502 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8508 * Controls whether the shell is interactive or not.
8511 setinteractive(int on)
8513 static smallint is_interactive;
8515 if (++on == is_interactive)
8517 is_interactive = on;
8521 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8522 if (is_interactive > 1) {
8523 /* Looks like they want an interactive shell */
8524 static smallint did_banner;
8527 /* note: ash and hush share this string */
8528 out1fmt("\n\n%s %s\n"
8529 "Enter 'help' for a list of built-in commands."
8532 "built-in shell (ash)"
8546 setinteractive(iflag);
8548 #if ENABLE_FEATURE_EDITING_VI
8550 line_input_state->flags |= VI_MODE;
8552 line_input_state->flags &= ~VI_MODE;
8554 viflag = 0; /* forcibly keep the option off */
8558 static struct localvar *localvars;
8561 * Called after a function returns.
8562 * Interrupts must be off.
8567 struct localvar *lvp;
8570 while ((lvp = localvars) != NULL) {
8571 localvars = lvp->next;
8573 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8574 if (vp == NULL) { /* $- saved */
8575 memcpy(optlist, lvp->text, sizeof(optlist));
8576 free((char*)lvp->text);
8578 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8582 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8583 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8584 free((char*)vp->text);
8585 vp->flags = lvp->flags;
8586 vp->text = lvp->text;
8593 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8595 volatile struct shparam saveparam;
8596 struct localvar *volatile savelocalvars;
8597 struct jmploc *volatile savehandler;
8598 struct jmploc jmploc;
8601 saveparam = shellparam;
8602 savelocalvars = localvars;
8603 e = setjmp(jmploc.loc);
8608 savehandler = exception_handler;
8609 exception_handler = &jmploc;
8611 shellparam.malloced = 0;
8615 shellparam.nparam = argc - 1;
8616 shellparam.p = argv + 1;
8617 #if ENABLE_ASH_GETOPTS
8618 shellparam.optind = 1;
8619 shellparam.optoff = -1;
8621 evaltree(&func->n, flags & EV_TESTED);
8627 localvars = savelocalvars;
8628 freeparam(&shellparam);
8629 shellparam = saveparam;
8630 exception_handler = savehandler;
8632 evalskip &= ~SKIPFUNC;
8636 #if ENABLE_ASH_CMDCMD
8638 parse_command_args(char **argv, const char **path)
8651 if (c == '-' && !*cp) {
8658 *path = bb_default_path;
8661 /* run 'typecmd' for other options */
8672 * Make a variable a local variable. When a variable is made local, it's
8673 * value and flags are saved in a localvar structure. The saved values
8674 * will be restored when the shell function returns. We handle the name
8675 * "-" as a special case.
8680 struct localvar *lvp;
8685 lvp = ckzalloc(sizeof(struct localvar));
8686 if (LONE_DASH(name)) {
8688 p = ckmalloc(sizeof(optlist));
8689 lvp->text = memcpy(p, optlist, sizeof(optlist));
8694 vpp = hashvar(name);
8695 vp = *findvar(vpp, name);
8696 eq = strchr(name, '=');
8699 setvareq(name, VSTRFIXED);
8701 setvar(name, NULL, VSTRFIXED);
8702 vp = *vpp; /* the new variable */
8703 lvp->flags = VUNSET;
8705 lvp->text = vp->text;
8706 lvp->flags = vp->flags;
8707 vp->flags |= VSTRFIXED|VTEXTFIXED;
8713 lvp->next = localvars;
8719 * The "local" command.
8721 static int FAST_FUNC
8722 localcmd(int argc UNUSED_PARAM, char **argv)
8727 while ((name = *argv++) != NULL) {
8733 static int FAST_FUNC
8734 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8739 static int FAST_FUNC
8740 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8745 static int FAST_FUNC
8746 execcmd(int argc UNUSED_PARAM, char **argv)
8749 iflag = 0; /* exit on error */
8752 shellexec(argv + 1, pathval(), 0);
8758 * The return command.
8760 static int FAST_FUNC
8761 returncmd(int argc UNUSED_PARAM, char **argv)
8764 * If called outside a function, do what ksh does;
8765 * skip the rest of the file.
8767 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8768 return argv[1] ? number(argv[1]) : exitstatus;
8771 /* Forward declarations for builtintab[] */
8772 static int breakcmd(int, char **) FAST_FUNC;
8773 static int dotcmd(int, char **) FAST_FUNC;
8774 static int evalcmd(int, char **) FAST_FUNC;
8775 static int exitcmd(int, char **) FAST_FUNC;
8776 static int exportcmd(int, char **) FAST_FUNC;
8777 #if ENABLE_ASH_GETOPTS
8778 static int getoptscmd(int, char **) FAST_FUNC;
8780 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8781 static int helpcmd(int, char **) FAST_FUNC;
8783 #if ENABLE_SH_MATH_SUPPORT
8784 static int letcmd(int, char **) FAST_FUNC;
8786 static int readcmd(int, char **) FAST_FUNC;
8787 static int setcmd(int, char **) FAST_FUNC;
8788 static int shiftcmd(int, char **) FAST_FUNC;
8789 static int timescmd(int, char **) FAST_FUNC;
8790 static int trapcmd(int, char **) FAST_FUNC;
8791 static int umaskcmd(int, char **) FAST_FUNC;
8792 static int unsetcmd(int, char **) FAST_FUNC;
8793 static int ulimitcmd(int, char **) FAST_FUNC;
8795 #define BUILTIN_NOSPEC "0"
8796 #define BUILTIN_SPECIAL "1"
8797 #define BUILTIN_REGULAR "2"
8798 #define BUILTIN_SPEC_REG "3"
8799 #define BUILTIN_ASSIGN "4"
8800 #define BUILTIN_SPEC_ASSG "5"
8801 #define BUILTIN_REG_ASSG "6"
8802 #define BUILTIN_SPEC_REG_ASSG "7"
8804 /* Stubs for calling non-FAST_FUNC's */
8805 #if ENABLE_ASH_BUILTIN_ECHO
8806 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8808 #if ENABLE_ASH_BUILTIN_PRINTF
8809 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8811 #if ENABLE_ASH_BUILTIN_TEST
8812 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8815 /* Keep these in proper order since it is searched via bsearch() */
8816 static const struct builtincmd builtintab[] = {
8817 { BUILTIN_SPEC_REG ".", dotcmd },
8818 { BUILTIN_SPEC_REG ":", truecmd },
8819 #if ENABLE_ASH_BUILTIN_TEST
8820 { BUILTIN_REGULAR "[", testcmd },
8821 #if ENABLE_ASH_BASH_COMPAT
8822 { BUILTIN_REGULAR "[[", testcmd },
8825 #if ENABLE_ASH_ALIAS
8826 { BUILTIN_REG_ASSG "alias", aliascmd },
8829 { BUILTIN_REGULAR "bg", fg_bgcmd },
8831 { BUILTIN_SPEC_REG "break", breakcmd },
8832 { BUILTIN_REGULAR "cd", cdcmd },
8833 { BUILTIN_NOSPEC "chdir", cdcmd },
8834 #if ENABLE_ASH_CMDCMD
8835 { BUILTIN_REGULAR "command", commandcmd },
8837 { BUILTIN_SPEC_REG "continue", breakcmd },
8838 #if ENABLE_ASH_BUILTIN_ECHO
8839 { BUILTIN_REGULAR "echo", echocmd },
8841 { BUILTIN_SPEC_REG "eval", evalcmd },
8842 { BUILTIN_SPEC_REG "exec", execcmd },
8843 { BUILTIN_SPEC_REG "exit", exitcmd },
8844 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8845 { BUILTIN_REGULAR "false", falsecmd },
8847 { BUILTIN_REGULAR "fg", fg_bgcmd },
8849 #if ENABLE_ASH_GETOPTS
8850 { BUILTIN_REGULAR "getopts", getoptscmd },
8852 { BUILTIN_NOSPEC "hash", hashcmd },
8853 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8854 { BUILTIN_NOSPEC "help", helpcmd },
8857 { BUILTIN_REGULAR "jobs", jobscmd },
8858 { BUILTIN_REGULAR "kill", killcmd },
8860 #if ENABLE_SH_MATH_SUPPORT
8861 { BUILTIN_NOSPEC "let", letcmd },
8863 { BUILTIN_ASSIGN "local", localcmd },
8864 #if ENABLE_ASH_BUILTIN_PRINTF
8865 { BUILTIN_REGULAR "printf", printfcmd },
8867 { BUILTIN_NOSPEC "pwd", pwdcmd },
8868 { BUILTIN_REGULAR "read", readcmd },
8869 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8870 { BUILTIN_SPEC_REG "return", returncmd },
8871 { BUILTIN_SPEC_REG "set", setcmd },
8872 { BUILTIN_SPEC_REG "shift", shiftcmd },
8873 { BUILTIN_SPEC_REG "source", dotcmd },
8874 #if ENABLE_ASH_BUILTIN_TEST
8875 { BUILTIN_REGULAR "test", testcmd },
8877 { BUILTIN_SPEC_REG "times", timescmd },
8878 { BUILTIN_SPEC_REG "trap", trapcmd },
8879 { BUILTIN_REGULAR "true", truecmd },
8880 { BUILTIN_NOSPEC "type", typecmd },
8881 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8882 { BUILTIN_REGULAR "umask", umaskcmd },
8883 #if ENABLE_ASH_ALIAS
8884 { BUILTIN_REGULAR "unalias", unaliascmd },
8886 { BUILTIN_SPEC_REG "unset", unsetcmd },
8887 { BUILTIN_REGULAR "wait", waitcmd },
8890 /* Should match the above table! */
8891 #define COMMANDCMD (builtintab + \
8893 1 * ENABLE_ASH_BUILTIN_TEST + \
8894 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8895 1 * ENABLE_ASH_ALIAS + \
8896 1 * ENABLE_ASH_JOB_CONTROL + \
8898 #define EXECCMD (builtintab + \
8900 1 * ENABLE_ASH_BUILTIN_TEST + \
8901 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8902 1 * ENABLE_ASH_ALIAS + \
8903 1 * ENABLE_ASH_JOB_CONTROL + \
8905 1 * ENABLE_ASH_CMDCMD + \
8907 ENABLE_ASH_BUILTIN_ECHO + \
8911 * Search the table of builtin commands.
8913 static struct builtincmd *
8914 find_builtin(const char *name)
8916 struct builtincmd *bp;
8919 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8926 * Execute a simple command.
8929 isassignment(const char *p)
8931 const char *q = endofname(p);
8936 static int FAST_FUNC
8937 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8939 /* Preserve exitstatus of a previous possible redirection
8940 * as POSIX mandates */
8941 return back_exitstatus;
8944 evalcommand(union node *cmd, int flags)
8946 static const struct builtincmd null_bltin = {
8947 "\0\0", bltincmd /* why three NULs? */
8949 struct stackmark smark;
8951 struct arglist arglist;
8952 struct arglist varlist;
8955 const struct strlist *sp;
8956 struct cmdentry cmdentry;
8963 struct builtincmd *bcmd;
8964 smallint cmd_is_exec;
8965 smallint pseudovarflag = 0;
8967 /* First expand the arguments. */
8968 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8969 setstackmark(&smark);
8970 back_exitstatus = 0;
8972 cmdentry.cmdtype = CMDBUILTIN;
8973 cmdentry.u.cmd = &null_bltin;
8974 varlist.lastp = &varlist.list;
8975 *varlist.lastp = NULL;
8976 arglist.lastp = &arglist.list;
8977 *arglist.lastp = NULL;
8980 if (cmd->ncmd.args) {
8981 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8982 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8985 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8986 struct strlist **spp;
8988 spp = arglist.lastp;
8989 if (pseudovarflag && isassignment(argp->narg.text))
8990 expandarg(argp, &arglist, EXP_VARTILDE);
8992 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8994 for (sp = *spp; sp; sp = sp->next)
8998 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
8999 for (sp = arglist.list; sp; sp = sp->next) {
9000 TRACE(("evalcommand arg: %s\n", sp->text));
9001 *nargv++ = sp->text;
9006 if (iflag && funcnest == 0 && argc > 0)
9007 lastarg = nargv[-1];
9010 expredir(cmd->ncmd.redirect);
9011 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9014 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9015 struct strlist **spp;
9018 spp = varlist.lastp;
9019 expandarg(argp, &varlist, EXP_VARTILDE);
9022 * Modify the command lookup path, if a PATH= assignment
9026 if (varequal(p, path))
9030 /* Print the command if xflag is set. */
9033 const char *p = " %s";
9036 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9039 for (n = 0; n < 2; n++) {
9041 fdprintf(preverrout_fd, p, sp->text);
9049 safe_write(preverrout_fd, "\n", 1);
9055 /* Now locate the command. */
9057 const char *oldpath;
9058 int cmd_flag = DO_ERR;
9063 find_command(argv[0], &cmdentry, cmd_flag, path);
9064 if (cmdentry.cmdtype == CMDUNKNOWN) {
9065 flush_stdout_stderr();
9070 /* implement bltin and command here */
9071 if (cmdentry.cmdtype != CMDBUILTIN)
9074 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9075 if (cmdentry.u.cmd == EXECCMD)
9077 #if ENABLE_ASH_CMDCMD
9078 if (cmdentry.u.cmd == COMMANDCMD) {
9080 nargv = parse_command_args(argv, &path);
9083 argc -= nargv - argv;
9085 cmd_flag |= DO_NOFUNC;
9093 /* We have a redirection error. */
9095 raise_exception(EXERROR);
9097 exitstatus = status;
9101 /* Execute the command. */
9102 switch (cmdentry.cmdtype) {
9105 #if ENABLE_FEATURE_SH_NOFORK
9106 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9107 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9109 /* find_command() encodes applet_no as (-2 - applet_no) */
9110 int applet_no = (- cmdentry.u.index - 2);
9111 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9112 listsetvar(varlist.list, VEXPORT|VSTACK);
9113 /* run <applet>_main() */
9114 exitstatus = run_nofork_applet(applet_no, argv);
9119 /* Fork off a child process if necessary. */
9120 if (!(flags & EV_EXIT) || trap[0]) {
9122 jp = makejob(/*cmd,*/ 1);
9123 if (forkshell(jp, cmd, FORK_FG) != 0) {
9124 exitstatus = waitforjob(jp);
9126 TRACE(("forked child exited with %d\n", exitstatus));
9131 listsetvar(varlist.list, VEXPORT|VSTACK);
9132 shellexec(argv, path, cmdentry.u.index);
9136 cmdenviron = varlist.list;
9138 struct strlist *list = cmdenviron;
9140 if (spclbltin > 0 || argc == 0) {
9142 if (cmd_is_exec && argc > 1)
9145 listsetvar(list, i);
9147 /* Tight loop with builtins only:
9148 * "while kill -0 $child; do true; done"
9149 * will never exit even if $child died, unless we do this
9150 * to reap the zombie and make kill detect that it's gone: */
9151 dowait(DOWAIT_NONBLOCK, NULL);
9153 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9155 int i = exception_type;
9160 exit_status = 128 + SIGINT;
9162 exit_status = 128 + pending_sig;
9163 exitstatus = exit_status;
9164 if (i == EXINT || spclbltin > 0) {
9166 longjmp(exception_handler->loc, 1);
9173 listsetvar(varlist.list, 0);
9174 /* See above for the rationale */
9175 dowait(DOWAIT_NONBLOCK, NULL);
9176 if (evalfun(cmdentry.u.func, argc, argv, flags))
9182 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9184 /* dsl: I think this is intended to be used to support
9185 * '_' in 'vi' command mode during line editing...
9186 * However I implemented that within libedit itself.
9188 setvar("_", lastarg, 0);
9190 popstackmark(&smark);
9194 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9196 char *volatile savecmdname;
9197 struct jmploc *volatile savehandler;
9198 struct jmploc jmploc;
9201 savecmdname = commandname;
9202 i = setjmp(jmploc.loc);
9205 savehandler = exception_handler;
9206 exception_handler = &jmploc;
9207 commandname = argv[0];
9209 optptr = NULL; /* initialize nextopt */
9210 exitstatus = (*cmd->builtin)(argc, argv);
9211 flush_stdout_stderr();
9213 exitstatus |= ferror(stdout);
9215 commandname = savecmdname;
9216 exception_handler = savehandler;
9222 goodname(const char *p)
9224 return !*endofname(p);
9229 * Search for a command. This is called before we fork so that the
9230 * location of the command will be available in the parent as well as
9231 * the child. The check for "goodname" is an overly conservative
9232 * check that the name will not be subject to expansion.
9235 prehash(union node *n)
9237 struct cmdentry entry;
9239 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9240 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9244 /* ============ Builtin commands
9246 * Builtin commands whose functions are closely tied to evaluation
9247 * are implemented here.
9251 * Handle break and continue commands. Break, continue, and return are
9252 * all handled by setting the evalskip flag. The evaluation routines
9253 * above all check this flag, and if it is set they start skipping
9254 * commands rather than executing them. The variable skipcount is
9255 * the number of loops to break/continue, or the number of function
9256 * levels to return. (The latter is always 1.) It should probably
9257 * be an error to break out of more loops than exist, but it isn't
9258 * in the standard shell so we don't make it one here.
9260 static int FAST_FUNC
9261 breakcmd(int argc UNUSED_PARAM, char **argv)
9263 int n = argv[1] ? number(argv[1]) : 1;
9266 ash_msg_and_raise_error(msg_illnum, argv[1]);
9270 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9277 /* ============ input.c
9279 * This implements the input routines used by the parser.
9283 INPUT_PUSH_FILE = 1,
9284 INPUT_NOFILE_OK = 2,
9287 static smallint checkkwd;
9288 /* values of checkkwd variable */
9289 #define CHKALIAS 0x1
9294 * Push a string back onto the input at this current parsefile level.
9295 * We handle aliases this way.
9297 #if !ENABLE_ASH_ALIAS
9298 #define pushstring(s, ap) pushstring(s)
9301 pushstring(char *s, struct alias *ap)
9308 if (g_parsefile->strpush) {
9309 sp = ckzalloc(sizeof(*sp));
9310 sp->prev = g_parsefile->strpush;
9312 sp = &(g_parsefile->basestrpush);
9314 g_parsefile->strpush = sp;
9315 sp->prev_string = g_parsefile->next_to_pgetc;
9316 sp->prev_left_in_line = g_parsefile->left_in_line;
9317 #if ENABLE_ASH_ALIAS
9320 ap->flag |= ALIASINUSE;
9324 g_parsefile->next_to_pgetc = s;
9325 g_parsefile->left_in_line = len;
9332 struct strpush *sp = g_parsefile->strpush;
9335 #if ENABLE_ASH_ALIAS
9337 if (g_parsefile->next_to_pgetc[-1] == ' '
9338 || g_parsefile->next_to_pgetc[-1] == '\t'
9340 checkkwd |= CHKALIAS;
9342 if (sp->string != sp->ap->val) {
9345 sp->ap->flag &= ~ALIASINUSE;
9346 if (sp->ap->flag & ALIASDEAD) {
9347 unalias(sp->ap->name);
9351 g_parsefile->next_to_pgetc = sp->prev_string;
9352 g_parsefile->left_in_line = sp->prev_left_in_line;
9353 g_parsefile->strpush = sp->prev;
9354 if (sp != &(g_parsefile->basestrpush))
9359 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9360 //it peeks whether it is &>, and then pushes back both chars.
9361 //This function needs to save last *next_to_pgetc to buf[0]
9362 //to make two pungetc() reliable. Currently,
9363 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9368 char *buf = g_parsefile->buf;
9370 g_parsefile->next_to_pgetc = buf;
9371 #if ENABLE_FEATURE_EDITING
9373 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9374 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9376 #if ENABLE_FEATURE_TAB_COMPLETION
9377 line_input_state->path_lookup = pathval();
9379 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9381 /* Ctrl+C pressed */
9390 if (nr < 0 && errno == 0) {
9391 /* Ctrl+D pressed */
9396 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9400 /* nonblock_safe_read() handles this problem */
9402 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9403 int flags = fcntl(0, F_GETFL);
9404 if (flags >= 0 && (flags & O_NONBLOCK)) {
9405 flags &= ~O_NONBLOCK;
9406 if (fcntl(0, F_SETFL, flags) >= 0) {
9407 out2str("sh: turning off NDELAY mode\n");
9418 * Refill the input buffer and return the next input character:
9420 * 1) If a string was pushed back on the input, pop it;
9421 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9422 * or we are reading from a string so we can't refill the buffer,
9424 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9425 * 4) Process input up to the next newline, deleting nul characters.
9427 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9428 #define pgetc_debug(...) ((void)0)
9435 while (g_parsefile->strpush) {
9436 #if ENABLE_ASH_ALIAS
9437 if (g_parsefile->left_in_line == -1
9438 && g_parsefile->strpush->ap
9439 && g_parsefile->next_to_pgetc[-1] != ' '
9440 && g_parsefile->next_to_pgetc[-1] != '\t'
9442 pgetc_debug("preadbuffer PEOA");
9447 /* try "pgetc" now: */
9448 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9449 g_parsefile->left_in_line,
9450 g_parsefile->next_to_pgetc,
9451 g_parsefile->next_to_pgetc);
9452 if (--g_parsefile->left_in_line >= 0)
9453 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9455 /* on both branches above g_parsefile->left_in_line < 0.
9456 * "pgetc" needs refilling.
9459 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9460 * pungetc() may increment it a few times.
9461 * Assuming it won't increment it to less than -90.
9463 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9464 pgetc_debug("preadbuffer PEOF1");
9465 /* even in failure keep left_in_line and next_to_pgetc
9466 * in lock step, for correct multi-layer pungetc.
9467 * left_in_line was decremented before preadbuffer(),
9468 * must inc next_to_pgetc: */
9469 g_parsefile->next_to_pgetc++;
9473 more = g_parsefile->left_in_buffer;
9475 flush_stdout_stderr();
9479 /* don't try reading again */
9480 g_parsefile->left_in_line = -99;
9481 pgetc_debug("preadbuffer PEOF2");
9482 g_parsefile->next_to_pgetc++;
9487 /* Find out where's the end of line.
9488 * Set g_parsefile->left_in_line
9489 * and g_parsefile->left_in_buffer acordingly.
9490 * NUL chars are deleted.
9492 q = g_parsefile->next_to_pgetc;
9500 memmove(q, q + 1, more);
9504 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9510 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9511 if (g_parsefile->left_in_line < 0)
9516 g_parsefile->left_in_buffer = more;
9521 out2str(g_parsefile->next_to_pgetc);
9525 pgetc_debug("preadbuffer at %d:%p'%s'",
9526 g_parsefile->left_in_line,
9527 g_parsefile->next_to_pgetc,
9528 g_parsefile->next_to_pgetc);
9529 return (unsigned char)*g_parsefile->next_to_pgetc++;
9532 #define pgetc_as_macro() \
9533 (--g_parsefile->left_in_line >= 0 \
9534 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9541 pgetc_debug("pgetc_fast at %d:%p'%s'",
9542 g_parsefile->left_in_line,
9543 g_parsefile->next_to_pgetc,
9544 g_parsefile->next_to_pgetc);
9545 return pgetc_as_macro();
9548 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9549 # define pgetc_fast() pgetc()
9551 # define pgetc_fast() pgetc_as_macro()
9554 #if ENABLE_ASH_ALIAS
9556 pgetc_without_PEOA(void)
9560 pgetc_debug("pgetc_fast at %d:%p'%s'",
9561 g_parsefile->left_in_line,
9562 g_parsefile->next_to_pgetc,
9563 g_parsefile->next_to_pgetc);
9565 } while (c == PEOA);
9569 # define pgetc_without_PEOA() pgetc()
9573 * Read a line from the script.
9576 pfgets(char *line, int len)
9582 while (--nleft > 0) {
9583 c = pgetc_without_PEOA();
9598 * Undo the last call to pgetc. Only one character may be pushed back.
9599 * PEOF may be pushed back.
9604 g_parsefile->left_in_line++;
9605 g_parsefile->next_to_pgetc--;
9606 pgetc_debug("pushed back to %d:%p'%s'",
9607 g_parsefile->left_in_line,
9608 g_parsefile->next_to_pgetc,
9609 g_parsefile->next_to_pgetc);
9613 * To handle the "." command, a stack of input files is used. Pushfile
9614 * adds a new entry to the stack and popfile restores the previous level.
9619 struct parsefile *pf;
9621 pf = ckzalloc(sizeof(*pf));
9622 pf->prev = g_parsefile;
9624 /*pf->strpush = NULL; - ckzalloc did it */
9625 /*pf->basestrpush.prev = NULL;*/
9632 struct parsefile *pf = g_parsefile;
9640 g_parsefile = pf->prev;
9646 * Return to top level.
9651 while (g_parsefile != &basepf)
9656 * Close the file(s) that the shell is reading commands from. Called
9657 * after a fork is done.
9663 if (g_parsefile->fd > 0) {
9664 close(g_parsefile->fd);
9665 g_parsefile->fd = 0;
9670 * Like setinputfile, but takes an open file descriptor. Call this with
9674 setinputfd(int fd, int push)
9676 close_on_exec_on(fd);
9679 g_parsefile->buf = NULL;
9681 g_parsefile->fd = fd;
9682 if (g_parsefile->buf == NULL)
9683 g_parsefile->buf = ckmalloc(IBUFSIZ);
9684 g_parsefile->left_in_buffer = 0;
9685 g_parsefile->left_in_line = 0;
9686 g_parsefile->linno = 1;
9690 * Set the input to take input from a file. If push is set, push the
9691 * old input onto the stack first.
9694 setinputfile(const char *fname, int flags)
9700 fd = open(fname, O_RDONLY);
9702 if (flags & INPUT_NOFILE_OK)
9704 ash_msg_and_raise_error("can't open '%s'", fname);
9707 fd2 = copyfd(fd, 10);
9710 ash_msg_and_raise_error("out of file descriptors");
9713 setinputfd(fd, flags & INPUT_PUSH_FILE);
9720 * Like setinputfile, but takes input from a string.
9723 setinputstring(char *string)
9727 g_parsefile->next_to_pgetc = string;
9728 g_parsefile->left_in_line = strlen(string);
9729 g_parsefile->buf = NULL;
9730 g_parsefile->linno = 1;
9735 /* ============ mail.c
9737 * Routines to check for mail.
9742 #define MAXMBOXES 10
9744 /* times of mailboxes */
9745 static time_t mailtime[MAXMBOXES];
9746 /* Set if MAIL or MAILPATH is changed. */
9747 static smallint mail_var_path_changed;
9750 * Print appropriate message(s) if mail has arrived.
9751 * If mail_var_path_changed is set,
9752 * then the value of MAIL has mail_var_path_changed,
9753 * so we just update the values.
9762 struct stackmark smark;
9765 setstackmark(&smark);
9766 mpath = mpathset() ? mpathval() : mailval();
9767 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9768 p = path_advance(&mpath, nullstr);
9773 for (q = p; *q; q++)
9779 q[-1] = '\0'; /* delete trailing '/' */
9780 if (stat(p, &statb) < 0) {
9784 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9787 pathopt ? pathopt : "you have mail"
9790 *mtp = statb.st_mtime;
9792 mail_var_path_changed = 0;
9793 popstackmark(&smark);
9796 static void FAST_FUNC
9797 changemail(const char *val UNUSED_PARAM)
9799 mail_var_path_changed = 1;
9802 #endif /* ASH_MAIL */
9805 /* ============ ??? */
9808 * Set the shell parameters.
9811 setparam(char **argv)
9817 for (nparam = 0; argv[nparam]; nparam++)
9819 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9821 *ap++ = ckstrdup(*argv++);
9824 freeparam(&shellparam);
9825 shellparam.malloced = 1;
9826 shellparam.nparam = nparam;
9827 shellparam.p = newparam;
9828 #if ENABLE_ASH_GETOPTS
9829 shellparam.optind = 1;
9830 shellparam.optoff = -1;
9835 * Process shell options. The global variable argptr contains a pointer
9836 * to the argument list; we advance it past the options.
9838 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9839 * For a non-interactive shell, an error condition encountered
9840 * by a special built-in ... shall cause the shell to write a diagnostic message
9841 * to standard error and exit as shown in the following table:
9842 * Error Special Built-In
9844 * Utility syntax error (option or operand error) Shall exit
9846 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9847 * we see that bash does not do that (set "finishes" with error code 1 instead,
9848 * and shell continues), and people rely on this behavior!
9850 * set -o barfoo 2>/dev/null
9853 * Oh well. Let's mimic that.
9856 plus_minus_o(char *name, int val)
9861 for (i = 0; i < NOPTS; i++) {
9862 if (strcmp(name, optnames(i)) == 0) {
9867 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9870 for (i = 0; i < NOPTS; i++) {
9872 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9874 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9880 setoption(int flag, int val)
9884 for (i = 0; i < NOPTS; i++) {
9885 if (optletters(i) == flag) {
9890 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9894 options(int cmdline)
9902 while ((p = *argptr) != NULL) {
9904 if (c != '-' && c != '+')
9907 val = 0; /* val = 0 if c == '+' */
9910 if (p[0] == '\0' || LONE_DASH(p)) {
9912 /* "-" means turn off -x and -v */
9915 /* "--" means reset params */
9916 else if (*argptr == NULL)
9919 break; /* "-" or "--" terminates options */
9922 /* first char was + or - */
9923 while ((c = *p++) != '\0') {
9924 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9925 if (c == 'c' && cmdline) {
9926 minusc = p; /* command is after shell args */
9927 } else if (c == 'o') {
9928 if (plus_minus_o(*argptr, val)) {
9929 /* it already printed err message */
9930 return 1; /* error */
9934 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9936 /* bash does not accept +-login, we also won't */
9937 } else if (cmdline && val && (c == '-')) { /* long options */
9938 if (strcmp(p, "login") == 0)
9950 * The shift builtin command.
9952 static int FAST_FUNC
9953 shiftcmd(int argc UNUSED_PARAM, char **argv)
9960 n = number(argv[1]);
9961 if (n > shellparam.nparam)
9962 n = 0; /* bash compat, was = shellparam.nparam; */
9964 shellparam.nparam -= n;
9965 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9966 if (shellparam.malloced)
9970 while ((*ap2++ = *ap1++) != NULL)
9972 #if ENABLE_ASH_GETOPTS
9973 shellparam.optind = 1;
9974 shellparam.optoff = -1;
9981 * POSIX requires that 'set' (but not export or readonly) output the
9982 * variables in lexicographic order - by the locale's collating order (sigh).
9983 * Maybe we could keep them in an ordered balanced binary tree
9984 * instead of hashed lists.
9985 * For now just roll 'em through qsort for printing...
9988 showvars(const char *sep_prefix, int on, int off)
9993 ep = listvars(on, off, &epend);
9994 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9996 sep = *sep_prefix ? " " : sep_prefix;
9998 for (; ep < epend; ep++) {
10002 p = strchrnul(*ep, '=');
10005 q = single_quote(++p);
10006 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10012 * The set command builtin.
10014 static int FAST_FUNC
10015 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10020 return showvars(nullstr, 0, VUNSET);
10023 if (!options(0)) { /* if no parse error... */
10026 if (*argptr != NULL) {
10034 #if ENABLE_ASH_RANDOM_SUPPORT
10035 static void FAST_FUNC
10036 change_random(const char *value)
10040 if (value == NULL) {
10041 /* "get", generate */
10042 t = next_random(&random_gen);
10043 /* set without recursion */
10044 setvar(vrandom.text, utoa(t), VNOFUNC);
10045 vrandom.flags &= ~VNOFUNC;
10048 t = strtoul(value, NULL, 10);
10049 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10054 #if ENABLE_ASH_GETOPTS
10056 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10065 if (*param_optind < 1)
10067 optnext = optfirst + *param_optind - 1;
10069 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10072 p = optnext[-1] + *optoff;
10073 if (p == NULL || *p == '\0') {
10074 /* Current word is done, advance */
10076 if (p == NULL || *p != '-' || *++p == '\0') {
10083 if (LONE_DASH(p)) /* check for "--" */
10088 for (q = optstr; *q != c;) {
10090 if (optstr[0] == ':') {
10093 err |= setvarsafe("OPTARG", s, 0);
10095 fprintf(stderr, "Illegal option -%c\n", c);
10096 unsetvar("OPTARG");
10106 if (*p == '\0' && (p = *optnext) == NULL) {
10107 if (optstr[0] == ':') {
10110 err |= setvarsafe("OPTARG", s, 0);
10113 fprintf(stderr, "No arg for -%c option\n", c);
10114 unsetvar("OPTARG");
10122 err |= setvarsafe("OPTARG", p, 0);
10125 err |= setvarsafe("OPTARG", nullstr, 0);
10127 *optoff = p ? p - *(optnext - 1) : -1;
10128 *param_optind = optnext - optfirst + 1;
10129 fmtstr(s, sizeof(s), "%d", *param_optind);
10130 err |= setvarsafe("OPTIND", s, VNOFUNC);
10133 err |= setvarsafe(optvar, s, 0);
10137 flush_stdout_stderr();
10138 raise_exception(EXERROR);
10144 * The getopts builtin. Shellparam.optnext points to the next argument
10145 * to be processed. Shellparam.optptr points to the next character to
10146 * be processed in the current argument. If shellparam.optnext is NULL,
10147 * then it's the first time getopts has been called.
10149 static int FAST_FUNC
10150 getoptscmd(int argc, char **argv)
10155 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10157 optbase = shellparam.p;
10158 if (shellparam.optind > shellparam.nparam + 1) {
10159 shellparam.optind = 1;
10160 shellparam.optoff = -1;
10163 optbase = &argv[3];
10164 if (shellparam.optind > argc - 2) {
10165 shellparam.optind = 1;
10166 shellparam.optoff = -1;
10170 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10171 &shellparam.optoff);
10173 #endif /* ASH_GETOPTS */
10176 /* ============ Shell parser */
10179 struct heredoc *next; /* next here document in list */
10180 union node *here; /* redirection node */
10181 char *eofmark; /* string indicating end of input */
10182 smallint striptabs; /* if set, strip leading tabs */
10185 static smallint tokpushback; /* last token pushed back */
10186 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10187 static smallint quoteflag; /* set if (part of) last token was quoted */
10188 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10189 static struct heredoc *heredoclist; /* list of here documents to read */
10190 static char *wordtext; /* text of last word returned by readtoken */
10191 static struct nodelist *backquotelist;
10192 static union node *redirnode;
10193 static struct heredoc *heredoc;
10196 * Called when an unexpected token is read during the parse. The argument
10197 * is the token that is expected, or -1 if more than one type of token can
10198 * occur at this point.
10200 static void raise_error_unexpected_syntax(int) NORETURN;
10202 raise_error_unexpected_syntax(int token)
10207 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10209 sprintf(msg + l, " (expecting %s)", tokname(token));
10210 raise_error_syntax(msg);
10214 #define EOFMARKLEN 79
10216 /* parsing is heavily cross-recursive, need these forward decls */
10217 static union node *andor(void);
10218 static union node *pipeline(void);
10219 static union node *parse_command(void);
10220 static void parseheredoc(void);
10221 static char peektoken(void);
10222 static int readtoken(void);
10224 static union node *
10227 union node *n1, *n2, *n3;
10230 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10231 if (nlflag == 2 && peektoken())
10237 if (tok == TBACKGND) {
10238 if (n2->type == NPIPE) {
10239 n2->npipe.pipe_backgnd = 1;
10241 if (n2->type != NREDIR) {
10242 n3 = stzalloc(sizeof(struct nredir));
10244 /*n3->nredir.redirect = NULL; - stzalloc did it */
10247 n2->type = NBACKGND;
10253 n3 = stzalloc(sizeof(struct nbinary));
10255 n3->nbinary.ch1 = n1;
10256 n3->nbinary.ch2 = n2;
10272 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10280 pungetc(); /* push back EOF on input */
10284 raise_error_unexpected_syntax(-1);
10291 static union node *
10294 union node *n1, *n2, *n3;
10302 } else if (t == TOR) {
10308 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10310 n3 = stzalloc(sizeof(struct nbinary));
10312 n3->nbinary.ch1 = n1;
10313 n3->nbinary.ch2 = n2;
10318 static union node *
10321 union node *n1, *n2, *pipenode;
10322 struct nodelist *lp, *prev;
10326 TRACE(("pipeline: entered\n"));
10327 if (readtoken() == TNOT) {
10329 checkkwd = CHKKWD | CHKALIAS;
10332 n1 = parse_command();
10333 if (readtoken() == TPIPE) {
10334 pipenode = stzalloc(sizeof(struct npipe));
10335 pipenode->type = NPIPE;
10336 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10337 lp = stzalloc(sizeof(struct nodelist));
10338 pipenode->npipe.cmdlist = lp;
10342 lp = stzalloc(sizeof(struct nodelist));
10343 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10344 lp->n = parse_command();
10346 } while (readtoken() == TPIPE);
10352 n2 = stzalloc(sizeof(struct nnot));
10360 static union node *
10365 n = stzalloc(sizeof(struct narg));
10367 /*n->narg.next = NULL; - stzalloc did it */
10368 n->narg.text = wordtext;
10369 n->narg.backquote = backquotelist;
10374 fixredir(union node *n, const char *text, int err)
10378 TRACE(("Fix redir %s %d\n", text, err));
10380 n->ndup.vname = NULL;
10382 fd = bb_strtou(text, NULL, 10);
10383 if (!errno && fd >= 0)
10384 n->ndup.dupfd = fd;
10385 else if (LONE_DASH(text))
10386 n->ndup.dupfd = -1;
10389 raise_error_syntax("bad fd number");
10390 n->ndup.vname = makename();
10395 * Returns true if the text contains nothing to expand (no dollar signs
10399 noexpand(const char *text)
10403 while ((c = *text++) != '\0') {
10404 if (c == CTLQUOTEMARK)
10408 else if (SIT(c, BASESYNTAX) == CCTL)
10417 union node *n = redirnode;
10419 if (readtoken() != TWORD)
10420 raise_error_unexpected_syntax(-1);
10421 if (n->type == NHERE) {
10422 struct heredoc *here = heredoc;
10426 if (quoteflag == 0)
10428 TRACE(("Here document %d\n", n->type));
10429 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10430 raise_error_syntax("illegal eof marker for << redirection");
10431 rmescapes(wordtext, 0);
10432 here->eofmark = wordtext;
10434 if (heredoclist == NULL)
10435 heredoclist = here;
10437 for (p = heredoclist; p->next; p = p->next)
10441 } else if (n->type == NTOFD || n->type == NFROMFD) {
10442 fixredir(n, wordtext, 0);
10444 n->nfile.fname = makename();
10448 static union node *
10451 union node *args, **app;
10452 union node *n = NULL;
10453 union node *vars, **vpp;
10454 union node **rpp, *redir;
10456 #if ENABLE_ASH_BASH_COMPAT
10457 smallint double_brackets_flag = 0;
10467 savecheckkwd = CHKALIAS;
10470 checkkwd = savecheckkwd;
10473 #if ENABLE_ASH_BASH_COMPAT
10474 case TAND: /* "&&" */
10475 case TOR: /* "||" */
10476 if (!double_brackets_flag) {
10480 wordtext = (char *) (t == TAND ? "-a" : "-o");
10483 n = stzalloc(sizeof(struct narg));
10485 /*n->narg.next = NULL; - stzalloc did it */
10486 n->narg.text = wordtext;
10487 #if ENABLE_ASH_BASH_COMPAT
10488 if (strcmp("[[", wordtext) == 0)
10489 double_brackets_flag = 1;
10490 else if (strcmp("]]", wordtext) == 0)
10491 double_brackets_flag = 0;
10493 n->narg.backquote = backquotelist;
10494 if (savecheckkwd && isassignment(wordtext)) {
10496 vpp = &n->narg.next;
10499 app = &n->narg.next;
10504 *rpp = n = redirnode;
10505 rpp = &n->nfile.next;
10506 parsefname(); /* read name of redirection file */
10509 if (args && app == &args->narg.next
10512 struct builtincmd *bcmd;
10515 /* We have a function */
10516 if (readtoken() != TRP)
10517 raise_error_unexpected_syntax(TRP);
10518 name = n->narg.text;
10519 if (!goodname(name)
10520 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10522 raise_error_syntax("bad function name");
10525 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10526 n->narg.next = parse_command();
10539 n = stzalloc(sizeof(struct ncmd));
10541 n->ncmd.args = args;
10542 n->ncmd.assign = vars;
10543 n->ncmd.redirect = redir;
10547 static union node *
10548 parse_command(void)
10550 union node *n1, *n2;
10551 union node *ap, **app;
10552 union node *cp, **cpp;
10553 union node *redir, **rpp;
10560 switch (readtoken()) {
10562 raise_error_unexpected_syntax(-1);
10565 n1 = stzalloc(sizeof(struct nif));
10567 n1->nif.test = list(0);
10568 if (readtoken() != TTHEN)
10569 raise_error_unexpected_syntax(TTHEN);
10570 n1->nif.ifpart = list(0);
10572 while (readtoken() == TELIF) {
10573 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10574 n2 = n2->nif.elsepart;
10576 n2->nif.test = list(0);
10577 if (readtoken() != TTHEN)
10578 raise_error_unexpected_syntax(TTHEN);
10579 n2->nif.ifpart = list(0);
10581 if (lasttoken == TELSE)
10582 n2->nif.elsepart = list(0);
10584 n2->nif.elsepart = NULL;
10592 n1 = stzalloc(sizeof(struct nbinary));
10593 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10594 n1->nbinary.ch1 = list(0);
10597 TRACE(("expecting DO got %s %s\n", tokname(got),
10598 got == TWORD ? wordtext : ""));
10599 raise_error_unexpected_syntax(TDO);
10601 n1->nbinary.ch2 = list(0);
10606 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10607 raise_error_syntax("bad for loop variable");
10608 n1 = stzalloc(sizeof(struct nfor));
10610 n1->nfor.var = wordtext;
10611 checkkwd = CHKKWD | CHKALIAS;
10612 if (readtoken() == TIN) {
10614 while (readtoken() == TWORD) {
10615 n2 = stzalloc(sizeof(struct narg));
10617 /*n2->narg.next = NULL; - stzalloc did it */
10618 n2->narg.text = wordtext;
10619 n2->narg.backquote = backquotelist;
10621 app = &n2->narg.next;
10624 n1->nfor.args = ap;
10625 if (lasttoken != TNL && lasttoken != TSEMI)
10626 raise_error_unexpected_syntax(-1);
10628 n2 = stzalloc(sizeof(struct narg));
10630 /*n2->narg.next = NULL; - stzalloc did it */
10631 n2->narg.text = (char *)dolatstr;
10632 /*n2->narg.backquote = NULL;*/
10633 n1->nfor.args = n2;
10635 * Newline or semicolon here is optional (but note
10636 * that the original Bourne shell only allowed NL).
10638 if (lasttoken != TNL && lasttoken != TSEMI)
10641 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10642 if (readtoken() != TDO)
10643 raise_error_unexpected_syntax(TDO);
10644 n1->nfor.body = list(0);
10648 n1 = stzalloc(sizeof(struct ncase));
10650 if (readtoken() != TWORD)
10651 raise_error_unexpected_syntax(TWORD);
10652 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10654 /*n2->narg.next = NULL; - stzalloc did it */
10655 n2->narg.text = wordtext;
10656 n2->narg.backquote = backquotelist;
10658 checkkwd = CHKKWD | CHKALIAS;
10659 } while (readtoken() == TNL);
10660 if (lasttoken != TIN)
10661 raise_error_unexpected_syntax(TIN);
10662 cpp = &n1->ncase.cases;
10664 checkkwd = CHKNL | CHKKWD;
10666 while (t != TESAC) {
10667 if (lasttoken == TLP)
10669 *cpp = cp = stzalloc(sizeof(struct nclist));
10671 app = &cp->nclist.pattern;
10673 *app = ap = stzalloc(sizeof(struct narg));
10675 /*ap->narg.next = NULL; - stzalloc did it */
10676 ap->narg.text = wordtext;
10677 ap->narg.backquote = backquotelist;
10678 if (readtoken() != TPIPE)
10680 app = &ap->narg.next;
10683 //ap->narg.next = NULL;
10684 if (lasttoken != TRP)
10685 raise_error_unexpected_syntax(TRP);
10686 cp->nclist.body = list(2);
10688 cpp = &cp->nclist.next;
10690 checkkwd = CHKNL | CHKKWD;
10694 raise_error_unexpected_syntax(TENDCASE);
10701 n1 = stzalloc(sizeof(struct nredir));
10702 n1->type = NSUBSHELL;
10703 n1->nredir.n = list(0);
10704 /*n1->nredir.redirect = NULL; - stzalloc did it */
10714 return simplecmd();
10717 if (readtoken() != t)
10718 raise_error_unexpected_syntax(t);
10721 /* Now check for redirection which may follow command */
10722 checkkwd = CHKKWD | CHKALIAS;
10724 while (readtoken() == TREDIR) {
10725 *rpp = n2 = redirnode;
10726 rpp = &n2->nfile.next;
10732 if (n1->type != NSUBSHELL) {
10733 n2 = stzalloc(sizeof(struct nredir));
10738 n1->nredir.redirect = redir;
10743 #if ENABLE_ASH_BASH_COMPAT
10744 static int decode_dollar_squote(void)
10746 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10752 p = strchr(C_escapes, c);
10757 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10761 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10763 } else if (c == 'x') { /* \xHH */
10767 } while (isxdigit(c) && --cnt);
10769 if (cnt == 3) { /* \x but next char is "bad" */
10773 } else { /* simple seq like \\ or \t */
10778 c = bb_process_escape_sequence((void*)&p);
10779 } else { /* unrecognized "\z": print both chars unless ' or " */
10780 if (c != '\'' && c != '"') {
10782 c |= 0x100; /* "please encode \, then me" */
10790 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10791 * is not NULL, read a here document. In the latter case, eofmark is the
10792 * word which marks the end of the document and striptabs is true if
10793 * leading tabs should be stripped from the document. The argument c
10794 * is the first character of the input token or document.
10796 * Because C does not have internal subroutines, I have simulated them
10797 * using goto's to implement the subroutine linkage. The following macros
10798 * will run code that appears at the end of readtoken1.
10800 #define CHECKEND() {goto checkend; checkend_return:;}
10801 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10802 #define PARSESUB() {goto parsesub; parsesub_return:;}
10803 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10804 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10805 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10807 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10809 /* NB: syntax parameter fits into smallint */
10810 /* c parameter is an unsigned char or PEOF or PEOA */
10813 char line[EOFMARKLEN + 1];
10814 struct nodelist *bqlist;
10818 smallint prevsyntax; /* syntax before arithmetic */
10819 #if ENABLE_ASH_EXPAND_PRMT
10820 smallint pssyntax; /* we are expanding a prompt string */
10822 int varnest; /* levels of variables expansion */
10823 int arinest; /* levels of arithmetic expansion */
10824 int parenlevel; /* levels of parens in arithmetic */
10825 int dqvarnest; /* levels of variables expansion within double quotes */
10827 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10830 /* Avoid longjmp clobbering */
10836 (void) &parenlevel;
10839 (void) &prevsyntax;
10842 startlinno = g_parsefile->linno;
10847 #if ENABLE_ASH_EXPAND_PRMT
10848 pssyntax = (syntax == PSSYNTAX);
10852 dblquote = (syntax == DQSYNTAX);
10858 STARTSTACKSTR(out);
10860 /* For each line, until end of word */
10862 CHECKEND(); /* set c to PEOF if at end of here document */
10863 for (;;) { /* until end of line or end of word */
10864 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10865 switch (SIT(c, syntax)) {
10866 case CNL: /* '\n' */
10867 if (syntax == BASESYNTAX)
10868 goto endword; /* exit outer loop */
10870 g_parsefile->linno++;
10874 goto loop; /* continue outer loop */
10879 if (eofmark == NULL || dblquote)
10880 USTPUTC(CTLESC, out);
10881 #if ENABLE_ASH_BASH_COMPAT
10882 if (c == '\\' && bash_dollar_squote) {
10883 c = decode_dollar_squote();
10885 USTPUTC('\\', out);
10886 c = (unsigned char)c;
10892 case CBACK: /* backslash */
10893 c = pgetc_without_PEOA();
10895 USTPUTC(CTLESC, out);
10896 USTPUTC('\\', out);
10898 } else if (c == '\n') {
10902 #if ENABLE_ASH_EXPAND_PRMT
10903 if (c == '$' && pssyntax) {
10904 USTPUTC(CTLESC, out);
10905 USTPUTC('\\', out);
10908 if (dblquote && c != '\\'
10909 && c != '`' && c != '$'
10910 && (c != '"' || eofmark != NULL)
10912 USTPUTC(CTLESC, out);
10913 USTPUTC('\\', out);
10915 if (SIT(c, SQSYNTAX) == CCTL)
10916 USTPUTC(CTLESC, out);
10924 if (eofmark == NULL) {
10925 USTPUTC(CTLQUOTEMARK, out);
10933 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10934 if (eofmark != NULL && arinest == 0
10939 if (dqvarnest == 0) {
10940 syntax = BASESYNTAX;
10947 case CVAR: /* '$' */
10948 PARSESUB(); /* parse substitution */
10950 case CENDVAR: /* '}' */
10953 if (dqvarnest > 0) {
10956 USTPUTC(CTLENDVAR, out);
10961 #if ENABLE_SH_MATH_SUPPORT
10962 case CLP: /* '(' in arithmetic */
10966 case CRP: /* ')' in arithmetic */
10967 if (parenlevel > 0) {
10971 if (pgetc() == ')') {
10972 if (--arinest == 0) {
10973 USTPUTC(CTLENDARI, out);
10974 syntax = prevsyntax;
10975 dblquote = (syntax == DQSYNTAX);
10980 * unbalanced parens
10981 * (don't 2nd guess - no error)
10989 case CBQUOTE: /* '`' */
10993 goto endword; /* exit outer loop */
10997 if (varnest == 0) {
10998 #if ENABLE_ASH_BASH_COMPAT
11000 if (pgetc() == '>')
11001 c = 0x100 + '>'; /* flag &> */
11005 goto endword; /* exit outer loop */
11007 IF_ASH_ALIAS(if (c != PEOA))
11015 #if ENABLE_SH_MATH_SUPPORT
11016 if (syntax == ARISYNTAX)
11017 raise_error_syntax("missing '))'");
11019 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11020 raise_error_syntax("unterminated quoted string");
11021 if (varnest != 0) {
11022 startlinno = g_parsefile->linno;
11024 raise_error_syntax("missing '}'");
11026 USTPUTC('\0', out);
11027 len = out - (char *)stackblock();
11028 out = stackblock();
11029 if (eofmark == NULL) {
11030 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11033 if (isdigit_str9(out)) {
11034 PARSEREDIR(); /* passed as params: out, c */
11035 lasttoken = TREDIR;
11038 /* else: non-number X seen, interpret it
11039 * as "NNNX>file" = "NNNX >file" */
11043 quoteflag = quotef;
11044 backquotelist = bqlist;
11045 grabstackblock(len);
11049 /* end of readtoken routine */
11052 * Check to see whether we are at the end of the here document. When this
11053 * is called, c is set to the first character of the next input line. If
11054 * we are at the end of the here document, this routine sets the c to PEOF.
11058 #if ENABLE_ASH_ALIAS
11060 c = pgetc_without_PEOA();
11063 while (c == '\t') {
11064 c = pgetc_without_PEOA();
11067 if (c == *eofmark) {
11068 if (pfgets(line, sizeof(line)) != NULL) {
11072 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11074 if (*p == '\n' && *q == '\0') {
11076 g_parsefile->linno++;
11077 needprompt = doprompt;
11079 pushstring(line, NULL);
11084 goto checkend_return;
11088 * Parse a redirection operator. The variable "out" points to a string
11089 * specifying the fd to be redirected. The variable "c" contains the
11090 * first character of the redirection operator.
11093 /* out is already checked to be a valid number or "" */
11094 int fd = (*out == '\0' ? -1 : atoi(out));
11097 np = stzalloc(sizeof(struct nfile));
11102 np->type = NAPPEND;
11104 np->type = NCLOBBER;
11107 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11113 #if ENABLE_ASH_BASH_COMPAT
11114 else if (c == 0x100 + '>') { /* this flags &> redirection */
11116 pgetc(); /* this is '>', no need to check */
11120 else { /* c == '<' */
11121 /*np->nfile.fd = 0; - stzalloc did it */
11125 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11126 np = stzalloc(sizeof(struct nhere));
11127 /*np->nfile.fd = 0; - stzalloc did it */
11130 heredoc = stzalloc(sizeof(struct heredoc));
11131 heredoc->here = np;
11134 heredoc->striptabs = 1;
11136 /*heredoc->striptabs = 0; - stzalloc did it */
11142 np->type = NFROMFD;
11146 np->type = NFROMTO;
11158 goto parseredir_return;
11162 * Parse a substitution. At this point, we have read the dollar sign
11163 * and nothing else.
11166 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11167 * (assuming ascii char codes, as the original implementation did) */
11168 #define is_special(c) \
11169 (((unsigned)(c) - 33 < 32) \
11170 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11172 unsigned char subtype;
11176 static const char types[] ALIGN1 = "}-+?=";
11179 if (c > 255 /* PEOA or PEOF */
11180 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11182 #if ENABLE_ASH_BASH_COMPAT
11184 bash_dollar_squote = 1;
11189 } else if (c == '(') { /* $(command) or $((arith)) */
11190 if (pgetc() == '(') {
11191 #if ENABLE_SH_MATH_SUPPORT
11194 raise_error_syntax("you disabled math support for $((arith)) syntax");
11201 USTPUTC(CTLVAR, out);
11202 typeloc = out - (char *)stackblock();
11203 USTPUTC(VSNORMAL, out);
11204 subtype = VSNORMAL;
11212 subtype = VSLENGTH;
11216 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11220 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11221 } else if (isdigit(c)) {
11225 } while (isdigit(c));
11226 } else if (is_special(c)) {
11231 raise_error_syntax("bad substitution");
11233 if (c != '}' && subtype == VSLENGTH)
11238 if (subtype == 0) {
11242 #if ENABLE_ASH_BASH_COMPAT
11243 if (c == ':' || c == '$' || isdigit(c)) {
11245 subtype = VSSUBSTR;
11252 p = strchr(types, c);
11255 subtype = p - types + VSNORMAL;
11260 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11268 #if ENABLE_ASH_BASH_COMPAT
11270 subtype = VSREPLACE;
11273 subtype++; /* VSREPLACEALL */
11282 if (dblquote || arinest)
11284 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11285 if (subtype != VSNORMAL) {
11287 if (dblquote || arinest) {
11292 goto parsesub_return;
11296 * Called to parse command substitutions. Newstyle is set if the command
11297 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11298 * list of commands (passed by reference), and savelen is the number of
11299 * characters on the top of the stack which must be preserved.
11302 struct nodelist **nlpp;
11305 char *volatile str;
11306 struct jmploc jmploc;
11307 struct jmploc *volatile savehandler;
11309 smallint saveprompt = 0;
11312 (void) &saveprompt;
11314 savepbq = parsebackquote;
11315 if (setjmp(jmploc.loc)) {
11317 parsebackquote = 0;
11318 exception_handler = savehandler;
11319 longjmp(exception_handler->loc, 1);
11323 savelen = out - (char *)stackblock();
11325 str = ckmalloc(savelen);
11326 memcpy(str, stackblock(), savelen);
11328 savehandler = exception_handler;
11329 exception_handler = &jmploc;
11332 /* We must read until the closing backquote, giving special
11333 treatment to some slashes, and then push the string and
11334 reread it as input, interpreting it normally. */
11341 STARTSTACKSTR(pout);
11354 g_parsefile->linno++;
11358 * If eating a newline, avoid putting
11359 * the newline into the new character
11360 * stream (via the STPUTC after the
11365 if (pc != '\\' && pc != '`' && pc != '$'
11366 && (!dblquote || pc != '"')
11368 STPUTC('\\', pout);
11370 if (pc <= 255 /* not PEOA or PEOF */) {
11376 IF_ASH_ALIAS(case PEOA:)
11377 startlinno = g_parsefile->linno;
11378 raise_error_syntax("EOF in backquote substitution");
11381 g_parsefile->linno++;
11382 needprompt = doprompt;
11391 STPUTC('\0', pout);
11392 psavelen = pout - (char *)stackblock();
11393 if (psavelen > 0) {
11394 pstr = grabstackstr(pout);
11395 setinputstring(pstr);
11400 nlpp = &(*nlpp)->next;
11401 *nlpp = stzalloc(sizeof(**nlpp));
11402 /* (*nlpp)->next = NULL; - stzalloc did it */
11403 parsebackquote = oldstyle;
11406 saveprompt = doprompt;
11413 doprompt = saveprompt;
11414 else if (readtoken() != TRP)
11415 raise_error_unexpected_syntax(TRP);
11420 * Start reading from old file again, ignoring any pushed back
11421 * tokens left from the backquote parsing
11426 while (stackblocksize() <= savelen)
11428 STARTSTACKSTR(out);
11430 memcpy(out, str, savelen);
11431 STADJUST(savelen, out);
11437 parsebackquote = savepbq;
11438 exception_handler = savehandler;
11439 if (arinest || dblquote)
11440 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11442 USTPUTC(CTLBACKQ, out);
11444 goto parsebackq_oldreturn;
11445 goto parsebackq_newreturn;
11448 #if ENABLE_SH_MATH_SUPPORT
11450 * Parse an arithmetic expansion (indicate start of one and set state)
11453 if (++arinest == 1) {
11454 prevsyntax = syntax;
11455 syntax = ARISYNTAX;
11456 USTPUTC(CTLARI, out);
11463 * we collapse embedded arithmetic expansion to
11464 * parenthesis, which should be equivalent
11468 goto parsearith_return;
11472 } /* end of readtoken */
11475 * Read the next input token.
11476 * If the token is a word, we set backquotelist to the list of cmds in
11477 * backquotes. We set quoteflag to true if any part of the word was
11479 * If the token is TREDIR, then we set redirnode to a structure containing
11481 * In all cases, the variable startlinno is set to the number of the line
11482 * on which the token starts.
11484 * [Change comment: here documents and internal procedures]
11485 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11486 * word parsing code into a separate routine. In this case, readtoken
11487 * doesn't need to have any internal procedures, but parseword does.
11488 * We could also make parseoperator in essence the main routine, and
11489 * have parseword (readtoken1?) handle both words and redirection.]
11491 #define NEW_xxreadtoken
11492 #ifdef NEW_xxreadtoken
11493 /* singles must be first! */
11494 static const char xxreadtoken_chars[7] ALIGN1 = {
11495 '\n', '(', ')', /* singles */
11496 '&', '|', ';', /* doubles */
11500 #define xxreadtoken_singles 3
11501 #define xxreadtoken_doubles 3
11503 static const char xxreadtoken_tokens[] ALIGN1 = {
11504 TNL, TLP, TRP, /* only single occurrence allowed */
11505 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11506 TEOF, /* corresponds to trailing nul */
11507 TAND, TOR, TENDCASE /* if double occurrence */
11522 startlinno = g_parsefile->linno;
11523 for (;;) { /* until token or start of word found */
11525 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11529 while ((c = pgetc()) != '\n' && c != PEOF)
11532 } else if (c == '\\') {
11533 if (pgetc() != '\n') {
11535 break; /* return readtoken1(...) */
11537 startlinno = ++g_parsefile->linno;
11543 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11546 g_parsefile->linno++;
11547 needprompt = doprompt;
11550 p = strchr(xxreadtoken_chars, c);
11552 break; /* return readtoken1(...) */
11554 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11556 if (cc == c) { /* double occurrence? */
11557 p += xxreadtoken_doubles + 1;
11560 #if ENABLE_ASH_BASH_COMPAT
11561 if (c == '&' && cc == '>') /* &> */
11562 break; /* return readtoken1(...) */
11567 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11572 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11574 #else /* old xxreadtoken */
11575 #define RETURN(token) return lasttoken = token
11588 startlinno = g_parsefile->linno;
11589 for (;;) { /* until token or start of word found */
11592 case ' ': case '\t':
11593 IF_ASH_ALIAS(case PEOA:)
11596 while ((c = pgetc()) != '\n' && c != PEOF)
11601 if (pgetc() == '\n') {
11602 startlinno = ++g_parsefile->linno;
11610 g_parsefile->linno++;
11611 needprompt = doprompt;
11616 if (pgetc() == '&')
11621 if (pgetc() == '|')
11626 if (pgetc() == ';')
11639 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11642 #endif /* old xxreadtoken */
11649 smallint alreadyseen = tokpushback;
11652 #if ENABLE_ASH_ALIAS
11661 if (checkkwd & CHKNL) {
11668 if (t != TWORD || quoteflag) {
11673 * check for keywords
11675 if (checkkwd & CHKKWD) {
11676 const char *const *pp;
11678 pp = findkwd(wordtext);
11680 lasttoken = t = pp - tokname_array;
11681 TRACE(("keyword %s recognized\n", tokname(t)));
11686 if (checkkwd & CHKALIAS) {
11687 #if ENABLE_ASH_ALIAS
11689 ap = lookupalias(wordtext, 1);
11692 pushstring(ap->val, ap);
11702 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11704 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11716 return tokname_array[t][0];
11720 * Read and parse a command. Returns NODE_EOF on end of file.
11721 * (NULL is a valid parse tree indicating a blank line.)
11723 static union node *
11724 parsecmd(int interact)
11729 doprompt = interact;
11731 setprompt(doprompt);
11743 * Input any here documents.
11748 struct heredoc *here;
11751 here = heredoclist;
11752 heredoclist = NULL;
11758 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11759 here->eofmark, here->striptabs);
11760 n = stzalloc(sizeof(struct narg));
11761 n->narg.type = NARG;
11762 /*n->narg.next = NULL; - stzalloc did it */
11763 n->narg.text = wordtext;
11764 n->narg.backquote = backquotelist;
11765 here->here->nhere.doc = n;
11772 * called by editline -- any expansions to the prompt should be added here.
11774 #if ENABLE_ASH_EXPAND_PRMT
11775 static const char *
11776 expandstr(const char *ps)
11780 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11781 * and token processing _can_ alter it (delete NULs etc). */
11782 setinputstring((char *)ps);
11783 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11786 n.narg.type = NARG;
11787 n.narg.next = NULL;
11788 n.narg.text = wordtext;
11789 n.narg.backquote = backquotelist;
11791 expandarg(&n, NULL, 0);
11792 return stackblock();
11797 * Execute a command or commands contained in a string.
11800 evalstring(char *s, int mask)
11803 struct stackmark smark;
11807 setstackmark(&smark);
11810 while ((n = parsecmd(0)) != NODE_EOF) {
11812 popstackmark(&smark);
11825 * The eval command.
11827 static int FAST_FUNC
11828 evalcmd(int argc UNUSED_PARAM, char **argv)
11837 STARTSTACKSTR(concat);
11839 concat = stack_putstr(p, concat);
11843 STPUTC(' ', concat);
11845 STPUTC('\0', concat);
11846 p = grabstackstr(concat);
11848 evalstring(p, ~SKIPEVAL);
11855 * Read and execute commands. "Top" is nonzero for the top level command
11856 * loop; it turns on prompting if the shell is interactive.
11862 struct stackmark smark;
11866 TRACE(("cmdloop(%d) called\n", top));
11870 setstackmark(&smark);
11873 showjobs(stderr, SHOW_CHANGED);
11876 if (iflag && top) {
11878 #if ENABLE_ASH_MAIL
11882 n = parsecmd(inter);
11884 if (DEBUG > 2 && debug && (n != NODE_EOF))
11887 if (n == NODE_EOF) {
11888 if (!top || numeof >= 50)
11890 if (!stoppedjobs()) {
11893 out2str("\nUse \"exit\" to leave shell.\n");
11896 } else if (nflag == 0) {
11897 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11902 popstackmark(&smark);
11907 return skip & SKIPEVAL;
11914 * Take commands from a file. To be compatible we should do a path
11915 * search for the file, which is necessary to find sub-commands.
11918 find_dot_file(char *name)
11921 const char *path = pathval();
11924 /* don't try this for absolute or relative paths */
11925 if (strchr(name, '/'))
11928 /* IIRC standards do not say whether . is to be searched.
11929 * And it is even smaller this way, making it unconditional for now:
11931 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11936 while ((fullname = path_advance(&path, name)) != NULL) {
11938 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11940 * Don't bother freeing here, since it will
11941 * be freed by the caller.
11945 if (fullname != name)
11946 stunalloc(fullname);
11949 /* not found in the PATH */
11950 ash_msg_and_raise_error("%s: not found", name);
11954 static int FAST_FUNC
11955 dotcmd(int argc, char **argv)
11957 struct strlist *sp;
11958 volatile struct shparam saveparam;
11961 for (sp = cmdenviron; sp; sp = sp->next)
11962 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11964 if (argv[1]) { /* That's what SVR2 does */
11965 char *fullname = find_dot_file(argv[1]);
11968 if (argc) { /* argc > 0, argv[0] != NULL */
11969 saveparam = shellparam;
11970 shellparam.malloced = 0;
11971 shellparam.nparam = argc;
11972 shellparam.p = argv;
11975 setinputfile(fullname, INPUT_PUSH_FILE);
11976 commandname = fullname;
11981 freeparam(&shellparam);
11982 shellparam = saveparam;
11984 status = exitstatus;
11989 static int FAST_FUNC
11990 exitcmd(int argc UNUSED_PARAM, char **argv)
11995 exitstatus = number(argv[1]);
11996 raise_exception(EXEXIT);
12001 * Read a file containing shell functions.
12004 readcmdfile(char *name)
12006 setinputfile(name, INPUT_PUSH_FILE);
12012 /* ============ find_command inplementation */
12015 * Resolve a command name. If you change this routine, you may have to
12016 * change the shellexec routine as well.
12019 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12021 struct tblentry *cmdp;
12028 struct builtincmd *bcmd;
12030 /* If name contains a slash, don't use PATH or hash table */
12031 if (strchr(name, '/') != NULL) {
12032 entry->u.index = -1;
12033 if (act & DO_ABS) {
12034 while (stat(name, &statb) < 0) {
12036 if (errno == EINTR)
12039 entry->cmdtype = CMDUNKNOWN;
12043 entry->cmdtype = CMDNORMAL;
12047 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12049 updatetbl = (path == pathval());
12052 if (strstr(path, "%builtin") != NULL)
12053 act |= DO_ALTBLTIN;
12056 /* If name is in the table, check answer will be ok */
12057 cmdp = cmdlookup(name, 0);
12058 if (cmdp != NULL) {
12061 switch (cmdp->cmdtype) {
12079 } else if (cmdp->rehash == 0)
12080 /* if not invalidated by cd, we're done */
12084 /* If %builtin not in path, check for builtin next */
12085 bcmd = find_builtin(name);
12087 if (IS_BUILTIN_REGULAR(bcmd))
12088 goto builtin_success;
12089 if (act & DO_ALTPATH) {
12090 if (!(act & DO_ALTBLTIN))
12091 goto builtin_success;
12092 } else if (builtinloc <= 0) {
12093 goto builtin_success;
12097 #if ENABLE_FEATURE_SH_STANDALONE
12099 int applet_no = find_applet_by_name(name);
12100 if (applet_no >= 0) {
12101 entry->cmdtype = CMDNORMAL;
12102 entry->u.index = -2 - applet_no;
12108 /* We have to search path. */
12109 prev = -1; /* where to start */
12110 if (cmdp && cmdp->rehash) { /* doing a rehash */
12111 if (cmdp->cmdtype == CMDBUILTIN)
12114 prev = cmdp->param.index;
12120 while ((fullname = path_advance(&path, name)) != NULL) {
12121 stunalloc(fullname);
12122 /* NB: code below will still use fullname
12123 * despite it being "unallocated" */
12126 if (prefix(pathopt, "builtin")) {
12128 goto builtin_success;
12131 if ((act & DO_NOFUNC)
12132 || !prefix(pathopt, "func")
12133 ) { /* ignore unimplemented options */
12137 /* if rehash, don't redo absolute path names */
12138 if (fullname[0] == '/' && idx <= prev) {
12141 TRACE(("searchexec \"%s\": no change\n", name));
12144 while (stat(fullname, &statb) < 0) {
12146 if (errno == EINTR)
12149 if (errno != ENOENT && errno != ENOTDIR)
12153 e = EACCES; /* if we fail, this will be the error */
12154 if (!S_ISREG(statb.st_mode))
12156 if (pathopt) { /* this is a %func directory */
12157 stalloc(strlen(fullname) + 1);
12158 /* NB: stalloc will return space pointed by fullname
12159 * (because we don't have any intervening allocations
12160 * between stunalloc above and this stalloc) */
12161 readcmdfile(fullname);
12162 cmdp = cmdlookup(name, 0);
12163 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12164 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12165 stunalloc(fullname);
12168 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12170 entry->cmdtype = CMDNORMAL;
12171 entry->u.index = idx;
12175 cmdp = cmdlookup(name, 1);
12176 cmdp->cmdtype = CMDNORMAL;
12177 cmdp->param.index = idx;
12182 /* We failed. If there was an entry for this command, delete it */
12183 if (cmdp && updatetbl)
12184 delete_cmd_entry();
12186 ash_msg("%s: %s", name, errmsg(e, "not found"));
12187 entry->cmdtype = CMDUNKNOWN;
12192 entry->cmdtype = CMDBUILTIN;
12193 entry->u.cmd = bcmd;
12197 cmdp = cmdlookup(name, 1);
12198 cmdp->cmdtype = CMDBUILTIN;
12199 cmdp->param.cmd = bcmd;
12203 entry->cmdtype = cmdp->cmdtype;
12204 entry->u = cmdp->param;
12208 /* ============ trap.c */
12211 * The trap builtin.
12213 static int FAST_FUNC
12214 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12223 for (signo = 0; signo < NSIG; signo++) {
12224 char *tr = trap_ptr[signo];
12226 /* note: bash adds "SIG", but only if invoked
12227 * as "bash". If called as "sh", or if set -o posix,
12228 * then it prints short signal names.
12229 * We are printing short names: */
12230 out1fmt("trap -- %s %s\n",
12232 get_signame(signo));
12233 /* trap_ptr != trap only if we are in special-cased `trap` code.
12234 * In this case, we will exit very soon, no need to free(). */
12235 /* if (trap_ptr != trap && tp[0]) */
12240 if (trap_ptr != trap) {
12252 signo = get_signum(*ap);
12254 ash_msg_and_raise_error("%s: bad trap", *ap);
12257 if (LONE_DASH(action))
12260 action = ckstrdup(action);
12263 trap[signo] = action;
12273 /* ============ Builtins */
12275 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12277 * Lists available builtins
12279 static int FAST_FUNC
12280 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12286 "Built-in commands:\n"
12287 "------------------\n");
12288 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12289 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12290 builtintab[i].name + 1);
12296 #if ENABLE_FEATURE_SH_STANDALONE
12298 const char *a = applet_names;
12300 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12305 a += strlen(a) + 1;
12310 return EXIT_SUCCESS;
12312 #endif /* FEATURE_SH_EXTRA_QUIET */
12315 * The export and readonly commands.
12317 static int FAST_FUNC
12318 exportcmd(int argc UNUSED_PARAM, char **argv)
12324 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12326 if (nextopt("p") != 'p') {
12331 p = strchr(name, '=');
12335 vp = *findvar(hashvar(name), name);
12341 setvar(name, p, flag);
12342 } while ((name = *++aptr) != NULL);
12346 showvars(argv[0], flag, 0);
12351 * Delete a function if it exists.
12354 unsetfunc(const char *name)
12356 struct tblentry *cmdp;
12358 cmdp = cmdlookup(name, 0);
12359 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12360 delete_cmd_entry();
12364 * The unset builtin command. We unset the function before we unset the
12365 * variable to allow a function to be unset when there is a readonly variable
12366 * with the same name.
12368 static int FAST_FUNC
12369 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12376 while ((i = nextopt("vf")) != '\0') {
12380 for (ap = argptr; *ap; ap++) {
12396 #include <sys/times.h>
12398 static const unsigned char timescmd_str[] ALIGN1 = {
12399 ' ', offsetof(struct tms, tms_utime),
12400 '\n', offsetof(struct tms, tms_stime),
12401 ' ', offsetof(struct tms, tms_cutime),
12402 '\n', offsetof(struct tms, tms_cstime),
12406 static int FAST_FUNC
12407 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12409 long clk_tck, s, t;
12410 const unsigned char *p;
12413 clk_tck = sysconf(_SC_CLK_TCK);
12418 t = *(clock_t *)(((char *) &buf) + p[1]);
12420 out1fmt("%ldm%ld.%.3lds%c",
12422 ((t - s * clk_tck) * 1000) / clk_tck,
12424 } while (*(p += 2));
12429 #if ENABLE_SH_MATH_SUPPORT
12431 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12432 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12434 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12436 static int FAST_FUNC
12437 letcmd(int argc UNUSED_PARAM, char **argv)
12443 ash_msg_and_raise_error("expression expected");
12445 i = ash_arith(*argv);
12450 #endif /* SH_MATH_SUPPORT */
12453 /* ============ miscbltin.c
12455 * Miscellaneous builtins.
12460 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12461 typedef enum __rlimit_resource rlim_t;
12465 * The read builtin. Options:
12466 * -r Do not interpret '\' specially
12467 * -s Turn off echo (tty only)
12468 * -n NCHARS Read NCHARS max
12469 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12470 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12471 * -u FD Read from given FD instead of fd 0
12472 * This uses unbuffered input, which may be avoidable in some cases.
12473 * TODO: bash also has:
12474 * -a ARRAY Read into array[0],[1],etc
12475 * -d DELIM End on DELIM char, not newline
12476 * -e Use line editing (tty only)
12478 static int FAST_FUNC
12479 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12481 static const char *const arg_REPLY[] = { "REPLY", NULL };
12494 #if ENABLE_ASH_READ_NCHARS
12495 int nchars = 0; /* if != 0, -n is in effect */
12497 struct termios tty, old_tty;
12499 #if ENABLE_ASH_READ_TIMEOUT
12500 unsigned end_ms = 0;
12501 unsigned timeout = 0;
12506 while ((i = nextopt("p:u:r"
12507 IF_ASH_READ_TIMEOUT("t:")
12508 IF_ASH_READ_NCHARS("n:s")
12512 prompt = optionarg;
12514 #if ENABLE_ASH_READ_NCHARS
12516 nchars = bb_strtou(optionarg, NULL, 10);
12517 if (nchars < 0 || errno)
12518 ash_msg_and_raise_error("invalid count");
12519 /* nchars == 0: off (bash 3.2 does this too) */
12525 #if ENABLE_ASH_READ_TIMEOUT
12527 timeout = bb_strtou(optionarg, NULL, 10);
12528 if (errno || timeout > UINT_MAX / 2048)
12529 ash_msg_and_raise_error("invalid timeout");
12531 #if 0 /* even bash have no -t N.NNN support */
12532 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12534 /* EINVAL means number is ok, but not terminated by NUL */
12535 if (*p == '.' && errno == EINVAL) {
12539 ts.tv_usec = bb_strtou(p, &p2, 10);
12541 ash_msg_and_raise_error("invalid timeout");
12543 /* normalize to usec */
12545 ash_msg_and_raise_error("invalid timeout");
12546 while (scale++ < 6)
12549 } else if (ts.tv_sec < 0 || errno) {
12550 ash_msg_and_raise_error("invalid timeout");
12552 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12553 ash_msg_and_raise_error("invalid timeout");
12562 fd = bb_strtou(optionarg, NULL, 10);
12563 if (fd < 0 || errno)
12564 ash_msg_and_raise_error("invalid file descriptor");
12570 if (prompt && isatty(fd)) {
12575 ap = (char**)arg_REPLY;
12576 ifs = bltinlookup("IFS");
12579 #if ENABLE_ASH_READ_NCHARS
12580 tcgetattr(fd, &tty);
12582 if (nchars || silent) {
12584 tty.c_lflag &= ~ICANON;
12585 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12588 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12590 /* if tcgetattr failed, tcsetattr will fail too.
12591 * Ignoring, it's harmless. */
12592 tcsetattr(fd, TCSANOW, &tty);
12599 #if ENABLE_ASH_READ_TIMEOUT
12600 if (timeout) /* NB: ensuring end_ms is nonzero */
12601 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12605 const char *is_ifs;
12607 #if ENABLE_ASH_READ_TIMEOUT
12609 struct pollfd pfd[1];
12611 pfd[0].events = POLLIN;
12612 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12613 if ((int)timeout <= 0 /* already late? */
12614 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12615 ) { /* timed out! */
12616 #if ENABLE_ASH_READ_NCHARS
12617 tcsetattr(fd, TCSANOW, &old_tty);
12623 if (nonblock_safe_read(fd, &c, 1) != 1) {
12635 if (!rflag && c == '\\') {
12641 /* $IFS splitting */
12642 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12643 is_ifs = strchr(ifs, c);
12644 if (startword && is_ifs) {
12647 /* it is a non-space ifs char */
12649 if (startword == 1) /* first one? */
12650 continue; /* yes, it is not next word yet */
12653 if (ap[1] != NULL && is_ifs) {
12656 beg = stackblock();
12657 setvar(*ap, beg, 0);
12659 /* can we skip one non-space ifs char? (2: yes) */
12660 startword = isspace(c) ? 2 : 1;
12667 /* end of do {} while: */
12668 #if ENABLE_ASH_READ_NCHARS
12674 #if ENABLE_ASH_READ_NCHARS
12675 tcsetattr(fd, TCSANOW, &old_tty);
12679 /* Remove trailing space ifs chars */
12680 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12682 setvar(*ap, stackblock(), 0);
12683 while (*++ap != NULL)
12684 setvar(*ap, nullstr, 0);
12688 static int FAST_FUNC
12689 umaskcmd(int argc UNUSED_PARAM, char **argv)
12691 static const char permuser[3] ALIGN1 = "ugo";
12692 static const char permmode[3] ALIGN1 = "rwx";
12693 static const short permmask[] ALIGN2 = {
12694 S_IRUSR, S_IWUSR, S_IXUSR,
12695 S_IRGRP, S_IWGRP, S_IXGRP,
12696 S_IROTH, S_IWOTH, S_IXOTH
12699 /* TODO: use bb_parse_mode() instead */
12704 int symbolic_mode = 0;
12706 while (nextopt("S") != '\0') {
12717 if (symbolic_mode) {
12721 for (i = 0; i < 3; i++) {
12724 *p++ = permuser[i];
12726 for (j = 0; j < 3; j++) {
12727 if ((mask & permmask[3 * i + j]) == 0) {
12728 *p++ = permmode[j];
12736 out1fmt("%.4o\n", mask);
12739 if (isdigit((unsigned char) *ap)) {
12742 if (*ap >= '8' || *ap < '0')
12743 ash_msg_and_raise_error(msg_illnum, argv[1]);
12744 mask = (mask << 3) + (*ap - '0');
12745 } while (*++ap != '\0');
12748 mask = ~mask & 0777;
12749 if (!bb_parse_mode(ap, &mask)) {
12750 ash_msg_and_raise_error("illegal mode: %s", ap);
12752 umask(~mask & 0777);
12761 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12762 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12763 * ash by J.T. Conklin.
12768 uint8_t cmd; /* RLIMIT_xxx fit into it */
12769 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12773 static const struct limits limits_tbl[] = {
12775 { RLIMIT_CPU, 0, 't' },
12777 #ifdef RLIMIT_FSIZE
12778 { RLIMIT_FSIZE, 9, 'f' },
12781 { RLIMIT_DATA, 10, 'd' },
12783 #ifdef RLIMIT_STACK
12784 { RLIMIT_STACK, 10, 's' },
12787 { RLIMIT_CORE, 9, 'c' },
12790 { RLIMIT_RSS, 10, 'm' },
12792 #ifdef RLIMIT_MEMLOCK
12793 { RLIMIT_MEMLOCK, 10, 'l' },
12795 #ifdef RLIMIT_NPROC
12796 { RLIMIT_NPROC, 0, 'p' },
12798 #ifdef RLIMIT_NOFILE
12799 { RLIMIT_NOFILE, 0, 'n' },
12802 { RLIMIT_AS, 10, 'v' },
12804 #ifdef RLIMIT_LOCKS
12805 { RLIMIT_LOCKS, 0, 'w' },
12808 static const char limits_name[] =
12810 "time(seconds)" "\0"
12812 #ifdef RLIMIT_FSIZE
12813 "file(blocks)" "\0"
12818 #ifdef RLIMIT_STACK
12822 "coredump(blocks)" "\0"
12827 #ifdef RLIMIT_MEMLOCK
12828 "locked memory(kb)" "\0"
12830 #ifdef RLIMIT_NPROC
12833 #ifdef RLIMIT_NOFILE
12839 #ifdef RLIMIT_LOCKS
12844 enum limtype { SOFT = 0x1, HARD = 0x2 };
12847 printlim(enum limtype how, const struct rlimit *limit,
12848 const struct limits *l)
12852 val = limit->rlim_max;
12854 val = limit->rlim_cur;
12856 if (val == RLIM_INFINITY)
12857 out1fmt("unlimited\n");
12859 val >>= l->factor_shift;
12860 out1fmt("%lld\n", (long long) val);
12864 static int FAST_FUNC
12865 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12868 enum limtype how = SOFT | HARD;
12869 const struct limits *l;
12872 struct rlimit limit;
12875 while ((optc = nextopt("HSa"
12879 #ifdef RLIMIT_FSIZE
12885 #ifdef RLIMIT_STACK
12894 #ifdef RLIMIT_MEMLOCK
12897 #ifdef RLIMIT_NPROC
12900 #ifdef RLIMIT_NOFILE
12906 #ifdef RLIMIT_LOCKS
12924 for (l = limits_tbl; l->option != what; l++)
12927 set = *argptr ? 1 : 0;
12932 if (all || argptr[1])
12933 ash_msg_and_raise_error("too many arguments");
12934 if (strncmp(p, "unlimited\n", 9) == 0)
12935 val = RLIM_INFINITY;
12937 if (sizeof(val) == sizeof(int))
12938 val = bb_strtou(p, NULL, 10);
12939 else if (sizeof(val) == sizeof(long))
12940 val = bb_strtoul(p, NULL, 10);
12942 val = bb_strtoull(p, NULL, 10);
12944 ash_msg_and_raise_error("bad number");
12945 val <<= l->factor_shift;
12949 const char *lname = limits_name;
12950 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12951 getrlimit(l->cmd, &limit);
12952 out1fmt("%-20s ", lname);
12953 lname += strlen(lname) + 1;
12954 printlim(how, &limit, l);
12959 getrlimit(l->cmd, &limit);
12962 limit.rlim_max = val;
12964 limit.rlim_cur = val;
12965 if (setrlimit(l->cmd, &limit) < 0)
12966 ash_msg_and_raise_error("error setting limit (%m)");
12968 printlim(how, &limit, l);
12973 /* ============ main() and helpers */
12976 * Called to exit the shell.
12978 static void exitshell(void) NORETURN;
12986 status = exitstatus;
12987 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12988 if (setjmp(loc.loc)) {
12989 if (exception_type == EXEXIT)
12990 /* dash bug: it just does _exit(exitstatus) here
12991 * but we have to do setjobctl(0) first!
12992 * (bug is still not fixed in dash-0.5.3 - if you run dash
12993 * under Midnight Commander, on exit from dash MC is backgrounded) */
12994 status = exitstatus;
12997 exception_handler = &loc;
13004 flush_stdout_stderr();
13014 /* from input.c: */
13015 basepf.next_to_pgetc = basepf.buf = basebuf;
13018 signal(SIGCHLD, SIG_DFL);
13024 struct stat st1, st2;
13027 for (envp = environ; envp && *envp; envp++) {
13028 if (strchr(*envp, '=')) {
13029 setvareq(*envp, VEXPORT|VTEXTFIXED);
13033 setvar("PPID", utoa(getppid()), 0);
13035 p = lookupvar("PWD");
13037 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13038 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13045 * Process the shell command line arguments.
13048 procargs(char **argv)
13051 const char *xminusc;
13056 /* if (xargv[0]) - mmm, this is always true! */
13058 for (i = 0; i < NOPTS; i++)
13062 /* it already printed err message */
13063 raise_exception(EXERROR);
13067 if (*xargv == NULL) {
13069 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13072 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13076 for (i = 0; i < NOPTS; i++)
13077 if (optlist[i] == 2)
13082 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13087 } else if (!sflag) {
13088 setinputfile(*xargv, 0);
13091 commandname = arg0;
13094 shellparam.p = xargv;
13095 #if ENABLE_ASH_GETOPTS
13096 shellparam.optind = 1;
13097 shellparam.optoff = -1;
13099 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13101 shellparam.nparam++;
13108 * Read /etc/profile or .profile.
13111 read_profile(const char *name)
13115 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13124 * This routine is called when an error or an interrupt occurs in an
13125 * interactive shell and control is returned to the main command loop.
13133 /* from input.c: */
13134 g_parsefile->left_in_buffer = 0;
13135 g_parsefile->left_in_line = 0; /* clear input buffer */
13137 /* from parser.c: */
13140 /* from redir.c: */
13141 clearredir(/*drop:*/ 0);
13145 static short profile_buf[16384];
13146 extern int etext();
13150 * Main routine. We initialize things, parse the arguments, execute
13151 * profiles if we're a login shell, and then call cmdloop to execute
13152 * commands. The setjmp call sets up the location to jump to when an
13153 * exception occurs. When an exception occurs the variable "state"
13154 * is used to figure out how far we had gotten.
13156 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13157 int ash_main(int argc UNUSED_PARAM, char **argv)
13159 const char *shinit;
13160 volatile smallint state;
13161 struct jmploc jmploc;
13162 struct stackmark smark;
13164 /* Initialize global data */
13168 #if ENABLE_ASH_ALIAS
13174 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13177 #if ENABLE_FEATURE_EDITING
13178 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13181 if (setjmp(jmploc.loc)) {
13187 e = exception_type;
13191 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13194 outcslow('\n', stderr);
13196 popstackmark(&smark);
13197 FORCE_INT_ON; /* enable interrupts */
13206 exception_handler = &jmploc;
13209 TRACE(("Shell args: "));
13210 trace_puts_args(argv);
13212 rootpid = getpid();
13215 setstackmark(&smark);
13218 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13220 const char *hp = lookupvar("HISTFILE");
13223 hp = lookupvar("HOME");
13225 char *defhp = concat_path_file(hp, ".ash_history");
13226 setvar("HISTFILE", defhp, 0);
13232 if (/* argv[0] && */ argv[0][0] == '-')
13236 read_profile("/etc/profile");
13239 read_profile(".profile");
13245 getuid() == geteuid() && getgid() == getegid() &&
13249 shinit = lookupvar("ENV");
13250 if (shinit != NULL && *shinit != '\0') {
13251 read_profile(shinit);
13257 /* evalstring pushes parsefile stack.
13258 * Ensure we don't falsely claim that 0 (stdin)
13259 * is one of stacked source fds.
13260 * Testcase: ash -c 'exec 1>&0' must not complain. */
13262 g_parsefile->fd = -1;
13263 evalstring(minusc, 0);
13266 if (sflag || minusc == NULL) {
13267 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13269 const char *hp = lookupvar("HISTFILE");
13271 line_input_state->hist_file = hp;
13274 state4: /* XXX ??? - why isn't this before the "if" statement */
13282 extern void _mcleanup(void);
13292 * Copyright (c) 1989, 1991, 1993, 1994
13293 * The Regents of the University of California. All rights reserved.
13295 * This code is derived from software contributed to Berkeley by
13296 * Kenneth Almquist.
13298 * Redistribution and use in source and binary forms, with or without
13299 * modification, are permitted provided that the following conditions
13301 * 1. Redistributions of source code must retain the above copyright
13302 * notice, this list of conditions and the following disclaimer.
13303 * 2. Redistributions in binary form must reproduce the above copyright
13304 * notice, this list of conditions and the following disclaimer in the
13305 * documentation and/or other materials provided with the distribution.
13306 * 3. Neither the name of the University nor the names of its contributors
13307 * may be used to endorse or promote products derived from this software
13308 * without specific prior written permission.
13310 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13311 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13312 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13313 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13314 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13315 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13316 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13317 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13318 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13319 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF