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[] = {
104 #if ENABLE_ASH_BASH_COMPAT
113 #define optletters(n) optletters_optnames[n][0]
114 #define optnames(n) (optletters_optnames[n] + 1)
116 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
119 /* ============ Misc data */
121 static const char homestr[] ALIGN1 = "HOME";
122 static const char snlfmt[] ALIGN1 = "%s\n";
123 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
126 * We enclose jmp_buf in a structure so that we can declare pointers to
127 * jump locations. The global variable handler contains the location to
128 * jump to when an exception occurs, and the global variable exception_type
129 * contains a code identifying the exception. To implement nested
130 * exception handlers, the user should save the value of handler on entry
131 * to an inner scope, set handler to point to a jmploc structure for the
132 * inner scope, and restore handler on exit from the scope.
138 struct globals_misc {
139 /* pid of main shell */
141 /* shell level: 0 for the main shell, 1 for its children, and so on */
143 #define rootshell (!shlvl)
144 char *minusc; /* argument to -c option */
146 char *curdir; // = nullstr; /* current working directory */
147 char *physdir; // = nullstr; /* physical working directory */
149 char *arg0; /* value of $0 */
151 struct jmploc *exception_handler;
153 volatile int suppress_int; /* counter */
154 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
155 /* last pending signal */
156 volatile /*sig_atomic_t*/ smallint pending_sig;
157 smallint exception_type; /* kind of exception (0..5) */
159 #define EXINT 0 /* SIGINT received */
160 #define EXERROR 1 /* a generic error */
161 #define EXSHELLPROC 2 /* execute a shell procedure */
162 #define EXEXEC 3 /* command execution failed */
163 #define EXEXIT 4 /* exit the shell */
164 #define EXSIG 5 /* trapped signal in wait(1) */
167 char nullstr[1]; /* zero length string */
170 #define eflag optlist[0]
171 #define fflag optlist[1]
172 #define Iflag optlist[2]
173 #define iflag optlist[3]
174 #define mflag optlist[4]
175 #define nflag optlist[5]
176 #define sflag optlist[6]
177 #define xflag optlist[7]
178 #define vflag optlist[8]
179 #define Cflag optlist[9]
180 #define aflag optlist[10]
181 #define bflag optlist[11]
182 #define uflag optlist[12]
183 #define viflag optlist[13]
184 #if ENABLE_ASH_BASH_COMPAT
185 # define pipefail optlist[14]
190 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
191 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
194 /* trap handler commands */
196 * Sigmode records the current value of the signal handlers for the various
197 * modes. A value of zero means that the current handler is not known.
198 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
200 char sigmode[NSIG - 1];
201 #define S_DFL 1 /* default signal handling (SIG_DFL) */
202 #define S_CATCH 2 /* signal is caught */
203 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
204 #define S_HARD_IGN 4 /* signal is ignored permenantly */
206 /* indicates specified signal received */
207 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
209 char **trap_ptr; /* used only by "trap hack" */
211 /* Rarely referenced stuff */
212 #if ENABLE_ASH_RANDOM_SUPPORT
215 pid_t backgndpid; /* pid of last background process */
216 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
218 extern struct globals_misc *const ash_ptr_to_globals_misc;
219 #define G_misc (*ash_ptr_to_globals_misc)
220 #define rootpid (G_misc.rootpid )
221 #define shlvl (G_misc.shlvl )
222 #define minusc (G_misc.minusc )
223 #define curdir (G_misc.curdir )
224 #define physdir (G_misc.physdir )
225 #define arg0 (G_misc.arg0 )
226 #define exception_handler (G_misc.exception_handler)
227 #define exception_type (G_misc.exception_type )
228 #define suppress_int (G_misc.suppress_int )
229 #define pending_int (G_misc.pending_int )
230 #define pending_sig (G_misc.pending_sig )
231 #define isloginsh (G_misc.isloginsh )
232 #define nullstr (G_misc.nullstr )
233 #define optlist (G_misc.optlist )
234 #define sigmode (G_misc.sigmode )
235 #define gotsig (G_misc.gotsig )
236 #define trap (G_misc.trap )
237 #define trap_ptr (G_misc.trap_ptr )
238 #define random_gen (G_misc.random_gen )
239 #define backgndpid (G_misc.backgndpid )
240 #define job_warning (G_misc.job_warning)
241 #define INIT_G_misc() do { \
242 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
250 /* ============ DEBUG */
252 static void trace_printf(const char *fmt, ...);
253 static void trace_vprintf(const char *fmt, va_list va);
254 # define TRACE(param) trace_printf param
255 # define TRACEV(param) trace_vprintf param
256 # define close(fd) do { \
258 if (close(dfd) < 0) \
259 bb_error_msg("bug on %d: closing %d(0x%x)", \
260 __LINE__, dfd, dfd); \
263 # define TRACE(param)
264 # define TRACEV(param)
268 /* ============ Utility functions */
269 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
271 static int isdigit_str9(const char *str)
273 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
274 while (--maxlen && isdigit(*str))
276 return (*str == '\0');
280 /* ============ Interrupts / exceptions */
282 * These macros allow the user to suspend the handling of interrupt signals
283 * over a period of time. This is similar to SIGHOLD or to sigblock, but
284 * much more efficient and portable. (But hacking the kernel is so much
285 * more fun than worrying about efficiency and portability. :-))
287 #define INT_OFF do { \
293 * Called to raise an exception. Since C doesn't include exceptions, we
294 * just do a longjmp to the exception handler. The type of exception is
295 * stored in the global variable "exception_type".
297 static void raise_exception(int) NORETURN;
299 raise_exception(int e)
302 if (exception_handler == NULL)
307 longjmp(exception_handler->loc, 1);
310 #define raise_exception(e) do { \
311 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
312 raise_exception(e); \
317 * Called from trap.c when a SIGINT is received. (If the user specifies
318 * that SIGINT is to be trapped or ignored using the trap builtin, then
319 * this routine is not called.) Suppressint is nonzero when interrupts
320 * are held using the INT_OFF macro. (The test for iflag is just
321 * defensive programming.)
323 static void raise_interrupt(void) NORETURN;
325 raise_interrupt(void)
330 /* Signal is not automatically unmasked after it is raised,
331 * do it ourself - unmask all signals */
332 sigprocmask_allsigs(SIG_UNBLOCK);
333 /* pending_sig = 0; - now done in onsig() */
336 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
337 if (!(rootshell && iflag)) {
338 /* Kill ourself with SIGINT */
339 signal(SIGINT, SIG_DFL);
344 raise_exception(ex_type);
348 #define raise_interrupt() do { \
349 TRACE(("raising interrupt on line %d\n", __LINE__)); \
354 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
358 if (--suppress_int == 0 && pending_int) {
362 #define INT_ON int_on()
363 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
371 #define FORCE_INT_ON force_int_on()
373 #define SAVE_INT(v) ((v) = suppress_int)
375 #define RESTORE_INT(v) do { \
377 suppress_int = (v); \
378 if (suppress_int == 0 && pending_int) \
383 /* ============ Stdout/stderr output */
386 outstr(const char *p, FILE *file)
394 flush_stdout_stderr(void)
402 outcslow(int c, FILE *dest)
410 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
412 out1fmt(const char *fmt, ...)
419 r = vprintf(fmt, ap);
425 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
427 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
434 ret = vsnprintf(outbuf, length, fmt, ap);
441 out1str(const char *p)
447 out2str(const char *p)
450 flush_stdout_stderr();
454 /* ============ Parser structures */
456 /* control characters in argument strings */
457 #define CTL_FIRST CTLESC
458 #define CTLESC ((unsigned char)'\201') /* escape next character */
459 #define CTLVAR ((unsigned char)'\202') /* variable defn */
460 #define CTLENDVAR ((unsigned char)'\203')
461 #define CTLBACKQ ((unsigned char)'\204')
462 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
463 /* CTLBACKQ | CTLQUOTE == '\205' */
464 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
465 #define CTLENDARI ((unsigned char)'\207')
466 #define CTLQUOTEMARK ((unsigned char)'\210')
467 #define CTL_LAST CTLQUOTEMARK
469 /* variable substitution byte (follows CTLVAR) */
470 #define VSTYPE 0x0f /* type of variable substitution */
471 #define VSNUL 0x10 /* colon--treat the empty string as unset */
472 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
474 /* values of VSTYPE field */
475 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
476 #define VSMINUS 0x2 /* ${var-text} */
477 #define VSPLUS 0x3 /* ${var+text} */
478 #define VSQUESTION 0x4 /* ${var?message} */
479 #define VSASSIGN 0x5 /* ${var=text} */
480 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
481 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
482 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
483 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
484 #define VSLENGTH 0xa /* ${#var} */
485 #if ENABLE_ASH_BASH_COMPAT
486 #define VSSUBSTR 0xc /* ${var:position:length} */
487 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
488 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491 static const char dolatstr[] ALIGN1 = {
492 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
512 #if ENABLE_ASH_BASH_COMPAT
529 smallint type; /* Nxxxx */
532 union node *redirect;
537 smallint pipe_backgnd;
538 struct nodelist *cmdlist;
544 union node *redirect;
557 union node *elsepart;
584 struct nodelist *backquote;
587 /* nfile and ndup layout must match!
588 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
589 * that it is actually NTO2 (>&file), and change its type.
606 char *_unused_expfname;
625 struct nredir nredir;
626 struct nbinary nbinary;
630 struct nclist nclist;
639 * NODE_EOF is returned by parsecmd when it encounters an end of file.
640 * It must be distinct from NULL.
642 #define NODE_EOF ((union node *) -1L)
645 struct nodelist *next;
658 freefunc(struct funcnode *f)
660 if (f && --f->count < 0)
665 /* ============ Debugging output */
669 static FILE *tracefile;
672 trace_printf(const char *fmt, ...)
679 fprintf(tracefile, "%u ", (int) time(NULL));
681 fprintf(tracefile, "[%u] ", (int) getpid());
683 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
685 vfprintf(tracefile, fmt, va);
690 trace_vprintf(const char *fmt, va_list va)
695 fprintf(tracefile, "%u ", (int) time(NULL));
697 fprintf(tracefile, "[%u] ", (int) getpid());
699 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
700 vfprintf(tracefile, fmt, va);
704 trace_puts(const char *s)
712 trace_puts_quoted(char *s)
719 putc('"', tracefile);
720 for (p = s; *p; p++) {
721 switch ((unsigned char)*p) {
722 case '\n': c = 'n'; goto backslash;
723 case '\t': c = 't'; goto backslash;
724 case '\r': c = 'r'; goto backslash;
725 case '\"': c = '\"'; goto backslash;
726 case '\\': c = '\\'; goto backslash;
727 case CTLESC: c = 'e'; goto backslash;
728 case CTLVAR: c = 'v'; goto backslash;
729 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
730 case CTLBACKQ: c = 'q'; goto backslash;
731 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
733 putc('\\', tracefile);
737 if (*p >= ' ' && *p <= '~')
740 putc('\\', tracefile);
741 putc((*p >> 6) & 03, tracefile);
742 putc((*p >> 3) & 07, tracefile);
743 putc(*p & 07, tracefile);
748 putc('"', tracefile);
752 trace_puts_args(char **ap)
759 trace_puts_quoted(*ap);
761 putc('\n', tracefile);
764 putc(' ', tracefile);
779 /* leave open because libedit might be using it */
782 strcpy(s, "./trace");
784 if (!freopen(s, "a", tracefile)) {
785 fprintf(stderr, "Can't re-open %s\n", s);
790 tracefile = fopen(s, "a");
791 if (tracefile == NULL) {
792 fprintf(stderr, "Can't open %s\n", s);
798 flags = fcntl(fileno(tracefile), F_GETFL);
800 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
802 setlinebuf(tracefile);
803 fputs("\nTracing started.\n", tracefile);
807 indent(int amount, char *pfx, FILE *fp)
811 for (i = 0; i < amount; i++) {
812 if (pfx && i == amount - 1)
818 /* little circular references here... */
819 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822 sharg(union node *arg, FILE *fp)
825 struct nodelist *bqlist;
826 unsigned char subtype;
828 if (arg->type != NARG) {
829 out1fmt("<node type %d>\n", arg->type);
832 bqlist = arg->narg.backquote;
833 for (p = arg->narg.text; *p; p++) {
834 switch ((unsigned char)*p) {
842 if (subtype == VSLENGTH)
851 switch (subtype & VSTYPE) {
884 out1fmt("<subtype %d>", subtype);
891 case CTLBACKQ|CTLQUOTE:
894 shtree(bqlist->n, -1, NULL, fp);
905 shcmd(union node *cmd, FILE *fp)
913 for (np = cmd->ncmd.args; np; np = np->narg.next) {
919 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
923 switch (np->nfile.type) {
924 case NTO: s = ">>"+1; dftfd = 1; break;
925 case NCLOBBER: s = ">|"; dftfd = 1; break;
926 case NAPPEND: s = ">>"; dftfd = 1; break;
927 #if ENABLE_ASH_BASH_COMPAT
930 case NTOFD: s = ">&"; dftfd = 1; break;
931 case NFROM: s = "<"; break;
932 case NFROMFD: s = "<&"; break;
933 case NFROMTO: s = "<>"; break;
934 default: s = "*error*"; break;
936 if (np->nfile.fd != dftfd)
937 fprintf(fp, "%d", np->nfile.fd);
939 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
940 fprintf(fp, "%d", np->ndup.dupfd);
942 sharg(np->nfile.fname, fp);
949 shtree(union node *n, int ind, char *pfx, FILE *fp)
957 indent(ind, pfx, fp);
974 shtree(n->nbinary.ch1, ind, NULL, fp);
977 shtree(n->nbinary.ch2, ind, NULL, fp);
985 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
986 shtree(lp->n, 0, NULL, fp);
990 if (n->npipe.pipe_backgnd)
996 fprintf(fp, "<node type %d>", n->type);
1004 showtree(union node *n)
1006 trace_puts("showtree called\n");
1007 shtree(n, 1, NULL, stderr);
1013 /* ============ Parser data */
1016 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 struct strlist *next;
1026 struct strpush *prev; /* preceding string on stack */
1028 int prev_left_in_line;
1029 #if ENABLE_ASH_ALIAS
1030 struct alias *ap; /* if push was associated with an alias */
1032 char *string; /* remember the string since it may change */
1036 struct parsefile *prev; /* preceding file on stack */
1037 int linno; /* current line */
1038 int fd; /* file descriptor (or -1 if string) */
1039 int left_in_line; /* number of chars left in this line */
1040 int left_in_buffer; /* number of chars left in this buffer past the line */
1041 char *next_to_pgetc; /* next char in buffer */
1042 char *buf; /* input buffer */
1043 struct strpush *strpush; /* for pushing strings at this level */
1044 struct strpush basestrpush; /* so pushing one is fast */
1047 static struct parsefile basepf; /* top level input file */
1048 static struct parsefile *g_parsefile = &basepf; /* current input file */
1049 static int startlinno; /* line # where last token started */
1050 static char *commandname; /* currently executing command */
1051 static struct strlist *cmdenviron; /* environment for builtin command */
1052 static uint8_t exitstatus; /* exit status of last command */
1055 /* ============ Message printing */
1058 ash_vmsg(const char *msg, va_list ap)
1060 fprintf(stderr, "%s: ", arg0);
1062 if (strcmp(arg0, commandname))
1063 fprintf(stderr, "%s: ", commandname);
1064 if (!iflag || g_parsefile->fd)
1065 fprintf(stderr, "line %d: ", startlinno);
1067 vfprintf(stderr, msg, ap);
1068 outcslow('\n', stderr);
1072 * Exverror is called to raise the error exception. If the second argument
1073 * is not NULL then error prints an error message using printf style
1074 * formatting. It then raises the error exception.
1076 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1078 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1082 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1084 TRACE(("\") pid=%d\n", getpid()));
1086 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1091 flush_stdout_stderr();
1092 raise_exception(cond);
1096 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1098 ash_msg_and_raise_error(const char *msg, ...)
1103 ash_vmsg_and_raise(EXERROR, msg, ap);
1108 static void raise_error_syntax(const char *) NORETURN;
1110 raise_error_syntax(const char *msg)
1112 ash_msg_and_raise_error("syntax error: %s", msg);
1116 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1118 ash_msg_and_raise(int cond, const char *msg, ...)
1123 ash_vmsg_and_raise(cond, msg, ap);
1129 * error/warning routines for external builtins
1132 ash_msg(const char *fmt, ...)
1142 * Return a string describing an error. The returned string may be a
1143 * pointer to a static buffer that will be overwritten on the next call.
1144 * Action describes the operation that got the error.
1147 errmsg(int e, const char *em)
1149 if (e == ENOENT || e == ENOTDIR) {
1156 /* ============ Memory allocation */
1159 /* I consider these wrappers nearly useless:
1160 * ok, they return you to nearest exception handler, but
1161 * how much memory do you leak in the process, making
1162 * memory starvation worse?
1165 ckrealloc(void * p, size_t nbytes)
1167 p = realloc(p, nbytes);
1169 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1174 ckmalloc(size_t nbytes)
1176 return ckrealloc(NULL, nbytes);
1180 ckzalloc(size_t nbytes)
1182 return memset(ckmalloc(nbytes), 0, nbytes);
1186 ckstrdup(const char *s)
1188 char *p = strdup(s);
1190 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1194 /* Using bbox equivalents. They exit if out of memory */
1195 # define ckrealloc xrealloc
1196 # define ckmalloc xmalloc
1197 # define ckzalloc xzalloc
1198 # define ckstrdup xstrdup
1202 * It appears that grabstackstr() will barf with such alignments
1203 * because stalloc() will return a string allocated in a new stackblock.
1205 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1207 /* Most machines require the value returned from malloc to be aligned
1208 * in some way. The following macro will get this right
1209 * on many machines. */
1210 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1211 /* Minimum size of a block */
1212 MINSIZE = SHELL_ALIGN(504),
1215 struct stack_block {
1216 struct stack_block *prev;
1217 char space[MINSIZE];
1221 struct stack_block *stackp;
1224 struct stackmark *marknext;
1228 struct globals_memstack {
1229 struct stack_block *g_stackp; // = &stackbase;
1230 struct stackmark *markp;
1231 char *g_stacknxt; // = stackbase.space;
1232 char *sstrend; // = stackbase.space + MINSIZE;
1233 size_t g_stacknleft; // = MINSIZE;
1234 int herefd; // = -1;
1235 struct stack_block stackbase;
1237 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1238 #define G_memstack (*ash_ptr_to_globals_memstack)
1239 #define g_stackp (G_memstack.g_stackp )
1240 #define markp (G_memstack.markp )
1241 #define g_stacknxt (G_memstack.g_stacknxt )
1242 #define sstrend (G_memstack.sstrend )
1243 #define g_stacknleft (G_memstack.g_stacknleft)
1244 #define herefd (G_memstack.herefd )
1245 #define stackbase (G_memstack.stackbase )
1246 #define INIT_G_memstack() do { \
1247 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1249 g_stackp = &stackbase; \
1250 g_stacknxt = stackbase.space; \
1251 g_stacknleft = MINSIZE; \
1252 sstrend = stackbase.space + MINSIZE; \
1257 #define stackblock() ((void *)g_stacknxt)
1258 #define stackblocksize() g_stacknleft
1261 * Parse trees for commands are allocated in lifo order, so we use a stack
1262 * to make this more efficient, and also to avoid all sorts of exception
1263 * handling code to handle interrupts in the middle of a parse.
1265 * The size 504 was chosen because the Ultrix malloc handles that size
1269 stalloc(size_t nbytes)
1274 aligned = SHELL_ALIGN(nbytes);
1275 if (aligned > g_stacknleft) {
1278 struct stack_block *sp;
1280 blocksize = aligned;
1281 if (blocksize < MINSIZE)
1282 blocksize = MINSIZE;
1283 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1284 if (len < blocksize)
1285 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1288 sp->prev = g_stackp;
1289 g_stacknxt = sp->space;
1290 g_stacknleft = blocksize;
1291 sstrend = g_stacknxt + blocksize;
1296 g_stacknxt += aligned;
1297 g_stacknleft -= aligned;
1302 stzalloc(size_t nbytes)
1304 return memset(stalloc(nbytes), 0, nbytes);
1311 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1312 write(STDERR_FILENO, "stunalloc\n", 10);
1316 g_stacknleft += g_stacknxt - (char *)p;
1321 * Like strdup but works with the ash stack.
1324 ststrdup(const char *p)
1326 size_t len = strlen(p) + 1;
1327 return memcpy(stalloc(len), p, len);
1331 setstackmark(struct stackmark *mark)
1333 mark->stackp = g_stackp;
1334 mark->stacknxt = g_stacknxt;
1335 mark->stacknleft = g_stacknleft;
1336 mark->marknext = markp;
1341 popstackmark(struct stackmark *mark)
1343 struct stack_block *sp;
1349 markp = mark->marknext;
1350 while (g_stackp != mark->stackp) {
1352 g_stackp = sp->prev;
1355 g_stacknxt = mark->stacknxt;
1356 g_stacknleft = mark->stacknleft;
1357 sstrend = mark->stacknxt + mark->stacknleft;
1362 * When the parser reads in a string, it wants to stick the string on the
1363 * stack and only adjust the stack pointer when it knows how big the
1364 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1365 * of space on top of the stack and stackblocklen returns the length of
1366 * this block. Growstackblock will grow this space by at least one byte,
1367 * possibly moving it (like realloc). Grabstackblock actually allocates the
1368 * part of the block that has been used.
1371 growstackblock(void)
1375 newlen = g_stacknleft * 2;
1376 if (newlen < g_stacknleft)
1377 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1381 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1382 struct stack_block *oldstackp;
1383 struct stackmark *xmark;
1384 struct stack_block *sp;
1385 struct stack_block *prevstackp;
1389 oldstackp = g_stackp;
1391 prevstackp = sp->prev;
1392 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1393 sp = ckrealloc(sp, grosslen);
1394 sp->prev = prevstackp;
1396 g_stacknxt = sp->space;
1397 g_stacknleft = newlen;
1398 sstrend = sp->space + newlen;
1401 * Stack marks pointing to the start of the old block
1402 * must be relocated to point to the new block
1405 while (xmark != NULL && xmark->stackp == oldstackp) {
1406 xmark->stackp = g_stackp;
1407 xmark->stacknxt = g_stacknxt;
1408 xmark->stacknleft = g_stacknleft;
1409 xmark = xmark->marknext;
1413 char *oldspace = g_stacknxt;
1414 size_t oldlen = g_stacknleft;
1415 char *p = stalloc(newlen);
1417 /* free the space we just allocated */
1418 g_stacknxt = memcpy(p, oldspace, oldlen);
1419 g_stacknleft += newlen;
1424 grabstackblock(size_t len)
1426 len = SHELL_ALIGN(len);
1428 g_stacknleft -= len;
1432 * The following routines are somewhat easier to use than the above.
1433 * The user declares a variable of type STACKSTR, which may be declared
1434 * to be a register. The macro STARTSTACKSTR initializes things. Then
1435 * the user uses the macro STPUTC to add characters to the string. In
1436 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1437 * grown as necessary. When the user is done, she can just leave the
1438 * string there and refer to it using stackblock(). Or she can allocate
1439 * the space for it using grabstackstr(). If it is necessary to allow
1440 * someone else to use the stack temporarily and then continue to grow
1441 * the string, the user should use grabstack to allocate the space, and
1442 * then call ungrabstr(p) to return to the previous mode of operation.
1444 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1445 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1446 * is space for at least one character.
1451 size_t len = stackblocksize();
1452 if (herefd >= 0 && len >= 1024) {
1453 full_write(herefd, stackblock(), len);
1454 return stackblock();
1457 return (char *)stackblock() + len;
1461 * Called from CHECKSTRSPACE.
1464 makestrspace(size_t newlen, char *p)
1466 size_t len = p - g_stacknxt;
1467 size_t size = stackblocksize();
1472 size = stackblocksize();
1474 if (nleft >= newlen)
1478 return (char *)stackblock() + len;
1482 stack_nputstr(const char *s, size_t n, char *p)
1484 p = makestrspace(n, p);
1485 p = (char *)memcpy(p, s, n) + n;
1490 stack_putstr(const char *s, char *p)
1492 return stack_nputstr(s, strlen(s), p);
1496 _STPUTC(int c, char *p)
1504 #define STARTSTACKSTR(p) ((p) = stackblock())
1505 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1506 #define CHECKSTRSPACE(n, p) do { \
1509 size_t m = sstrend - q; \
1511 (p) = makestrspace(l, q); \
1513 #define USTPUTC(c, p) (*(p)++ = (c))
1514 #define STACKSTRNUL(p) do { \
1515 if ((p) == sstrend) \
1516 (p) = growstackstr(); \
1519 #define STUNPUTC(p) (--(p))
1520 #define STTOPC(p) ((p)[-1])
1521 #define STADJUST(amount, p) ((p) += (amount))
1523 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1524 #define ungrabstackstr(s, p) stunalloc(s)
1525 #define stackstrend() ((void *)sstrend)
1528 /* ============ String helpers */
1531 * prefix -- see if pfx is a prefix of string.
1534 prefix(const char *string, const char *pfx)
1537 if (*pfx++ != *string++)
1540 return (char *) string;
1544 * Check for a valid number. This should be elsewhere.
1547 is_number(const char *p)
1552 } while (*++p != '\0');
1557 * Convert a string of digits to an integer, printing an error message on
1561 number(const char *s)
1564 ash_msg_and_raise_error(msg_illnum, s);
1569 * Produce a possibly single quoted string suitable as input to the shell.
1570 * The return string is allocated on the stack.
1573 single_quote(const char *s)
1583 len = strchrnul(s, '\'') - s;
1585 q = p = makestrspace(len + 3, p);
1588 q = (char *)memcpy(q, s, len) + len;
1597 do len++; while (*++s == '\'');
1599 q = p = makestrspace(len + 3, p);
1602 q = (char *)memcpy(q, s - len, len) + len;
1610 return stackblock();
1614 /* ============ nextopt */
1616 static char **argptr; /* argument list for builtin commands */
1617 static char *optionarg; /* set by nextopt (like getopt) */
1618 static char *optptr; /* used by nextopt */
1621 * XXX - should get rid of. Have all builtins use getopt(3).
1622 * The library getopt must have the BSD extension static variable
1623 * "optreset", otherwise it can't be used within the shell safely.
1625 * Standard option processing (a la getopt) for builtin routines.
1626 * The only argument that is passed to nextopt is the option string;
1627 * the other arguments are unnecessary. It returns the character,
1628 * or '\0' on end of input.
1631 nextopt(const char *optstring)
1638 if (p == NULL || *p == '\0') {
1639 /* We ate entire "-param", take next one */
1645 if (*++p == '\0') /* just "-" ? */
1648 if (LONE_DASH(p)) /* "--" ? */
1650 /* p => next "-param" */
1652 /* p => some option char in the middle of a "-param" */
1654 for (q = optstring; *q != c;) {
1656 ash_msg_and_raise_error("illegal option -%c", c);
1664 ash_msg_and_raise_error("no arg for -%c option", c);
1674 /* ============ Shell variables */
1677 * The parsefile structure pointed to by the global variable parsefile
1678 * contains information about the current file being read.
1681 int nparam; /* # of positional parameters (without $0) */
1682 #if ENABLE_ASH_GETOPTS
1683 int optind; /* next parameter to be processed by getopts */
1684 int optoff; /* used by getopts */
1686 unsigned char malloced; /* if parameter list dynamically allocated */
1687 char **p; /* parameter list */
1691 * Free the list of positional parameters.
1694 freeparam(volatile struct shparam *param)
1696 if (param->malloced) {
1698 ap = ap1 = param->p;
1705 #if ENABLE_ASH_GETOPTS
1706 static void FAST_FUNC getoptsreset(const char *value);
1710 struct var *next; /* next entry in hash list */
1711 int flags; /* flags are defined above */
1712 const char *text; /* name=value */
1713 void (*func)(const char *) FAST_FUNC; /* function to be called when */
1714 /* the variable gets set/unset */
1718 struct localvar *next; /* next local variable in list */
1719 struct var *vp; /* the variable that was made local */
1720 int flags; /* saved flags */
1721 const char *text; /* saved text */
1725 #define VEXPORT 0x01 /* variable is exported */
1726 #define VREADONLY 0x02 /* variable cannot be modified */
1727 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1728 #define VTEXTFIXED 0x08 /* text is statically allocated */
1729 #define VSTACK 0x10 /* text is allocated on the stack */
1730 #define VUNSET 0x20 /* the variable is not set */
1731 #define VNOFUNC 0x40 /* don't call the callback function */
1732 #define VNOSET 0x80 /* do not set variable - just readonly test */
1733 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1734 #if ENABLE_ASH_RANDOM_SUPPORT
1735 # define VDYNAMIC 0x200 /* dynamic variable */
1741 static const char defifsvar[] ALIGN1 = "IFS= \t\n";
1742 #define defifs (defifsvar + 4)
1744 static const char defifs[] ALIGN1 = " \t\n";
1748 /* Need to be before varinit_data[] */
1749 #if ENABLE_LOCALE_SUPPORT
1750 static void FAST_FUNC
1751 change_lc_all(const char *value)
1753 if (value && *value != '\0')
1754 setlocale(LC_ALL, value);
1756 static void FAST_FUNC
1757 change_lc_ctype(const char *value)
1759 if (value && *value != '\0')
1760 setlocale(LC_CTYPE, value);
1764 static void chkmail(void);
1765 static void changemail(const char *) FAST_FUNC;
1767 static void changepath(const char *) FAST_FUNC;
1768 #if ENABLE_ASH_RANDOM_SUPPORT
1769 static void change_random(const char *) FAST_FUNC;
1772 static const struct {
1775 void (*func)(const char *) FAST_FUNC;
1776 } varinit_data[] = {
1778 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1780 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
1783 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1784 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1786 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1787 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1788 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1789 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1790 #if ENABLE_ASH_GETOPTS
1791 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1793 #if ENABLE_ASH_RANDOM_SUPPORT
1794 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
1796 #if ENABLE_LOCALE_SUPPORT
1797 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1798 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
1800 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1801 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
1807 struct globals_var {
1808 struct shparam shellparam; /* $@ current positional parameters */
1809 struct redirtab *redirlist;
1811 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1812 struct var *vartab[VTABSIZE];
1813 struct var varinit[ARRAY_SIZE(varinit_data)];
1815 extern struct globals_var *const ash_ptr_to_globals_var;
1816 #define G_var (*ash_ptr_to_globals_var)
1817 #define shellparam (G_var.shellparam )
1818 //#define redirlist (G_var.redirlist )
1819 #define g_nullredirs (G_var.g_nullredirs )
1820 #define preverrout_fd (G_var.preverrout_fd)
1821 #define vartab (G_var.vartab )
1822 #define varinit (G_var.varinit )
1823 #define INIT_G_var() do { \
1825 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1827 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1828 varinit[i].flags = varinit_data[i].flags; \
1829 varinit[i].text = varinit_data[i].text; \
1830 varinit[i].func = varinit_data[i].func; \
1834 #define vifs varinit[0]
1836 # define vmail (&vifs)[1]
1837 # define vmpath (&vmail)[1]
1838 # define vpath (&vmpath)[1]
1840 # define vpath (&vifs)[1]
1842 #define vps1 (&vpath)[1]
1843 #define vps2 (&vps1)[1]
1844 #define vps4 (&vps2)[1]
1845 #if ENABLE_ASH_GETOPTS
1846 # define voptind (&vps4)[1]
1847 # if ENABLE_ASH_RANDOM_SUPPORT
1848 # define vrandom (&voptind)[1]
1851 # if ENABLE_ASH_RANDOM_SUPPORT
1852 # define vrandom (&vps4)[1]
1857 * The following macros access the values of the above variables.
1858 * They have to skip over the name. They return the null string
1859 * for unset variables.
1861 #define ifsval() (vifs.text + 4)
1862 #define ifsset() ((vifs.flags & VUNSET) == 0)
1864 # define mailval() (vmail.text + 5)
1865 # define mpathval() (vmpath.text + 9)
1866 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1868 #define pathval() (vpath.text + 5)
1869 #define ps1val() (vps1.text + 4)
1870 #define ps2val() (vps2.text + 4)
1871 #define ps4val() (vps4.text + 4)
1872 #if ENABLE_ASH_GETOPTS
1873 # define optindval() (voptind.text + 7)
1877 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1878 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1880 #if ENABLE_ASH_GETOPTS
1881 static void FAST_FUNC
1882 getoptsreset(const char *value)
1884 shellparam.optind = number(value);
1885 shellparam.optoff = -1;
1890 * Return of a legal variable name (a letter or underscore followed by zero or
1891 * more letters, underscores, and digits).
1894 endofname(const char *name)
1902 if (!is_in_name(*p))
1909 * Compares two strings up to the first = or '\0'. The first
1910 * string must be terminated by '='; the second may be terminated by
1911 * either '=' or '\0'.
1914 varcmp(const char *p, const char *q)
1918 while ((c = *p) == (d = *q)) {
1933 varequal(const char *a, const char *b)
1935 return !varcmp(a, b);
1939 * Find the appropriate entry in the hash table from the name.
1941 static struct var **
1942 hashvar(const char *p)
1946 hashval = ((unsigned char) *p) << 4;
1947 while (*p && *p != '=')
1948 hashval += (unsigned char) *p++;
1949 return &vartab[hashval % VTABSIZE];
1953 vpcmp(const void *a, const void *b)
1955 return varcmp(*(const char **)a, *(const char **)b);
1959 * This routine initializes the builtin variables.
1969 * PS1 depends on uid
1971 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1972 vps1.text = "PS1=\\w \\$ ";
1975 vps1.text = "PS1=# ";
1978 end = vp + ARRAY_SIZE(varinit);
1980 vpp = hashvar(vp->text);
1983 } while (++vp < end);
1986 static struct var **
1987 findvar(struct var **vpp, const char *name)
1989 for (; *vpp; vpp = &(*vpp)->next) {
1990 if (varequal((*vpp)->text, name)) {
1998 * Find the value of a variable. Returns NULL if not set.
2001 lookupvar(const char *name)
2005 v = *findvar(hashvar(name), name);
2007 #if ENABLE_ASH_RANDOM_SUPPORT
2009 * Dynamic variables are implemented roughly the same way they are
2010 * in bash. Namely, they're "special" so long as they aren't unset.
2011 * As soon as they're unset, they're no longer dynamic, and dynamic
2012 * lookup will no longer happen at that point. -- PFM.
2014 if ((v->flags & VDYNAMIC))
2017 if (!(v->flags & VUNSET))
2018 return strchrnul(v->text, '=') + 1;
2024 * Search the environment of a builtin command.
2027 bltinlookup(const char *name)
2031 for (sp = cmdenviron; sp; sp = sp->next) {
2032 if (varequal(sp->text, name))
2033 return strchrnul(sp->text, '=') + 1;
2035 return lookupvar(name);
2039 * Same as setvar except that the variable and value are passed in
2040 * the first argument as name=value. Since the first argument will
2041 * be actually stored in the table, it should not be a string that
2043 * Called with interrupts off.
2046 setvareq(char *s, int flags)
2048 struct var *vp, **vpp;
2051 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2052 vp = *findvar(vpp, s);
2054 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2057 if (flags & VNOSAVE)
2060 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2066 if (vp->func && (flags & VNOFUNC) == 0)
2067 (*vp->func)(strchrnul(s, '=') + 1);
2069 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2070 free((char*)vp->text);
2072 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2077 vp = ckzalloc(sizeof(*vp));
2079 /*vp->func = NULL; - ckzalloc did it */
2082 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2089 * Set the value of a variable. The flags argument is ored with the
2090 * flags of the variable. If val is NULL, the variable is unset.
2093 setvar(const char *name, const char *val, int flags)
2100 q = endofname(name);
2101 p = strchrnul(q, '=');
2103 if (!namelen || p != q)
2104 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2109 vallen = strlen(val);
2112 nameeq = ckmalloc(namelen + vallen + 2);
2113 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2116 p = (char *)memcpy(p, val, vallen) + vallen;
2119 setvareq(nameeq, flags | VNOSAVE);
2123 #if ENABLE_ASH_GETOPTS
2125 * Safe version of setvar, returns 1 on success 0 on failure.
2128 setvarsafe(const char *name, const char *val, int flags)
2131 volatile int saveint;
2132 struct jmploc *volatile savehandler = exception_handler;
2133 struct jmploc jmploc;
2136 if (setjmp(jmploc.loc))
2139 exception_handler = &jmploc;
2140 setvar(name, val, flags);
2143 exception_handler = savehandler;
2144 RESTORE_INT(saveint);
2150 * Unset the specified variable.
2153 unsetvar(const char *s)
2159 vpp = findvar(hashvar(s), s);
2163 int flags = vp->flags;
2166 if (flags & VREADONLY)
2168 #if ENABLE_ASH_RANDOM_SUPPORT
2169 vp->flags &= ~VDYNAMIC;
2173 if ((flags & VSTRFIXED) == 0) {
2175 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2176 free((char*)vp->text);
2182 vp->flags &= ~VEXPORT;
2192 * Process a linked list of variable assignments.
2195 listsetvar(struct strlist *list_set_var, int flags)
2197 struct strlist *lp = list_set_var;
2203 setvareq(lp->text, flags);
2210 * Generate a list of variables satisfying the given conditions.
2213 listvars(int on, int off, char ***end)
2224 for (vp = *vpp; vp; vp = vp->next) {
2225 if ((vp->flags & mask) == on) {
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2228 *ep++ = (char *) vp->text;
2231 } while (++vpp < vartab + VTABSIZE);
2232 if (ep == stackstrend())
2233 ep = growstackstr();
2237 return grabstackstr(ep);
2241 /* ============ Path search helper
2243 * The variable path (passed by reference) should be set to the start
2244 * of the path before the first call; path_advance will update
2245 * this value as it proceeds. Successive calls to path_advance will return
2246 * the possible path expansions in sequence. If an option (indicated by
2247 * a percent sign) appears in the path entry then the global variable
2248 * pathopt will be set to point to it; otherwise pathopt will be set to
2251 static const char *pathopt; /* set by path_advance */
2254 path_advance(const char **path, const char *name)
2264 for (p = start; *p && *p != ':' && *p != '%'; p++)
2266 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2267 while (stackblocksize() < len)
2271 memcpy(q, start, p - start);
2279 while (*p && *p != ':')
2286 return stalloc(len);
2290 /* ============ Prompt */
2292 static smallint doprompt; /* if set, prompt the user */
2293 static smallint needprompt; /* true if interactive and at start of line */
2295 #if ENABLE_FEATURE_EDITING
2296 static line_input_t *line_input_state;
2297 static const char *cmdedit_prompt;
2299 putprompt(const char *s)
2301 if (ENABLE_ASH_EXPAND_PRMT) {
2302 free((char*)cmdedit_prompt);
2303 cmdedit_prompt = ckstrdup(s);
2310 putprompt(const char *s)
2316 #if ENABLE_ASH_EXPAND_PRMT
2317 /* expandstr() needs parsing machinery, so it is far away ahead... */
2318 static const char *expandstr(const char *ps);
2320 #define expandstr(s) s
2324 setprompt(int whichprompt)
2327 #if ENABLE_ASH_EXPAND_PRMT
2328 struct stackmark smark;
2333 switch (whichprompt) {
2343 #if ENABLE_ASH_EXPAND_PRMT
2344 setstackmark(&smark);
2345 stalloc(stackblocksize());
2347 putprompt(expandstr(prompt));
2348 #if ENABLE_ASH_EXPAND_PRMT
2349 popstackmark(&smark);
2354 /* ============ The cd and pwd commands */
2356 #define CD_PHYSICAL 1
2366 while ((i = nextopt("LP")) != '\0') {
2368 flags ^= CD_PHYSICAL;
2377 * Update curdir (the name of the current directory) in response to a
2381 updatepwd(const char *dir)
2388 cdcomppath = ststrdup(dir);
2391 if (curdir == nullstr)
2393 new = stack_putstr(curdir, new);
2395 new = makestrspace(strlen(dir) + 2, new);
2396 lim = (char *)stackblock() + 1;
2400 if (new > lim && *lim == '/')
2405 if (dir[1] == '/' && dir[2] != '/') {
2411 p = strtok(cdcomppath, "/");
2415 if (p[1] == '.' && p[2] == '\0') {
2427 new = stack_putstr(p, new);
2435 return stackblock();
2439 * Find out what the current directory is. If we already know the current
2440 * directory, this routine returns immediately.
2445 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2446 return dir ? dir : nullstr;
2450 setpwd(const char *val, int setold)
2454 oldcur = dir = curdir;
2457 setvar("OLDPWD", oldcur, VEXPORT);
2460 if (physdir != nullstr) {
2461 if (physdir != oldcur)
2465 if (oldcur == val || !val) {
2471 dir = ckstrdup(val);
2472 if (oldcur != dir && oldcur != nullstr) {
2477 setvar("PWD", dir, VEXPORT);
2480 static void hashcd(void);
2483 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2484 * know that the current directory has changed.
2487 docd(const char *dest, int flags)
2489 const char *dir = 0;
2492 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2495 if (!(flags & CD_PHYSICAL)) {
2496 dir = updatepwd(dest);
2510 static int FAST_FUNC
2511 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2523 dest = bltinlookup(homestr);
2524 else if (LONE_DASH(dest)) {
2525 dest = bltinlookup("OLDPWD");
2547 path = bltinlookup("CDPATH");
2556 p = path_advance(&path, dest);
2557 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2561 if (!docd(p, flags))
2566 ash_msg_and_raise_error("can't cd to %s", dest);
2569 if (flags & CD_PRINT)
2570 out1fmt(snlfmt, curdir);
2574 static int FAST_FUNC
2575 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2578 const char *dir = curdir;
2582 if (physdir == nullstr)
2586 out1fmt(snlfmt, dir);
2591 /* ============ ... */
2594 #define IBUFSIZ COMMON_BUFSIZE
2595 /* buffer for top level input file */
2596 #define basebuf bb_common_bufsiz1
2598 /* Syntax classes */
2599 #define CWORD 0 /* character is nothing special */
2600 #define CNL 1 /* newline character */
2601 #define CBACK 2 /* a backslash character */
2602 #define CSQUOTE 3 /* single quote */
2603 #define CDQUOTE 4 /* double quote */
2604 #define CENDQUOTE 5 /* a terminating quote */
2605 #define CBQUOTE 6 /* backwards single quote */
2606 #define CVAR 7 /* a dollar sign */
2607 #define CENDVAR 8 /* a '}' character */
2608 #define CLP 9 /* a left paren in arithmetic */
2609 #define CRP 10 /* a right paren in arithmetic */
2610 #define CENDFILE 11 /* end of file */
2611 #define CCTL 12 /* like CWORD, except it must be escaped */
2612 #define CSPCL 13 /* these terminate a word */
2613 #define CIGN 14 /* character should be ignored */
2616 #if ENABLE_ASH_ALIAS
2620 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2622 #if ENABLE_SH_MATH_SUPPORT
2623 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2625 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2627 static const uint16_t S_I_T[] = {
2628 #if ENABLE_ASH_ALIAS
2629 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2631 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2632 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2633 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2634 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2635 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2636 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2637 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2638 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2639 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2640 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2641 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2642 #if !USE_SIT_FUNCTION
2643 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2644 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2645 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2649 /* Constants below must match table above */
2651 #if ENABLE_ASH_ALIAS
2652 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2654 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2655 CNL_CNL_CNL_CNL , /* 2 */
2656 CWORD_CCTL_CCTL_CWORD , /* 3 */
2657 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2658 CVAR_CVAR_CWORD_CVAR , /* 5 */
2659 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2660 CSPCL_CWORD_CWORD_CLP , /* 7 */
2661 CSPCL_CWORD_CWORD_CRP , /* 8 */
2662 CBACK_CBACK_CCTL_CBACK , /* 9 */
2663 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2664 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2665 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2666 CWORD_CWORD_CWORD_CWORD , /* 13 */
2667 CCTL_CCTL_CCTL_CCTL , /* 14 */
2670 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2671 * caller must ensure proper cast on it if c is *char_ptr!
2673 /* Values for syntax param */
2674 #define BASESYNTAX 0 /* not in quotes */
2675 #define DQSYNTAX 1 /* in double quotes */
2676 #define SQSYNTAX 2 /* in single quotes */
2677 #define ARISYNTAX 3 /* in arithmetic */
2678 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2680 #if USE_SIT_FUNCTION
2683 SIT(int c, int syntax)
2685 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2686 # if ENABLE_ASH_ALIAS
2687 static const uint8_t syntax_index_table[] ALIGN1 = {
2688 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2689 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2690 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2694 static const uint8_t syntax_index_table[] ALIGN1 = {
2695 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2696 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2697 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2706 # if ENABLE_ASH_ALIAS
2712 /* Cast is purely for paranoia here,
2713 * just in case someone passed signed char to us */
2714 if ((unsigned char)c >= CTL_FIRST
2715 && (unsigned char)c <= CTL_LAST
2719 s = strchrnul(spec_symbls, c);
2722 indx = syntax_index_table[s - spec_symbls];
2724 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2727 #else /* !USE_SIT_FUNCTION */
2729 static const uint8_t syntax_index_table[] = {
2730 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2731 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2741 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2742 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2764 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2765 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2766 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2768 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2769 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2770 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2771 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2772 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2773 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2776 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2777 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2778 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2779 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2792 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2793 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2794 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2795 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2824 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2825 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2828 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2856 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2857 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2858 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2859 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2861 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2862 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2863 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2864 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2865 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2866 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2867 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2868 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 255 */ CWORD_CWORD_CWORD_CWORD,
2987 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2988 # if ENABLE_ASH_ALIAS
2989 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2993 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
2995 #endif /* !USE_SIT_FUNCTION */
2998 /* ============ Alias handling */
3000 #if ENABLE_ASH_ALIAS
3002 #define ALIASINUSE 1
3013 static struct alias **atab; // [ATABSIZE];
3014 #define INIT_G_alias() do { \
3015 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3019 static struct alias **
3020 __lookupalias(const char *name) {
3021 unsigned int hashval;
3028 ch = (unsigned char)*p;
3032 ch = (unsigned char)*++p;
3034 app = &atab[hashval % ATABSIZE];
3036 for (; *app; app = &(*app)->next) {
3037 if (strcmp(name, (*app)->name) == 0) {
3045 static struct alias *
3046 lookupalias(const char *name, int check)
3048 struct alias *ap = *__lookupalias(name);
3050 if (check && ap && (ap->flag & ALIASINUSE))
3055 static struct alias *
3056 freealias(struct alias *ap)
3060 if (ap->flag & ALIASINUSE) {
3061 ap->flag |= ALIASDEAD;
3073 setalias(const char *name, const char *val)
3075 struct alias *ap, **app;
3077 app = __lookupalias(name);
3081 if (!(ap->flag & ALIASINUSE)) {
3084 ap->val = ckstrdup(val);
3085 ap->flag &= ~ALIASDEAD;
3088 ap = ckzalloc(sizeof(struct alias));
3089 ap->name = ckstrdup(name);
3090 ap->val = ckstrdup(val);
3091 /*ap->flag = 0; - ckzalloc did it */
3092 /*ap->next = NULL;*/
3099 unalias(const char *name)
3103 app = __lookupalias(name);
3107 *app = freealias(*app);
3118 struct alias *ap, **app;
3122 for (i = 0; i < ATABSIZE; i++) {
3124 for (ap = *app; ap; ap = *app) {
3125 *app = freealias(*app);
3135 printalias(const struct alias *ap)
3137 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3141 * TODO - sort output
3143 static int FAST_FUNC
3144 aliascmd(int argc UNUSED_PARAM, char **argv)
3153 for (i = 0; i < ATABSIZE; i++) {
3154 for (ap = atab[i]; ap; ap = ap->next) {
3160 while ((n = *++argv) != NULL) {
3161 v = strchr(n+1, '=');
3162 if (v == NULL) { /* n+1: funny ksh stuff */
3163 ap = *__lookupalias(n);
3165 fprintf(stderr, "%s: %s not found\n", "alias", n);
3178 static int FAST_FUNC
3179 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3183 while ((i = nextopt("a")) != '\0') {
3189 for (i = 0; *argptr; argptr++) {
3190 if (unalias(*argptr)) {
3191 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3199 #endif /* ASH_ALIAS */
3202 /* ============ jobs.c */
3204 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3207 #define FORK_NOJOB 2
3209 /* mode flags for showjob(s) */
3210 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3211 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3212 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3215 * A job structure contains information about a job. A job is either a
3216 * single process or a set of processes contained in a pipeline. In the
3217 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3221 pid_t ps_pid; /* process id */
3222 int ps_status; /* last process status from wait() */
3223 char *ps_cmd; /* text of command being run */
3227 struct procstat ps0; /* status of process */
3228 struct procstat *ps; /* status or processes when more than one */
3230 int stopstatus; /* status of a stopped job */
3233 nprocs: 16, /* number of processes */
3235 #define JOBRUNNING 0 /* at least one proc running */
3236 #define JOBSTOPPED 1 /* all procs are stopped */
3237 #define JOBDONE 2 /* all procs are completed */
3239 sigint: 1, /* job was killed by SIGINT */
3240 jobctl: 1, /* job running under job control */
3242 waited: 1, /* true if this entry has been waited for */
3243 used: 1, /* true if this entry is in used */
3244 changed: 1; /* true if status has changed */
3245 struct job *prev_job; /* previous job */
3248 static struct job *makejob(/*union node *,*/ int);
3249 static int forkshell(struct job *, union node *, int);
3250 static int waitforjob(struct job *);
3253 enum { doing_jobctl = 0 };
3254 #define setjobctl(on) do {} while (0)
3256 static smallint doing_jobctl; //references:8
3257 static void setjobctl(int);
3264 ignoresig(int signo)
3266 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3267 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3268 /* No, need to do it */
3269 signal(signo, SIG_IGN);
3271 sigmode[signo - 1] = S_HARD_IGN;
3275 * Signal handler. Only one usage site - in setsignal()
3280 gotsig[signo - 1] = 1;
3282 if (signo == SIGINT && !trap[SIGINT]) {
3283 if (!suppress_int) {
3285 raise_interrupt(); /* does not return */
3289 pending_sig = signo;
3294 * Set the signal handler for the specified signal. The routine figures
3295 * out what it should be set to.
3298 setsignal(int signo)
3301 char cur_act, new_act;
3302 struct sigaction act;
3306 if (t != NULL) { /* trap for this sig is set */
3308 if (t[0] == '\0') /* trap is "": ignore this sig */
3312 if (rootshell && new_act == S_DFL) {
3315 if (iflag || minusc || sflag == 0)
3324 * "In all cases, bash ignores SIGQUIT. Non-builtin
3325 * commands run by bash have signal handlers
3326 * set to the values inherited by the shell
3327 * from its parent". */
3343 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3344 //whereas we have to restore it to what shell got on entry
3345 //from the parent. See comment above
3347 t = &sigmode[signo - 1];
3350 /* current setting is not yet known */
3351 if (sigaction(signo, NULL, &act)) {
3352 /* pretend it worked; maybe we should give a warning,
3353 * but other shells don't. We don't alter sigmode,
3354 * so we retry every time.
3355 * btw, in Linux it never fails. --vda */
3358 if (act.sa_handler == SIG_IGN) {
3359 cur_act = S_HARD_IGN;
3361 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3363 cur_act = S_IGN; /* don't hard ignore these */
3367 if (cur_act == S_HARD_IGN || cur_act == new_act)
3370 act.sa_handler = SIG_DFL;
3373 act.sa_handler = onsig;
3374 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3375 sigfillset(&act.sa_mask); /* ditto */
3378 act.sa_handler = SIG_IGN;
3381 sigaction_set(signo, &act);
3386 /* mode flags for set_curjob */
3387 #define CUR_DELETE 2
3388 #define CUR_RUNNING 1
3389 #define CUR_STOPPED 0
3391 /* mode flags for dowait */
3392 #define DOWAIT_NONBLOCK WNOHANG
3393 #define DOWAIT_BLOCK 0
3396 /* pgrp of shell on invocation */
3397 static int initialpgrp; //references:2
3398 static int ttyfd = -1; //5
3401 static struct job *jobtab; //5
3403 static unsigned njobs; //4
3405 static struct job *curjob; //lots
3406 /* number of presumed living untracked jobs */
3407 static int jobless; //4
3410 set_curjob(struct job *jp, unsigned mode)
3413 struct job **jpp, **curp;
3415 /* first remove from list */
3416 jpp = curp = &curjob;
3421 jpp = &jp1->prev_job;
3423 *jpp = jp1->prev_job;
3425 /* Then re-insert in correct position */
3433 /* job being deleted */
3436 /* newly created job or backgrounded job,
3437 put after all stopped jobs. */
3441 if (!jp1 || jp1->state != JOBSTOPPED)
3444 jpp = &jp1->prev_job;
3450 /* newly stopped job - becomes curjob */
3451 jp->prev_job = *jpp;
3459 jobno(const struct job *jp)
3461 return jp - jobtab + 1;
3466 * Convert a job name to a job structure.
3469 #define getjob(name, getctl) getjob(name)
3472 getjob(const char *name, int getctl)
3476 const char *err_msg = "%s: no such job";
3480 char *(*match)(const char *, const char *);
3495 if (c == '+' || c == '%') {
3497 err_msg = "No current job";
3503 err_msg = "No previous job";
3514 jp = jobtab + num - 1;
3529 if (match(jp->ps[0].ps_cmd, p)) {
3533 err_msg = "%s: ambiguous";
3543 err_msg = "job %s not created under job control";
3544 if (getctl && jp->jobctl == 0)
3549 ash_msg_and_raise_error(err_msg, name);
3553 * Mark a job structure as unused.
3556 freejob(struct job *jp)
3558 struct procstat *ps;
3562 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3563 if (ps->ps_cmd != nullstr)
3566 if (jp->ps != &jp->ps0)
3569 set_curjob(jp, CUR_DELETE);
3575 xtcsetpgrp(int fd, pid_t pgrp)
3577 if (tcsetpgrp(fd, pgrp))
3578 ash_msg_and_raise_error("can't set tty process group (%m)");
3582 * Turn job control on and off.
3584 * Note: This code assumes that the third arg to ioctl is a character
3585 * pointer, which is true on Berkeley systems but not System V. Since
3586 * System V doesn't have job control yet, this isn't a problem now.
3588 * Called with interrupts off.
3596 if (on == doing_jobctl || rootshell == 0)
3600 ofd = fd = open(_PATH_TTY, O_RDWR);
3602 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3603 * That sometimes helps to acquire controlling tty.
3604 * Obviously, a workaround for bugs when someone
3605 * failed to provide a controlling tty to bash! :) */
3611 fd = fcntl(fd, F_DUPFD, 10);
3616 /* fd is a tty at this point */
3617 close_on_exec_on(fd);
3618 do { /* while we are in the background */
3619 pgrp = tcgetpgrp(fd);
3622 ash_msg("can't access tty; job control turned off");
3626 if (pgrp == getpgrp())
3637 xtcsetpgrp(fd, pgrp);
3639 /* turning job control off */
3642 /* was xtcsetpgrp, but this can make exiting ash
3643 * loop forever if pty is already deleted */
3644 tcsetpgrp(fd, pgrp);
3658 static int FAST_FUNC
3659 killcmd(int argc, char **argv)
3662 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3664 if (argv[i][0] == '%') {
3665 struct job *jp = getjob(argv[i], 0);
3666 unsigned pid = jp->ps[0].ps_pid;
3667 /* Enough space for ' -NNN<nul>' */
3668 argv[i] = alloca(sizeof(int)*3 + 3);
3669 /* kill_main has matching code to expect
3670 * leading space. Needed to not confuse
3671 * negative pids with "kill -SIGNAL_NO" syntax */
3672 sprintf(argv[i], " -%u", pid);
3674 } while (argv[++i]);
3676 return kill_main(argc, argv);
3680 showpipe(struct job *jp /*, FILE *out*/)
3682 struct procstat *ps;
3683 struct procstat *psend;
3685 psend = jp->ps + jp->nprocs;
3686 for (ps = jp->ps + 1; ps < psend; ps++)
3687 printf(" | %s", ps->ps_cmd);
3688 outcslow('\n', stdout);
3689 flush_stdout_stderr();
3694 restartjob(struct job *jp, int mode)
3696 struct procstat *ps;
3702 if (jp->state == JOBDONE)
3704 jp->state = JOBRUNNING;
3705 pgid = jp->ps[0].ps_pid;
3706 if (mode == FORK_FG)
3707 xtcsetpgrp(ttyfd, pgid);
3708 killpg(pgid, SIGCONT);
3712 if (WIFSTOPPED(ps->ps_status)) {
3718 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3723 static int FAST_FUNC
3724 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3730 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3734 jp = getjob(*argv, 1);
3735 if (mode == FORK_BG) {
3736 set_curjob(jp, CUR_RUNNING);
3737 printf("[%d] ", jobno(jp));
3739 out1str(jp->ps[0].ps_cmd);
3740 showpipe(jp /*, stdout*/);
3741 retval = restartjob(jp, mode);
3742 } while (*argv && *++argv);
3748 sprint_status(char *s, int status, int sigonly)
3754 if (!WIFEXITED(status)) {
3756 if (WIFSTOPPED(status))
3757 st = WSTOPSIG(status);
3760 st = WTERMSIG(status);
3762 if (st == SIGINT || st == SIGPIPE)
3765 if (WIFSTOPPED(status))
3770 col = fmtstr(s, 32, strsignal(st));
3771 if (WCOREDUMP(status)) {
3772 col += fmtstr(s + col, 16, " (core dumped)");
3774 } else if (!sigonly) {
3775 st = WEXITSTATUS(status);
3777 col = fmtstr(s, 16, "Done(%d)", st);
3779 col = fmtstr(s, 16, "Done");
3786 dowait(int wait_flags, struct job *job)
3791 struct job *thisjob;
3794 TRACE(("dowait(0x%x) called\n", wait_flags));
3796 /* Do a wait system call. If job control is compiled in, we accept
3797 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3798 * NB: _not_ safe_waitpid, we need to detect EINTR */
3800 wait_flags |= WUNTRACED;
3801 pid = waitpid(-1, &status, wait_flags);
3802 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3803 pid, status, errno, strerror(errno)));
3809 for (jp = curjob; jp; jp = jp->prev_job) {
3810 struct procstat *ps;
3811 struct procstat *psend;
3812 if (jp->state == JOBDONE)
3816 psend = ps + jp->nprocs;
3818 if (ps->ps_pid == pid) {
3819 TRACE(("Job %d: changing status of proc %d "
3820 "from 0x%x to 0x%x\n",
3821 jobno(jp), pid, ps->ps_status, status));
3822 ps->ps_status = status;
3825 if (ps->ps_status == -1)
3828 if (state == JOBRUNNING)
3830 if (WIFSTOPPED(ps->ps_status)) {
3831 jp->stopstatus = ps->ps_status;
3835 } while (++ps < psend);
3840 if (!WIFSTOPPED(status))
3846 if (state != JOBRUNNING) {
3847 thisjob->changed = 1;
3849 if (thisjob->state != state) {
3850 TRACE(("Job %d: changing state from %d to %d\n",
3851 jobno(thisjob), thisjob->state, state));
3852 thisjob->state = state;
3854 if (state == JOBSTOPPED) {
3855 set_curjob(thisjob, CUR_STOPPED);
3864 if (thisjob && thisjob == job) {
3868 len = sprint_status(s, status, 1);
3879 blocking_wait_with_raise_on_sig(struct job *job)
3881 pid_t pid = dowait(DOWAIT_BLOCK, job);
3882 if (pid <= 0 && pending_sig)
3883 raise_exception(EXSIG);
3889 showjob(FILE *out, struct job *jp, int mode)
3891 struct procstat *ps;
3892 struct procstat *psend;
3899 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3900 /* just output process (group) id of pipeline */
3901 fprintf(out, "%d\n", ps->ps_pid);
3905 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3910 else if (curjob && jp == curjob->prev_job)
3913 if (mode & SHOW_PIDS)
3914 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
3916 psend = ps + jp->nprocs;
3918 if (jp->state == JOBRUNNING) {
3919 strcpy(s + col, "Running");
3920 col += sizeof("Running") - 1;
3922 int status = psend[-1].ps_status;
3923 if (jp->state == JOBSTOPPED)
3924 status = jp->stopstatus;
3925 col += sprint_status(s + col, status, 0);
3927 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3929 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3930 * or prints several "PID | <cmdN>" lines,
3931 * depending on SHOW_PIDS bit.
3932 * We do not print status of individual processes
3933 * between PID and <cmdN>. bash does it, but not very well:
3934 * first line shows overall job status, not process status,
3935 * making it impossible to know 1st process status.
3939 /* for each process */
3942 if (mode & SHOW_PIDS)
3943 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
3945 fprintf(out, "%s%*c%s%s",
3947 33 - col >= 0 ? 33 - col : 0, ' ',
3948 ps == jp->ps ? "" : "| ",
3951 } while (++ps != psend);
3952 outcslow('\n', out);
3956 if (jp->state == JOBDONE) {
3957 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3963 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3964 * statuses have changed since the last call to showjobs.
3967 showjobs(FILE *out, int mode)
3971 TRACE(("showjobs(0x%x) called\n", mode));
3973 /* Handle all finished jobs */
3974 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
3977 for (jp = curjob; jp; jp = jp->prev_job) {
3978 if (!(mode & SHOW_CHANGED) || jp->changed) {
3979 showjob(out, jp, mode);
3984 static int FAST_FUNC
3985 jobscmd(int argc UNUSED_PARAM, char **argv)
3990 while ((m = nextopt("lp")) != '\0') {
3994 mode |= SHOW_ONLY_PGID;
4000 showjob(stdout, getjob(*argv, 0), mode);
4003 showjobs(stdout, mode);
4010 /* Called only on finished or stopped jobs (no members are running) */
4012 getstatus(struct job *job)
4016 struct procstat *ps;
4018 /* Fetch last member's status */
4019 ps = job->ps + job->nprocs - 1;
4020 status = ps->ps_status;
4022 /* "set -o pipefail" mode: use last _nonzero_ status */
4023 while (status == 0 && --ps >= job->ps)
4024 status = ps->ps_status;
4027 retval = WEXITSTATUS(status);
4028 if (!WIFEXITED(status)) {
4030 retval = WSTOPSIG(status);
4031 if (!WIFSTOPPED(status))
4034 /* XXX: limits number of signals */
4035 retval = WTERMSIG(status);
4037 if (retval == SIGINT)
4043 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4044 jobno(job), job->nprocs, status, retval));
4048 static int FAST_FUNC
4049 waitcmd(int argc UNUSED_PARAM, char **argv)
4056 raise_exception(EXSIG);
4063 /* wait for all jobs */
4067 if (!jp) /* no running procs */
4069 if (jp->state == JOBRUNNING)
4075 * "When bash is waiting for an asynchronous command via
4076 * the wait builtin, the reception of a signal for which a trap
4077 * has been set will cause the wait builtin to return immediately
4078 * with an exit status greater than 128, immediately after which
4079 * the trap is executed."
4080 * Do we do it that way? */
4081 blocking_wait_with_raise_on_sig(NULL);
4087 if (**argv != '%') {
4088 pid_t pid = number(*argv);
4093 if (job->ps[job->nprocs - 1].ps_pid == pid)
4095 job = job->prev_job;
4098 job = getjob(*argv, 0);
4099 /* loop until process terminated or stopped */
4100 while (job->state == JOBRUNNING)
4101 blocking_wait_with_raise_on_sig(NULL);
4103 retval = getstatus(job);
4116 struct job *jp, *jq;
4118 len = njobs * sizeof(*jp);
4120 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4122 offset = (char *)jp - (char *)jq;
4124 /* Relocate pointers */
4127 jq = (struct job *)((char *)jq + l);
4131 #define joff(p) ((struct job *)((char *)(p) + l))
4132 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4133 if (joff(jp)->ps == &jq->ps0)
4134 jmove(joff(jp)->ps);
4135 if (joff(jp)->prev_job)
4136 jmove(joff(jp)->prev_job);
4146 jp = (struct job *)((char *)jp + len);
4150 } while (--jq >= jp);
4155 * Return a new job structure.
4156 * Called with interrupts off.
4159 makejob(/*union node *node,*/ int nprocs)
4164 for (i = njobs, jp = jobtab; ; jp++) {
4171 if (jp->state != JOBDONE || !jp->waited)
4180 memset(jp, 0, sizeof(*jp));
4182 /* jp->jobctl is a bitfield.
4183 * "jp->jobctl |= jobctl" likely to give awful code */
4187 jp->prev_job = curjob;
4192 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4194 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4201 * Return a string identifying a command (to be printed by the
4204 static char *cmdnextc;
4207 cmdputs(const char *s)
4209 static const char vstype[VSTYPE + 1][3] = {
4210 "", "}", "-", "+", "?", "=",
4211 "%", "%%", "#", "##"
4212 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4215 const char *p, *str;
4219 unsigned char subtype = 0;
4223 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4225 while ((c = *p++) != '\0') {
4233 if ((subtype & VSTYPE) == VSLENGTH)
4237 if (!(subtype & VSQUOTE) == !(quoted & 1))
4243 str = "\"}" + !(quoted & 1);
4250 case CTLBACKQ+CTLQUOTE:
4253 #if ENABLE_SH_MATH_SUPPORT
4268 if ((subtype & VSTYPE) != VSNORMAL)
4270 str = vstype[subtype & VSTYPE];
4271 if (subtype & VSNUL)
4280 /* These can only happen inside quotes */
4293 while ((c = *str++) != '\0') {
4296 } /* while *p++ not NUL */
4299 USTPUTC('"', nextc);
4305 /* cmdtxt() and cmdlist() call each other */
4306 static void cmdtxt(union node *n);
4309 cmdlist(union node *np, int sep)
4311 for (; np; np = np->narg.next) {
4315 if (sep && np->narg.next)
4321 cmdtxt(union node *n)
4324 struct nodelist *lp;
4335 lp = n->npipe.cmdlist;
4353 cmdtxt(n->nbinary.ch1);
4369 cmdtxt(n->nif.test);
4371 if (n->nif.elsepart) {
4372 cmdtxt(n->nif.ifpart);
4374 n = n->nif.elsepart;
4392 cmdtxt(n->nbinary.ch1);
4402 cmdputs(n->nfor.var);
4404 cmdlist(n->nfor.args, 1);
4409 cmdputs(n->narg.text);
4413 cmdlist(n->ncmd.args, 1);
4414 cmdlist(n->ncmd.redirect, 0);
4427 cmdputs(n->ncase.expr->narg.text);
4429 for (np = n->ncase.cases; np; np = np->nclist.next) {
4430 cmdtxt(np->nclist.pattern);
4432 cmdtxt(np->nclist.body);
4446 #if ENABLE_ASH_BASH_COMPAT
4461 cmdputs(utoa(n->nfile.fd));
4463 if (n->type == NTOFD || n->type == NFROMFD) {
4464 cmdputs(utoa(n->ndup.dupfd));
4473 commandtext(union node *n)
4477 STARTSTACKSTR(cmdnextc);
4479 name = stackblock();
4480 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4481 name, cmdnextc, cmdnextc));
4482 return ckstrdup(name);
4487 * Fork off a subshell. If we are doing job control, give the subshell its
4488 * own process group. Jp is a job structure that the job is to be added to.
4489 * N is the command that will be evaluated by the child. Both jp and n may
4490 * be NULL. The mode parameter can be one of the following:
4491 * FORK_FG - Fork off a foreground process.
4492 * FORK_BG - Fork off a background process.
4493 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4494 * process group even if job control is on.
4496 * When job control is turned off, background processes have their standard
4497 * input redirected to /dev/null (except for the second and later processes
4500 * Called with interrupts off.
4503 * Clear traps on a fork.
4510 for (tp = trap; tp < &trap[NSIG]; tp++) {
4511 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4513 if (trap_ptr == trap)
4515 /* else: it "belongs" to trap_ptr vector, don't free */
4517 if ((tp - trap) != 0)
4518 setsignal(tp - trap);
4524 /* Lives far away from here, needed for forkchild */
4525 static void closescript(void);
4527 /* Called after fork(), in child */
4528 static NOINLINE void
4529 forkchild(struct job *jp, union node *n, int mode)
4533 TRACE(("Child shell %d\n", getpid()));
4537 /* man bash: "Non-builtin commands run by bash have signal handlers
4538 * set to the values inherited by the shell from its parent".
4539 * Do we do it correctly? */
4543 if (mode == FORK_NOJOB /* is it `xxx` ? */
4544 && n && n->type == NCMD /* is it single cmd? */
4545 /* && n->ncmd.args->type == NARG - always true? */
4546 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4547 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4548 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4550 TRACE(("Trap hack\n"));
4551 /* Awful hack for `trap` or $(trap).
4553 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4554 * contains an example where "trap" is executed in a subshell:
4556 * save_traps=$(trap)
4558 * eval "$save_traps"
4560 * Standard does not say that "trap" in subshell shall print
4561 * parent shell's traps. It only says that its output
4562 * must have suitable form, but then, in the above example
4563 * (which is not supposed to be normative), it implies that.
4565 * bash (and probably other shell) does implement it
4566 * (traps are reset to defaults, but "trap" still shows them),
4567 * but as a result, "trap" logic is hopelessly messed up:
4570 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4571 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4572 * # true | trap <--- trap is in subshell - no output (ditto)
4573 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4574 * trap -- 'echo Ho' SIGWINCH
4575 * # echo `(trap)` <--- in subshell in subshell - output
4576 * trap -- 'echo Ho' SIGWINCH
4577 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4578 * trap -- 'echo Ho' SIGWINCH
4580 * The rules when to forget and when to not forget traps
4581 * get really complex and nonsensical.
4583 * Our solution: ONLY bare $(trap) or `trap` is special.
4585 /* Save trap handler strings for trap builtin to print */
4586 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4587 /* Fall through into clearing traps */
4591 /* do job control only in root shell */
4593 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4596 if (jp->nprocs == 0)
4599 pgrp = jp->ps[0].ps_pid;
4600 /* this can fail because we are doing it in the parent also */
4602 if (mode == FORK_FG)
4603 xtcsetpgrp(ttyfd, pgrp);
4608 if (mode == FORK_BG) {
4609 /* man bash: "When job control is not in effect,
4610 * asynchronous commands ignore SIGINT and SIGQUIT" */
4613 if (jp->nprocs == 0) {
4615 if (open(bb_dev_null, O_RDONLY) != 0)
4616 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4620 if (iflag) { /* why if iflag only? */
4625 * "In all cases, bash ignores SIGQUIT. Non-builtin
4626 * commands run by bash have signal handlers
4627 * set to the values inherited by the shell
4629 * Take care of the second rule: */
4633 if (n && n->type == NCMD
4634 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4636 TRACE(("Job hack\n"));
4637 /* "jobs": we do not want to clear job list for it,
4638 * instead we remove only _its_ own_ job from job list.
4639 * This makes "jobs .... | cat" more useful.
4645 for (jp = curjob; jp; jp = jp->prev_job)
4650 /* Called after fork(), in parent */
4652 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4655 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4657 TRACE(("In parent shell: child = %d\n", pid));
4659 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4665 if (mode != FORK_NOJOB && jp->jobctl) {
4668 if (jp->nprocs == 0)
4671 pgrp = jp->ps[0].ps_pid;
4672 /* This can fail because we are doing it in the child also */
4676 if (mode == FORK_BG) {
4677 backgndpid = pid; /* set $! */
4678 set_curjob(jp, CUR_RUNNING);
4681 struct procstat *ps = &jp->ps[jp->nprocs++];
4684 ps->ps_cmd = nullstr;
4686 if (doing_jobctl && n)
4687 ps->ps_cmd = commandtext(n);
4693 forkshell(struct job *jp, union node *n, int mode)
4697 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4700 TRACE(("Fork failed, errno=%d", errno));
4703 ash_msg_and_raise_error("can't fork");
4706 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4707 forkchild(jp, n, mode);
4709 forkparent(jp, n, mode, pid);
4715 * Wait for job to finish.
4717 * Under job control we have the problem that while a child process
4718 * is running interrupts generated by the user are sent to the child
4719 * but not to the shell. This means that an infinite loop started by
4720 * an interactive user may be hard to kill. With job control turned off,
4721 * an interactive user may place an interactive program inside a loop.
4722 * If the interactive program catches interrupts, the user doesn't want
4723 * these interrupts to also abort the loop. The approach we take here
4724 * is to have the shell ignore interrupt signals while waiting for a
4725 * foreground process to terminate, and then send itself an interrupt
4726 * signal if the child process was terminated by an interrupt signal.
4727 * Unfortunately, some programs want to do a bit of cleanup and then
4728 * exit on interrupt; unless these processes terminate themselves by
4729 * sending a signal to themselves (instead of calling exit) they will
4730 * confuse this approach.
4732 * Called with interrupts off.
4735 waitforjob(struct job *jp)
4739 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4742 while (jp->state == JOBRUNNING) {
4743 /* In non-interactive shells, we _can_ get
4744 * a keyboard signal here and be EINTRed,
4745 * but we just loop back, waiting for command to complete.
4748 * "If bash is waiting for a command to complete and receives
4749 * a signal for which a trap has been set, the trap
4750 * will not be executed until the command completes."
4752 * Reality is that even if trap is not set, bash
4753 * will not act on the signal until command completes.
4754 * Try this. sleep5intoff.c:
4755 * #include <signal.h>
4756 * #include <unistd.h>
4759 * sigemptyset(&set);
4760 * sigaddset(&set, SIGINT);
4761 * sigaddset(&set, SIGQUIT);
4762 * sigprocmask(SIG_BLOCK, &set, NULL);
4766 * $ bash -c './sleep5intoff; echo hi'
4767 * ^C^C^C^C <--- pressing ^C once a second
4769 * $ bash -c './sleep5intoff; echo hi'
4770 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4773 dowait(DOWAIT_BLOCK, jp);
4780 xtcsetpgrp(ttyfd, rootpid);
4782 * This is truly gross.
4783 * If we're doing job control, then we did a TIOCSPGRP which
4784 * caused us (the shell) to no longer be in the controlling
4785 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4786 * intuit from the subprocess exit status whether a SIGINT
4787 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4789 if (jp->sigint) /* TODO: do the same with all signals */
4790 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4792 if (jp->state == JOBDONE)
4799 * return 1 if there are stopped jobs, otherwise 0
4811 if (jp && jp->state == JOBSTOPPED) {
4812 out2str("You have stopped jobs.\n");
4821 /* ============ redir.c
4823 * Code for dealing with input/output redirection.
4826 #define EMPTY -2 /* marks an unused slot in redirtab */
4827 #define CLOSED -3 /* marks a slot of previously-closed fd */
4830 * Open a file in noclobber mode.
4831 * The code was copied from bash.
4834 noclobberopen(const char *fname)
4837 struct stat finfo, finfo2;
4840 * If the file exists and is a regular file, return an error
4843 r = stat(fname, &finfo);
4844 if (r == 0 && S_ISREG(finfo.st_mode)) {
4850 * If the file was not present (r != 0), make sure we open it
4851 * exclusively so that if it is created before we open it, our open
4852 * will fail. Make sure that we do not truncate an existing file.
4853 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4854 * file was not a regular file, we leave O_EXCL off.
4857 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4858 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4860 /* If the open failed, return the file descriptor right away. */
4865 * OK, the open succeeded, but the file may have been changed from a
4866 * non-regular file to a regular file between the stat and the open.
4867 * We are assuming that the O_EXCL open handles the case where FILENAME
4868 * did not exist and is symlinked to an existing file between the stat
4873 * If we can open it and fstat the file descriptor, and neither check
4874 * revealed that it was a regular file, and the file has not been
4875 * replaced, return the file descriptor.
4877 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4878 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4881 /* The file has been replaced. badness. */
4888 * Handle here documents. Normally we fork off a process to write the
4889 * data to a pipe. If the document is short, we can stuff the data in
4890 * the pipe without forking.
4892 /* openhere needs this forward reference */
4893 static void expandhere(union node *arg, int fd);
4895 openhere(union node *redir)
4901 ash_msg_and_raise_error("pipe call failed");
4902 if (redir->type == NHERE) {
4903 len = strlen(redir->nhere.doc->narg.text);
4904 if (len <= PIPE_BUF) {
4905 full_write(pip[1], redir->nhere.doc->narg.text, len);
4909 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4912 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4913 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4914 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4915 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4916 signal(SIGPIPE, SIG_DFL);
4917 if (redir->type == NHERE)
4918 full_write(pip[1], redir->nhere.doc->narg.text, len);
4920 expandhere(redir->nhere.doc, pip[1]);
4921 _exit(EXIT_SUCCESS);
4929 openredirect(union node *redir)
4934 switch (redir->nfile.type) {
4936 fname = redir->nfile.expfname;
4937 f = open(fname, O_RDONLY);
4942 fname = redir->nfile.expfname;
4943 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4948 #if ENABLE_ASH_BASH_COMPAT
4951 /* Take care of noclobber mode. */
4953 fname = redir->nfile.expfname;
4954 f = noclobberopen(fname);
4961 fname = redir->nfile.expfname;
4962 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4967 fname = redir->nfile.expfname;
4968 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4976 /* Fall through to eliminate warning. */
4977 /* Our single caller does this itself */
4984 f = openhere(redir);
4990 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
4992 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
4996 * Copy a file descriptor to be >= to. Returns -1
4997 * if the source file descriptor is closed, EMPTY if there are no unused
4998 * file descriptors left.
5000 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5001 * old code was doing close(to) prior to copyfd() to achieve the same */
5003 COPYFD_EXACT = (int)~(INT_MAX),
5004 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5007 copyfd(int from, int to)
5011 if (to & COPYFD_EXACT) {
5012 to &= ~COPYFD_EXACT;
5014 newfd = dup2(from, to);
5016 newfd = fcntl(from, F_DUPFD, to);
5019 if (errno == EMFILE)
5021 /* Happens when source fd is not open: try "echo >&99" */
5022 ash_msg_and_raise_error("%d: %m", from);
5027 /* Struct def and variable are moved down to the first usage site */
5032 struct redirtab *next;
5035 struct two_fd_t two_fd[];
5037 #define redirlist (G_var.redirlist)
5039 static int need_to_remember(struct redirtab *rp, int fd)
5043 if (!rp) /* remembering was not requested */
5046 for (i = 0; i < rp->pair_count; i++) {
5047 if (rp->two_fd[i].orig == fd) {
5048 /* already remembered */
5055 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5056 static int is_hidden_fd(struct redirtab *rp, int fd)
5059 struct parsefile *pf;
5072 fd |= COPYFD_RESTORE;
5073 for (i = 0; i < rp->pair_count; i++) {
5074 if (rp->two_fd[i].copy == fd) {
5082 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5083 * old file descriptors are stashed away so that the redirection can be
5084 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5085 * standard output, and the standard error if it becomes a duplicate of
5086 * stdout, is saved in memory.
5088 /* flags passed to redirect */
5089 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5090 #define REDIR_SAVEFD2 03 /* set preverrout */
5092 redirect(union node *redir, int flags)
5094 struct redirtab *sv;
5099 int copied_fd2 = -1;
5109 if (flags & REDIR_PUSH) {
5110 union node *tmp = redir;
5113 #if ENABLE_ASH_BASH_COMPAT
5114 if (redir->nfile.type == NTO2)
5117 tmp = tmp->nfile.next;
5119 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5120 sv->next = redirlist;
5121 sv->pair_count = sv_pos;
5123 sv->nullredirs = g_nullredirs - 1;
5125 while (sv_pos > 0) {
5127 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5132 fd = redir->nfile.fd;
5133 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5134 int right_fd = redir->ndup.dupfd;
5135 /* redirect from/to same file descriptor? */
5138 /* echo >&10 and 10 is a fd opened to the sh script? */
5139 if (is_hidden_fd(sv, right_fd)) {
5140 errno = EBADF; /* as if it is closed */
5141 ash_msg_and_raise_error("%d: %m", right_fd);
5145 newfd = openredirect(redir); /* always >= 0 */
5147 /* Descriptor wasn't open before redirect.
5148 * Mark it for close in the future */
5149 if (need_to_remember(sv, fd)) {
5150 goto remember_to_close;
5155 #if ENABLE_ASH_BASH_COMPAT
5158 if (need_to_remember(sv, fd)) {
5159 /* Copy old descriptor */
5160 i = fcntl(fd, F_DUPFD, 10);
5161 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5162 * are closed in popredir() in the child, preventing them from leaking
5163 * into child. (popredir() also cleans up the mess in case of failures)
5168 /* Strange error (e.g. "too many files" EMFILE?) */
5172 ash_msg_and_raise_error("%d: %m", fd);
5175 /* EBADF: it is not open - good, remember to close it */
5178 } else { /* fd is open, save its copy */
5179 /* "exec fd>&-" should not close fds
5180 * which point to script file(s).
5181 * Force them to be restored afterwards */
5182 if (is_hidden_fd(sv, fd))
5183 i |= COPYFD_RESTORE;
5187 sv->two_fd[sv_pos].orig = fd;
5188 sv->two_fd[sv_pos].copy = i;
5192 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5193 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5194 /* Don't want to trigger debugging */
5198 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5200 } else if (fd != newfd) { /* move newfd to fd */
5201 copyfd(newfd, fd | COPYFD_EXACT);
5202 #if ENABLE_ASH_BASH_COMPAT
5203 if (!(redir->nfile.type == NTO2 && fd == 2))
5207 #if ENABLE_ASH_BASH_COMPAT
5208 if (redir->nfile.type == NTO2 && fd == 1) {
5209 /* We already redirected it to fd 1, now copy it to 2 */
5215 } while ((redir = redir->nfile.next) != NULL);
5218 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5219 preverrout_fd = copied_fd2;
5223 * Undo the effects of the last redirection.
5226 popredir(int drop, int restore)
5228 struct redirtab *rp;
5231 if (--g_nullredirs >= 0)
5235 for (i = 0; i < rp->pair_count; i++) {
5236 int fd = rp->two_fd[i].orig;
5237 int copy = rp->two_fd[i].copy;
5238 if (copy == CLOSED) {
5243 if (copy != EMPTY) {
5244 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5245 copy &= ~COPYFD_RESTORE;
5247 copyfd(copy, fd | COPYFD_EXACT);
5249 close(copy & ~COPYFD_RESTORE);
5252 redirlist = rp->next;
5253 g_nullredirs = rp->nullredirs;
5259 * Undo all redirections. Called on error or interrupt.
5263 * Discard all saved file descriptors.
5266 clearredir(int drop)
5272 popredir(drop, /*restore:*/ 0);
5277 redirectsafe(union node *redir, int flags)
5280 volatile int saveint;
5281 struct jmploc *volatile savehandler = exception_handler;
5282 struct jmploc jmploc;
5285 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5286 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5288 exception_handler = &jmploc;
5289 redirect(redir, flags);
5291 exception_handler = savehandler;
5292 if (err && exception_type != EXERROR)
5293 longjmp(exception_handler->loc, 1);
5294 RESTORE_INT(saveint);
5299 /* ============ Routines to expand arguments to commands
5301 * We have to deal with backquotes, shell variables, and file metacharacters.
5304 #if ENABLE_SH_MATH_SUPPORT
5306 ash_arith(const char *s)
5308 arith_eval_hooks_t math_hooks;
5312 math_hooks.lookupvar = lookupvar;
5313 math_hooks.setvar = setvar;
5314 math_hooks.endofname = endofname;
5317 result = arith(s, &errcode, &math_hooks);
5320 ash_msg_and_raise_error("exponent less than 0");
5322 ash_msg_and_raise_error("divide by zero");
5324 ash_msg_and_raise_error("expression recursion loop detected");
5325 raise_error_syntax(s);
5336 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5337 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5338 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5339 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5340 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5341 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5342 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5343 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5344 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5348 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5349 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5350 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5351 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5352 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5355 * Structure specifying which parts of the string should be searched
5356 * for IFS characters.
5359 struct ifsregion *next; /* next region in list */
5360 int begoff; /* offset of start of region */
5361 int endoff; /* offset of end of region */
5362 int nulonly; /* search for nul bytes only */
5366 struct strlist *list;
5367 struct strlist **lastp;
5370 /* output of current string */
5371 static char *expdest;
5372 /* list of back quote expressions */
5373 static struct nodelist *argbackq;
5374 /* first struct in list of ifs regions */
5375 static struct ifsregion ifsfirst;
5376 /* last struct in list */
5377 static struct ifsregion *ifslastp;
5378 /* holds expanded arg list */
5379 static struct arglist exparg;
5389 expdest = makestrspace(32, expdest);
5390 len = fmtstr(expdest, 32, arith_t_fmt, num);
5391 STADJUST(len, expdest);
5396 esclen(const char *start, const char *p)
5400 while (p > start && (unsigned char)*--p == CTLESC) {
5407 * Remove any CTLESC characters from a string.
5410 rmescapes(char *str, int flag)
5412 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5416 unsigned protect_against_glob;
5419 p = strpbrk(str, qchars);
5425 if (flag & RMESCAPE_ALLOC) {
5426 size_t len = p - str;
5427 size_t fulllen = len + strlen(p) + 1;
5429 if (flag & RMESCAPE_GROW) {
5430 r = makestrspace(fulllen, expdest);
5431 } else if (flag & RMESCAPE_HEAP) {
5432 r = ckmalloc(fulllen);
5434 r = stalloc(fulllen);
5438 q = (char *)memcpy(q, str, len) + len;
5442 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5443 globbing = flag & RMESCAPE_GLOB;
5444 protect_against_glob = globbing;
5446 if ((unsigned char)*p == CTLQUOTEMARK) {
5447 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5448 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5449 // Note: both inquotes and protect_against_glob only affect whether
5450 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5451 inquotes = ~inquotes;
5453 protect_against_glob = globbing;
5457 /* naked back slash */
5458 protect_against_glob = 0;
5461 if ((unsigned char)*p == CTLESC) {
5463 if (protect_against_glob && inquotes && *p != '/') {
5467 protect_against_glob = globbing;
5472 if (flag & RMESCAPE_GROW) {
5474 STADJUST(q - r + 1, expdest);
5478 #define pmatch(a, b) !fnmatch((a), (b), 0)
5481 * Prepare a pattern for a expmeta (internal glob(3)) call.
5483 * Returns an stalloced string.
5486 preglob(const char *pattern, int quoted, int flag)
5488 flag |= RMESCAPE_GLOB;
5490 flag |= RMESCAPE_QUOTED;
5492 return rmescapes((char *)pattern, flag);
5496 * Put a string on the stack.
5499 memtodest(const char *p, size_t len, int syntax, int quotes)
5503 q = makestrspace(quotes ? len * 2 : len, q);
5506 unsigned char c = *p++;
5510 int n = SIT(c, syntax);
5511 if (n == CCTL || n == CBACK)
5521 strtodest(const char *p, int syntax, int quotes)
5523 memtodest(p, strlen(p), syntax, quotes);
5527 * Record the fact that we have to scan this region of the
5528 * string for IFS characters.
5531 recordregion(int start, int end, int nulonly)
5533 struct ifsregion *ifsp;
5535 if (ifslastp == NULL) {
5539 ifsp = ckzalloc(sizeof(*ifsp));
5540 /*ifsp->next = NULL; - ckzalloc did it */
5541 ifslastp->next = ifsp;
5545 ifslastp->begoff = start;
5546 ifslastp->endoff = end;
5547 ifslastp->nulonly = nulonly;
5551 removerecordregions(int endoff)
5553 if (ifslastp == NULL)
5556 if (ifsfirst.endoff > endoff) {
5557 while (ifsfirst.next != NULL) {
5558 struct ifsregion *ifsp;
5560 ifsp = ifsfirst.next->next;
5561 free(ifsfirst.next);
5562 ifsfirst.next = ifsp;
5565 if (ifsfirst.begoff > endoff)
5568 ifslastp = &ifsfirst;
5569 ifsfirst.endoff = endoff;
5574 ifslastp = &ifsfirst;
5575 while (ifslastp->next && ifslastp->next->begoff < endoff)
5576 ifslastp=ifslastp->next;
5577 while (ifslastp->next != NULL) {
5578 struct ifsregion *ifsp;
5580 ifsp = ifslastp->next->next;
5581 free(ifslastp->next);
5582 ifslastp->next = ifsp;
5585 if (ifslastp->endoff > endoff)
5586 ifslastp->endoff = endoff;
5590 exptilde(char *startp, char *p, int flags)
5596 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5601 while ((c = *++p) != '\0') {
5608 if (flags & EXP_VARTILDE)
5618 if (*name == '\0') {
5619 home = lookupvar(homestr);
5621 pw = getpwnam(name);
5626 if (!home || !*home)
5629 startloc = expdest - (char *)stackblock();
5630 strtodest(home, SQSYNTAX, quotes);
5631 recordregion(startloc, expdest - (char *)stackblock(), 0);
5639 * Execute a command inside back quotes. If it's a builtin command, we
5640 * want to save its output in a block obtained from malloc. Otherwise
5641 * we fork off a subprocess and get the output of the command via a pipe.
5642 * Should be called with interrupts off.
5644 struct backcmd { /* result of evalbackcmd */
5645 int fd; /* file descriptor to read from */
5646 int nleft; /* number of chars in buffer */
5647 char *buf; /* buffer */
5648 struct job *jp; /* job structure for command */
5651 /* These forward decls are needed to use "eval" code for backticks handling: */
5652 static uint8_t back_exitstatus; /* exit status of backquoted command */
5653 #define EV_EXIT 01 /* exit after evaluating tree */
5654 static void evaltree(union node *, int);
5656 static void FAST_FUNC
5657 evalbackcmd(union node *n, struct backcmd *result)
5668 saveherefd = herefd;
5676 ash_msg_and_raise_error("pipe call failed");
5677 jp = makejob(/*n,*/ 1);
5678 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5683 copyfd(pip[1], 1 | COPYFD_EXACT);
5687 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5691 result->fd = pip[0];
5694 herefd = saveherefd;
5696 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5697 result->fd, result->buf, result->nleft, result->jp));
5701 * Expand stuff in backwards quotes.
5704 expbackq(union node *cmd, int quoted, int quotes)
5712 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5713 struct stackmark smark;
5716 setstackmark(&smark);
5718 startloc = dest - (char *)stackblock();
5720 evalbackcmd(cmd, &in);
5721 popstackmark(&smark);
5728 memtodest(p, i, syntax, quotes);
5732 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5733 TRACE(("expbackq: read returns %d\n", i));
5742 back_exitstatus = waitforjob(in.jp);
5746 /* Eat all trailing newlines */
5748 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5753 recordregion(startloc, dest - (char *)stackblock(), 0);
5754 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5755 (dest - (char *)stackblock()) - startloc,
5756 (dest - (char *)stackblock()) - startloc,
5757 stackblock() + startloc));
5760 #if ENABLE_SH_MATH_SUPPORT
5762 * Expand arithmetic expression. Backup to start of expression,
5763 * evaluate, place result in (backed up) result, adjust string position.
5776 * This routine is slightly over-complicated for
5777 * efficiency. Next we scan backwards looking for the
5778 * start of arithmetic.
5780 start = stackblock();
5787 while ((unsigned char)*p != CTLARI) {
5791 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5796 esc = esclen(start, p);
5806 removerecordregions(begoff);
5813 rmescapes(p + 2, 0);
5815 len = cvtnum(ash_arith(p + 2));
5818 recordregion(begoff, begoff + len, 0);
5822 /* argstr needs it */
5823 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5826 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5827 * characters to allow for further processing. Otherwise treat
5828 * $@ like $* since no splitting will be performed.
5830 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5831 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5832 * for correct expansion of "B=$A" word.
5835 argstr(char *p, int flags, struct strlist *var_str_list)
5837 static const char spclchars[] ALIGN1 = {
5845 CTLBACKQ | CTLQUOTE,
5846 #if ENABLE_SH_MATH_SUPPORT
5851 const char *reject = spclchars;
5852 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5853 int breakall = flags & EXP_WORD;
5858 if (!(flags & EXP_VARTILDE)) {
5860 } else if (flags & EXP_VARTILDE2) {
5865 if (flags & EXP_TILDE) {
5868 flags &= ~EXP_TILDE;
5871 if (*q == CTLESC && (flags & EXP_QWORD))
5874 p = exptilde(p, q, flags);
5877 startloc = expdest - (char *)stackblock();
5881 length += strcspn(p + length, reject);
5885 #if ENABLE_SH_MATH_SUPPORT
5889 /* c == '=' || c == ':' || c == CTLENDARI */
5895 expdest = stack_nputstr(p, length, expdest);
5896 newloc = expdest - (char *)stackblock();
5897 if (breakall && !inquotes && newloc > startloc) {
5898 recordregion(startloc, newloc, 0);
5909 if (flags & EXP_VARTILDE2) {
5913 flags |= EXP_VARTILDE2;
5918 * sort of a hack - expand tildes in variable
5919 * assignments (after the first '=' and after ':'s).
5928 case CTLENDVAR: /* ??? */
5931 /* "$@" syntax adherence hack */
5933 && memcmp(p, dolatstr, 4) == 0
5934 && ( p[4] == CTLQUOTEMARK
5935 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5938 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5941 inquotes = !inquotes;
5954 p = evalvar(p, flags, var_str_list);
5958 case CTLBACKQ|CTLQUOTE:
5959 expbackq(argbackq->n, c, quotes);
5960 argbackq = argbackq->next;
5962 #if ENABLE_SH_MATH_SUPPORT
5975 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
5978 // This commented out code was added by James Simmons <jsimmons@infradead.org>
5979 // as part of a larger change when he added support for ${var/a/b}.
5980 // However, it broke # and % operators:
5984 //echo ${var#ab} abcdcd abcdcd
5985 //echo ${var##ab} abcdcd abcdcd
5986 //echo ${var#a*b} abcdcd ababcdcd (!)
5987 //echo ${var##a*b} cdcd cdcd
5988 //echo ${var#?} babcdcd ababcdcd (!)
5989 //echo ${var##?} babcdcd babcdcd
5990 //echo ${var#*} ababcdcd babcdcd (!)
5992 //echo ${var%cd} ababcd ababcd
5993 //echo ${var%%cd} ababcd abab (!)
5994 //echo ${var%c*d} ababcd ababcd
5995 //echo ${var%%c*d} abab ababcdcd (!)
5996 //echo ${var%?} ababcdc ababcdc
5997 //echo ${var%%?} ababcdc ababcdcd (!)
5998 //echo ${var%*} ababcdcd ababcdcd
6001 // Commenting it back out helped. Remove it completely if it really
6004 char *loc, *loc2; //, *full;
6010 int match; // = strlen(str);
6011 const char *s = loc2;
6018 match = pmatch(str, s); // this line was deleted
6020 // // chop off end if its '*'
6021 // full = strrchr(str, '*');
6022 // if (full && full != str)
6025 // // If str starts with '*' replace with s.
6026 // if ((*str == '*') && strlen(s) >= match) {
6027 // full = xstrdup(s);
6028 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6030 // full = xstrndup(str, match);
6031 // match = strncmp(s, full, strlen(full));
6035 if (match) // if (!match)
6037 if (quotes && (unsigned char)*loc == CTLESC)
6046 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6053 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6056 const char *s = loc2;
6061 match = pmatch(str, s);
6068 esc = esclen(startp, loc);
6079 static void varunset(const char *, const char *, const char *, int) NORETURN;
6081 varunset(const char *end, const char *var, const char *umsg, int varflags)
6087 msg = "parameter not set";
6089 if ((unsigned char)*end == CTLENDVAR) {
6090 if (varflags & VSNUL)
6096 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6099 #if ENABLE_ASH_BASH_COMPAT
6101 parse_sub_pattern(char *arg, int inquotes)
6103 char *idx, *repl = NULL;
6112 /* Only the first '/' seen is our separator */
6119 if (!inquotes && c == '\\' && arg[1] == '\\')
6120 arg++; /* skip both \\, not just first one */
6127 #endif /* ENABLE_ASH_BASH_COMPAT */
6130 subevalvar(char *p, char *str, int strloc, int subtype,
6131 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6133 struct nodelist *saveargbackq = argbackq;
6136 char *rmesc, *rmescend;
6137 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6138 IF_ASH_BASH_COMPAT(char null = '\0';)
6139 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6140 int saveherefd = herefd;
6141 int amount, workloc, resetloc;
6143 char *(*scan)(char*, char*, char*, char*, int, int);
6146 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6148 STPUTC('\0', expdest);
6149 herefd = saveherefd;
6150 argbackq = saveargbackq;
6151 startp = (char *)stackblock() + startloc;
6155 setvar(str, startp, 0);
6156 amount = startp - expdest;
6157 STADJUST(amount, expdest);
6160 #if ENABLE_ASH_BASH_COMPAT
6162 loc = str = stackblock() + strloc;
6163 /* Read POS in ${var:POS:LEN} */
6164 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6165 len = str - startp - 1;
6167 /* *loc != '\0', guaranteed by parser */
6171 /* Adjust the length by the number of escapes */
6172 for (ptr = startp; ptr < (str - 1); ptr++) {
6173 if ((unsigned char)*ptr == CTLESC) {
6181 if (*loc++ == ':') {
6185 /* Skip POS in ${var:POS:LEN} */
6187 while (*loc && *loc != ':') {
6189 * bash complains on: var=qwe; echo ${var:1a:123}
6191 ash_msg_and_raise_error(msg_illnum, str);
6195 if (*loc++ == ':') {
6199 if (pos >= orig_len) {
6203 if (len > (orig_len - pos))
6204 len = orig_len - pos;
6206 for (str = startp; pos; str++, pos--) {
6207 if (quotes && (unsigned char)*str == CTLESC)
6210 for (loc = startp; len; len--) {
6211 if (quotes && (unsigned char)*str == CTLESC)
6216 amount = loc - expdest;
6217 STADJUST(amount, expdest);
6222 varunset(p, str, startp, varflags);
6225 resetloc = expdest - (char *)stackblock();
6227 /* We'll comeback here if we grow the stack while handling
6228 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6229 * stack will need rebasing, and we'll need to remove our work
6232 IF_ASH_BASH_COMPAT(restart:)
6234 amount = expdest - ((char *)stackblock() + resetloc);
6235 STADJUST(-amount, expdest);
6236 startp = (char *)stackblock() + startloc;
6239 rmescend = (char *)stackblock() + strloc;
6241 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6242 if (rmesc != startp) {
6244 startp = (char *)stackblock() + startloc;
6248 str = (char *)stackblock() + strloc;
6249 preglob(str, varflags & VSQUOTE, 0);
6250 workloc = expdest - (char *)stackblock();
6252 #if ENABLE_ASH_BASH_COMPAT
6253 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6254 char *idx, *end, *restart_detect;
6257 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6262 /* If there's no pattern to match, return the expansion unmolested */
6270 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6272 /* No match, advance */
6273 restart_detect = stackblock();
6274 STPUTC(*idx, expdest);
6275 if (quotes && (unsigned char)*idx == CTLESC) {
6278 STPUTC(*idx, expdest);
6280 if (stackblock() != restart_detect)
6288 if (subtype == VSREPLACEALL) {
6290 if (quotes && (unsigned char)*idx == CTLESC)
6299 for (loc = repl; *loc; loc++) {
6300 restart_detect = stackblock();
6301 STPUTC(*loc, expdest);
6302 if (stackblock() != restart_detect)
6307 if (subtype == VSREPLACE) {
6309 restart_detect = stackblock();
6310 STPUTC(*idx, expdest);
6311 if (stackblock() != restart_detect)
6320 /* We've put the replaced text into a buffer at workloc, now
6321 * move it to the right place and adjust the stack.
6323 startp = stackblock() + startloc;
6324 STPUTC('\0', expdest);
6325 memmove(startp, stackblock() + workloc, len);
6326 startp[len++] = '\0';
6327 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6328 STADJUST(-amount, expdest);
6331 #endif /* ENABLE_ASH_BASH_COMPAT */
6333 subtype -= VSTRIMRIGHT;
6335 if (subtype < 0 || subtype > 7)
6338 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6339 zero = subtype >> 1;
6340 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6341 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6343 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6346 memmove(startp, loc, str - loc);
6347 loc = startp + (str - loc) - 1;
6350 amount = loc - expdest;
6351 STADJUST(amount, expdest);
6357 * Add the value of a specialized variable to the stack string.
6358 * name parameter (examples):
6359 * ash -c 'echo $1' name:'1='
6360 * ash -c 'echo $qwe' name:'qwe='
6361 * ash -c 'echo $$' name:'$='
6362 * ash -c 'echo ${$}' name:'$='
6363 * ash -c 'echo ${$##q}' name:'$=q'
6364 * ash -c 'echo ${#$}' name:'$='
6365 * note: examples with bad shell syntax:
6366 * ash -c 'echo ${#$1}' name:'$=1'
6367 * ash -c 'echo ${#1#}' name:'1=#'
6369 static NOINLINE ssize_t
6370 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6377 int subtype = varflags & VSTYPE;
6378 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6379 int quoted = varflags & VSQUOTE;
6380 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6390 num = shellparam.nparam;
6398 goto check_1char_name;
6400 expdest = makestrspace(NOPTS, expdest);
6401 for (i = NOPTS - 1; i >= 0; i--) {
6403 USTPUTC(optletters(i), expdest);
6409 /* handles cases similar to ${#$1} */
6410 if (name[2] != '\0')
6411 raise_error_syntax("bad substitution");
6418 if (quoted && (flags & EXP_FULL)) {
6419 /* note: this is not meant as PEOF value */
6420 sep = 1 << CHAR_BIT;
6425 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6426 i = SIT(sep, syntax);
6427 if (quotes && (i == CCTL || i == CBACK))
6433 while ((p = *ap++) != NULL) {
6436 partlen = strlen(p);
6439 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6440 memtodest(p, partlen, syntax, quotes);
6446 if (subtype == VSPLUS || subtype == VSLENGTH) {
6452 /* note: may put NUL despite sep != 0
6453 * (see sep = 1 << CHAR_BIT above) */
6459 } /* case '@' and '*' */
6470 num = atoi(name); /* number(name) fails on ${N#str} etc */
6471 if (num < 0 || num > shellparam.nparam)
6473 p = num ? shellparam.p[num - 1] : arg0;
6476 /* NB: name has form "VAR=..." */
6478 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6479 * which should be considered before we check variables. */
6481 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6485 str = var_str_list->text;
6486 eq = strchr(str, '=');
6487 if (!eq) /* stop at first non-assignment */
6490 if (name_len == (unsigned)(eq - str)
6491 && strncmp(str, name, name_len) == 0
6494 /* goto value; - WRONG! */
6495 /* think "A=1 A=2 B=$A" */
6497 var_str_list = var_str_list->next;
6498 } while (var_str_list);
6502 p = lookupvar(name);
6508 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6509 memtodest(p, len, syntax, quotes);
6513 if (subtype == VSPLUS || subtype == VSLENGTH)
6514 STADJUST(-len, expdest);
6519 * Expand a variable, and return a pointer to the next character in the
6523 evalvar(char *p, int flags, struct strlist *var_str_list)
6534 varflags = (unsigned char) *p++;
6535 subtype = varflags & VSTYPE;
6536 quoted = varflags & VSQUOTE;
6538 easy = (!quoted || (*var == '@' && shellparam.nparam));
6539 startloc = expdest - (char *)stackblock();
6540 p = strchr(p, '=') + 1;
6543 varlen = varvalue(var, varflags, flags, var_str_list);
6544 if (varflags & VSNUL)
6547 if (subtype == VSPLUS) {
6548 varlen = -1 - varlen;
6552 if (subtype == VSMINUS) {
6556 p, flags | EXP_TILDE |
6557 (quoted ? EXP_QWORD : EXP_WORD),
6567 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6569 if (subevalvar(p, var, /* strloc: */ 0,
6570 subtype, startloc, varflags,
6576 * Remove any recorded regions beyond
6579 removerecordregions(startloc);
6589 if (varlen < 0 && uflag)
6590 varunset(p, var, 0, 0);
6592 if (subtype == VSLENGTH) {
6593 cvtnum(varlen > 0 ? varlen : 0);
6597 if (subtype == VSNORMAL) {
6608 case VSTRIMRIGHTMAX:
6609 #if ENABLE_ASH_BASH_COMPAT
6622 * Terminate the string and start recording the pattern
6625 STPUTC('\0', expdest);
6626 patloc = expdest - (char *)stackblock();
6627 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6629 //TODO: | EXP_REDIR too? All other such places do it too
6630 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6633 int amount = expdest - (
6634 (char *)stackblock() + patloc - 1
6636 STADJUST(-amount, expdest);
6638 /* Remove any recorded regions beyond start of variable */
6639 removerecordregions(startloc);
6641 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6645 if (subtype != VSNORMAL) { /* skip to end of alternative */
6648 unsigned char c = *p++;
6651 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6653 argbackq = argbackq->next;
6654 } else if (c == CTLVAR) {
6655 if ((*p++ & VSTYPE) != VSNORMAL)
6657 } else if (c == CTLENDVAR) {
6667 * Break the argument string into pieces based upon IFS and add the
6668 * strings to the argument list. The regions of the string to be
6669 * searched for IFS characters have been stored by recordregion.
6672 ifsbreakup(char *string, struct arglist *arglist)
6674 struct ifsregion *ifsp;
6679 const char *ifs, *realifs;
6684 if (ifslastp != NULL) {
6687 realifs = ifsset() ? ifsval() : defifs;
6690 p = string + ifsp->begoff;
6691 nulonly = ifsp->nulonly;
6692 ifs = nulonly ? nullstr : realifs;
6694 while (p < string + ifsp->endoff) {
6696 if ((unsigned char)*p == CTLESC)
6698 if (!strchr(ifs, *p)) {
6703 ifsspc = (strchr(defifs, *p) != NULL);
6704 /* Ignore IFS whitespace at start */
6705 if (q == start && ifsspc) {
6711 sp = stzalloc(sizeof(*sp));
6713 *arglist->lastp = sp;
6714 arglist->lastp = &sp->next;
6718 if (p >= string + ifsp->endoff) {
6722 if ((unsigned char)*p == CTLESC)
6724 if (strchr(ifs, *p) == NULL) {
6728 if (strchr(defifs, *p) == NULL) {
6743 } while (ifsp != NULL);
6752 sp = stzalloc(sizeof(*sp));
6754 *arglist->lastp = sp;
6755 arglist->lastp = &sp->next;
6761 struct ifsregion *p;
6766 struct ifsregion *ifsp;
6772 ifsfirst.next = NULL;
6777 * Add a file name to the list.
6780 addfname(const char *name)
6784 sp = stzalloc(sizeof(*sp));
6785 sp->text = ststrdup(name);
6787 exparg.lastp = &sp->next;
6790 static char *expdir;
6793 * Do metacharacter (i.e. *, ?, [...]) expansion.
6796 expmeta(char *enddir, char *name)
6811 for (p = name; *p; p++) {
6812 if (*p == '*' || *p == '?')
6814 else if (*p == '[') {
6821 if (*q == '/' || *q == '\0')
6828 } else if (*p == '\\')
6830 else if (*p == '/') {
6837 if (metaflag == 0) { /* we've reached the end of the file name */
6838 if (enddir != expdir)
6846 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6857 } while (p < start);
6859 if (enddir == expdir) {
6861 } else if (enddir == expdir + 1 && *expdir == '/') {
6870 if (enddir != expdir)
6872 if (*endname == 0) {
6884 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6885 if (dp->d_name[0] == '.' && !matchdot)
6887 if (pmatch(start, dp->d_name)) {
6889 strcpy(enddir, dp->d_name);
6892 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6895 expmeta(p, endname);
6904 static struct strlist *
6905 msort(struct strlist *list, int len)
6907 struct strlist *p, *q = NULL;
6908 struct strlist **lpp;
6916 for (n = half; --n >= 0;) {
6920 q->next = NULL; /* terminate first half of list */
6921 q = msort(list, half); /* sort first half of list */
6922 p = msort(p, len - half); /* sort second half */
6925 #if ENABLE_LOCALE_SUPPORT
6926 if (strcoll(p->text, q->text) < 0)
6928 if (strcmp(p->text, q->text) < 0)
6952 * Sort the results of file name expansion. It calculates the number of
6953 * strings to sort and then calls msort (short for merge sort) to do the
6956 static struct strlist *
6957 expsort(struct strlist *str)
6963 for (sp = str; sp; sp = sp->next)
6965 return msort(str, len);
6969 expandmeta(struct strlist *str /*, int flag*/)
6971 static const char metachars[] ALIGN1 = {
6974 /* TODO - EXP_REDIR */
6977 struct strlist **savelastp;
6983 if (!strpbrk(str->text, metachars))
6985 savelastp = exparg.lastp;
6988 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6990 int i = strlen(str->text);
6991 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6999 if (exparg.lastp == savelastp) {
7004 *exparg.lastp = str;
7005 rmescapes(str->text, 0);
7006 exparg.lastp = &str->next;
7008 *exparg.lastp = NULL;
7009 *savelastp = sp = expsort(*savelastp);
7010 while (sp->next != NULL)
7012 exparg.lastp = &sp->next;
7019 * Perform variable substitution and command substitution on an argument,
7020 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7021 * perform splitting and file name expansion. When arglist is NULL, perform
7022 * here document expansion.
7025 expandarg(union node *arg, struct arglist *arglist, int flag)
7030 argbackq = arg->narg.backquote;
7031 STARTSTACKSTR(expdest);
7032 ifsfirst.next = NULL;
7034 argstr(arg->narg.text, flag,
7035 /* var_str_list: */ arglist ? arglist->list : NULL);
7036 p = _STPUTC('\0', expdest);
7038 if (arglist == NULL) {
7039 return; /* here document expanded */
7041 p = grabstackstr(p);
7042 exparg.lastp = &exparg.list;
7046 if (flag & EXP_FULL) {
7047 ifsbreakup(p, &exparg);
7048 *exparg.lastp = NULL;
7049 exparg.lastp = &exparg.list;
7050 expandmeta(exparg.list /*, flag*/);
7052 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7054 sp = stzalloc(sizeof(*sp));
7057 exparg.lastp = &sp->next;
7061 *exparg.lastp = NULL;
7063 *arglist->lastp = exparg.list;
7064 arglist->lastp = exparg.lastp;
7069 * Expand shell variables and backquotes inside a here document.
7072 expandhere(union node *arg, int fd)
7075 expandarg(arg, (struct arglist *)NULL, 0);
7076 full_write(fd, stackblock(), expdest - (char *)stackblock());
7080 * Returns true if the pattern matches the string.
7083 patmatch(char *pattern, const char *string)
7085 return pmatch(preglob(pattern, 0, 0), string);
7089 * See if a pattern matches in a case statement.
7092 casematch(union node *pattern, char *val)
7094 struct stackmark smark;
7097 setstackmark(&smark);
7098 argbackq = pattern->narg.backquote;
7099 STARTSTACKSTR(expdest);
7101 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7102 /* var_str_list: */ NULL);
7103 STACKSTRNUL(expdest);
7104 result = patmatch(stackblock(), val);
7105 popstackmark(&smark);
7110 /* ============ find_command */
7114 int (*builtin)(int, char **) FAST_FUNC;
7115 /* unsigned flags; */
7117 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7118 /* "regular" builtins always take precedence over commands,
7119 * regardless of PATH=....%builtin... position */
7120 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7121 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7124 smallint cmdtype; /* CMDxxx */
7127 /* index >= 0 for commands without path (slashes) */
7128 /* (TODO: what exactly does the value mean? PATH position?) */
7129 /* index == -1 for commands with slashes */
7130 /* index == (-2 - applet_no) for NOFORK applets */
7131 const struct builtincmd *cmd;
7132 struct funcnode *func;
7135 /* values of cmdtype */
7136 #define CMDUNKNOWN -1 /* no entry in table for command */
7137 #define CMDNORMAL 0 /* command is an executable program */
7138 #define CMDFUNCTION 1 /* command is a shell function */
7139 #define CMDBUILTIN 2 /* command is a shell builtin */
7141 /* action to find_command() */
7142 #define DO_ERR 0x01 /* prints errors */
7143 #define DO_ABS 0x02 /* checks absolute paths */
7144 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7145 #define DO_ALTPATH 0x08 /* using alternate path */
7146 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7148 static void find_command(char *, struct cmdentry *, int, const char *);
7151 /* ============ Hashing commands */
7154 * When commands are first encountered, they are entered in a hash table.
7155 * This ensures that a full path search will not have to be done for them
7156 * on each invocation.
7158 * We should investigate converting to a linear search, even though that
7159 * would make the command name "hash" a misnomer.
7163 struct tblentry *next; /* next entry in hash chain */
7164 union param param; /* definition of builtin function */
7165 smallint cmdtype; /* CMDxxx */
7166 char rehash; /* if set, cd done since entry created */
7167 char cmdname[1]; /* name of command */
7170 static struct tblentry **cmdtable;
7171 #define INIT_G_cmdtable() do { \
7172 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7175 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7179 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7183 #if ENABLE_FEATURE_SH_STANDALONE
7184 if (applet_no >= 0) {
7185 if (APPLET_IS_NOEXEC(applet_no)) {
7188 run_applet_no_and_exit(applet_no, argv);
7190 /* re-exec ourselves with the new arguments */
7191 execve(bb_busybox_exec_path, argv, envp);
7192 /* If they called chroot or otherwise made the binary no longer
7193 * executable, fall through */
7200 execve(cmd, argv, envp);
7201 } while (errno == EINTR);
7203 execve(cmd, argv, envp);
7209 if (errno == ENOEXEC) {
7213 for (ap = argv; *ap; ap++)
7215 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7217 ap[0] = cmd = (char *)DEFAULT_SHELL;
7220 while ((*ap++ = *argv++) != NULL)
7229 * Exec a program. Never returns. If you change this routine, you may
7230 * have to change the find_command routine as well.
7232 static void shellexec(char **, const char *, int) NORETURN;
7234 shellexec(char **argv, const char *path, int idx)
7240 #if ENABLE_FEATURE_SH_STANDALONE
7244 clearredir(/*drop:*/ 1);
7245 envp = listvars(VEXPORT, VUNSET, 0);
7246 if (strchr(argv[0], '/') != NULL
7247 #if ENABLE_FEATURE_SH_STANDALONE
7248 || (applet_no = find_applet_by_name(argv[0])) >= 0
7251 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7255 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7256 if (--idx < 0 && pathopt == NULL) {
7257 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7258 if (errno != ENOENT && errno != ENOTDIR)
7265 /* Map to POSIX errors */
7277 exitstatus = exerrno;
7278 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7279 argv[0], e, suppress_int));
7280 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7285 printentry(struct tblentry *cmdp)
7291 idx = cmdp->param.index;
7294 name = path_advance(&path, cmdp->cmdname);
7296 } while (--idx >= 0);
7297 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7301 * Clear out command entries. The argument specifies the first entry in
7302 * PATH which has changed.
7305 clearcmdentry(int firstchange)
7307 struct tblentry **tblp;
7308 struct tblentry **pp;
7309 struct tblentry *cmdp;
7312 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7314 while ((cmdp = *pp) != NULL) {
7315 if ((cmdp->cmdtype == CMDNORMAL &&
7316 cmdp->param.index >= firstchange)
7317 || (cmdp->cmdtype == CMDBUILTIN &&
7318 builtinloc >= firstchange)
7331 * Locate a command in the command hash table. If "add" is nonzero,
7332 * add the command to the table if it is not already present. The
7333 * variable "lastcmdentry" is set to point to the address of the link
7334 * pointing to the entry, so that delete_cmd_entry can delete the
7337 * Interrupts must be off if called with add != 0.
7339 static struct tblentry **lastcmdentry;
7341 static struct tblentry *
7342 cmdlookup(const char *name, int add)
7344 unsigned int hashval;
7346 struct tblentry *cmdp;
7347 struct tblentry **pp;
7350 hashval = (unsigned char)*p << 4;
7352 hashval += (unsigned char)*p++;
7354 pp = &cmdtable[hashval % CMDTABLESIZE];
7355 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7356 if (strcmp(cmdp->cmdname, name) == 0)
7360 if (add && cmdp == NULL) {
7361 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7363 /* + 1 - already done because
7364 * tblentry::cmdname is char[1] */);
7365 /*cmdp->next = NULL; - ckzalloc did it */
7366 cmdp->cmdtype = CMDUNKNOWN;
7367 strcpy(cmdp->cmdname, name);
7374 * Delete the command entry returned on the last lookup.
7377 delete_cmd_entry(void)
7379 struct tblentry *cmdp;
7382 cmdp = *lastcmdentry;
7383 *lastcmdentry = cmdp->next;
7384 if (cmdp->cmdtype == CMDFUNCTION)
7385 freefunc(cmdp->param.func);
7391 * Add a new command entry, replacing any existing command entry for
7392 * the same name - except special builtins.
7395 addcmdentry(char *name, struct cmdentry *entry)
7397 struct tblentry *cmdp;
7399 cmdp = cmdlookup(name, 1);
7400 if (cmdp->cmdtype == CMDFUNCTION) {
7401 freefunc(cmdp->param.func);
7403 cmdp->cmdtype = entry->cmdtype;
7404 cmdp->param = entry->u;
7408 static int FAST_FUNC
7409 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7411 struct tblentry **pp;
7412 struct tblentry *cmdp;
7414 struct cmdentry entry;
7417 if (nextopt("r") != '\0') {
7422 if (*argptr == NULL) {
7423 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7424 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7425 if (cmdp->cmdtype == CMDNORMAL)
7433 while ((name = *argptr) != NULL) {
7434 cmdp = cmdlookup(name, 0);
7436 && (cmdp->cmdtype == CMDNORMAL
7437 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7441 find_command(name, &entry, DO_ERR, pathval());
7442 if (entry.cmdtype == CMDUNKNOWN)
7450 * Called when a cd is done. Marks all commands so the next time they
7451 * are executed they will be rehashed.
7456 struct tblentry **pp;
7457 struct tblentry *cmdp;
7459 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7460 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7461 if (cmdp->cmdtype == CMDNORMAL
7462 || (cmdp->cmdtype == CMDBUILTIN
7463 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7473 * Fix command hash table when PATH changed.
7474 * Called before PATH is changed. The argument is the new value of PATH;
7475 * pathval() still returns the old value at this point.
7476 * Called with interrupts off.
7478 static void FAST_FUNC
7479 changepath(const char *new)
7487 firstchange = 9999; /* assume no change */
7493 if ((*old == '\0' && *new == ':')
7494 || (*old == ':' && *new == '\0'))
7496 old = new; /* ignore subsequent differences */
7500 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7506 if (builtinloc < 0 && idx_bltin >= 0)
7507 builtinloc = idx_bltin; /* zap builtins */
7508 if (builtinloc >= 0 && idx_bltin < 0)
7510 clearcmdentry(firstchange);
7511 builtinloc = idx_bltin;
7526 #define TENDBQUOTE 12
7543 typedef smallint token_id_t;
7545 /* first char is indicating which tokens mark the end of a list */
7546 static const char *const tokname_array[] = {
7560 #define KWDOFFSET 13
7561 /* the following are keywords */
7583 static char buf[16];
7586 //if (tok < TSEMI) return tokname_array[tok] + 1;
7587 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7592 sprintf(buf + (tok >= TSEMI), "%s%c",
7593 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7597 /* Wrapper around strcmp for qsort/bsearch/... */
7599 pstrcmp(const void *a, const void *b)
7601 return strcmp((char*) a, (*(char**) b) + 1);
7604 static const char *const *
7605 findkwd(const char *s)
7607 return bsearch(s, tokname_array + KWDOFFSET,
7608 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7609 sizeof(tokname_array[0]), pstrcmp);
7613 * Locate and print what a word is...
7616 describe_command(char *command, int describe_command_verbose)
7618 struct cmdentry entry;
7619 struct tblentry *cmdp;
7620 #if ENABLE_ASH_ALIAS
7621 const struct alias *ap;
7623 const char *path = pathval();
7625 if (describe_command_verbose) {
7629 /* First look at the keywords */
7630 if (findkwd(command)) {
7631 out1str(describe_command_verbose ? " is a shell keyword" : command);
7635 #if ENABLE_ASH_ALIAS
7636 /* Then look at the aliases */
7637 ap = lookupalias(command, 0);
7639 if (!describe_command_verbose) {
7644 out1fmt(" is an alias for %s", ap->val);
7648 /* Then check if it is a tracked alias */
7649 cmdp = cmdlookup(command, 0);
7651 entry.cmdtype = cmdp->cmdtype;
7652 entry.u = cmdp->param;
7654 /* Finally use brute force */
7655 find_command(command, &entry, DO_ABS, path);
7658 switch (entry.cmdtype) {
7660 int j = entry.u.index;
7666 p = path_advance(&path, command);
7670 if (describe_command_verbose) {
7672 (cmdp ? " a tracked alias for" : nullstr), p
7681 if (describe_command_verbose) {
7682 out1str(" is a shell function");
7689 if (describe_command_verbose) {
7690 out1fmt(" is a %sshell builtin",
7691 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7692 "special " : nullstr
7700 if (describe_command_verbose) {
7701 out1str(": not found\n");
7710 static int FAST_FUNC
7711 typecmd(int argc UNUSED_PARAM, char **argv)
7717 /* type -p ... ? (we don't bother checking for 'p') */
7718 if (argv[1] && argv[1][0] == '-') {
7723 err |= describe_command(argv[i++], verbose);
7728 #if ENABLE_ASH_CMDCMD
7729 static int FAST_FUNC
7730 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7738 while ((c = nextopt("pvV")) != '\0')
7740 verify |= VERIFY_VERBOSE;
7742 verify |= VERIFY_BRIEF;
7747 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7748 if (verify && (*argptr != NULL)) {
7749 return describe_command(*argptr, verify - VERIFY_BRIEF);
7757 /* ============ eval.c */
7759 static int funcblocksize; /* size of structures in function */
7760 static int funcstringsize; /* size of strings in node */
7761 static void *funcblock; /* block to allocate function from */
7762 static char *funcstring; /* block to allocate strings from */
7764 /* flags in argument to evaltree */
7765 #define EV_EXIT 01 /* exit after evaluating tree */
7766 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7767 #define EV_BACKCMD 04 /* command executing within back quotes */
7769 static const uint8_t nodesize[N_NUMBER] = {
7770 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7771 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7772 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7773 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7774 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7775 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7776 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7777 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7778 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7779 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7780 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7781 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7782 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7783 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7784 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7785 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7786 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7787 #if ENABLE_ASH_BASH_COMPAT
7788 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7790 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7791 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7792 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7793 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7794 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7795 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7796 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7797 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7798 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7801 static void calcsize(union node *n);
7804 sizenodelist(struct nodelist *lp)
7807 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7814 calcsize(union node *n)
7818 funcblocksize += nodesize[n->type];
7821 calcsize(n->ncmd.redirect);
7822 calcsize(n->ncmd.args);
7823 calcsize(n->ncmd.assign);
7826 sizenodelist(n->npipe.cmdlist);
7831 calcsize(n->nredir.redirect);
7832 calcsize(n->nredir.n);
7839 calcsize(n->nbinary.ch2);
7840 calcsize(n->nbinary.ch1);
7843 calcsize(n->nif.elsepart);
7844 calcsize(n->nif.ifpart);
7845 calcsize(n->nif.test);
7848 funcstringsize += strlen(n->nfor.var) + 1;
7849 calcsize(n->nfor.body);
7850 calcsize(n->nfor.args);
7853 calcsize(n->ncase.cases);
7854 calcsize(n->ncase.expr);
7857 calcsize(n->nclist.body);
7858 calcsize(n->nclist.pattern);
7859 calcsize(n->nclist.next);
7863 sizenodelist(n->narg.backquote);
7864 funcstringsize += strlen(n->narg.text) + 1;
7865 calcsize(n->narg.next);
7868 #if ENABLE_ASH_BASH_COMPAT
7875 calcsize(n->nfile.fname);
7876 calcsize(n->nfile.next);
7880 calcsize(n->ndup.vname);
7881 calcsize(n->ndup.next);
7885 calcsize(n->nhere.doc);
7886 calcsize(n->nhere.next);
7889 calcsize(n->nnot.com);
7895 nodeckstrdup(char *s)
7897 char *rtn = funcstring;
7899 strcpy(funcstring, s);
7900 funcstring += strlen(s) + 1;
7904 static union node *copynode(union node *);
7906 static struct nodelist *
7907 copynodelist(struct nodelist *lp)
7909 struct nodelist *start;
7910 struct nodelist **lpp;
7915 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7916 (*lpp)->n = copynode(lp->n);
7918 lpp = &(*lpp)->next;
7925 copynode(union node *n)
7932 funcblock = (char *) funcblock + nodesize[n->type];
7936 new->ncmd.redirect = copynode(n->ncmd.redirect);
7937 new->ncmd.args = copynode(n->ncmd.args);
7938 new->ncmd.assign = copynode(n->ncmd.assign);
7941 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7942 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7947 new->nredir.redirect = copynode(n->nredir.redirect);
7948 new->nredir.n = copynode(n->nredir.n);
7955 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7956 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7959 new->nif.elsepart = copynode(n->nif.elsepart);
7960 new->nif.ifpart = copynode(n->nif.ifpart);
7961 new->nif.test = copynode(n->nif.test);
7964 new->nfor.var = nodeckstrdup(n->nfor.var);
7965 new->nfor.body = copynode(n->nfor.body);
7966 new->nfor.args = copynode(n->nfor.args);
7969 new->ncase.cases = copynode(n->ncase.cases);
7970 new->ncase.expr = copynode(n->ncase.expr);
7973 new->nclist.body = copynode(n->nclist.body);
7974 new->nclist.pattern = copynode(n->nclist.pattern);
7975 new->nclist.next = copynode(n->nclist.next);
7979 new->narg.backquote = copynodelist(n->narg.backquote);
7980 new->narg.text = nodeckstrdup(n->narg.text);
7981 new->narg.next = copynode(n->narg.next);
7984 #if ENABLE_ASH_BASH_COMPAT
7991 new->nfile.fname = copynode(n->nfile.fname);
7992 new->nfile.fd = n->nfile.fd;
7993 new->nfile.next = copynode(n->nfile.next);
7997 new->ndup.vname = copynode(n->ndup.vname);
7998 new->ndup.dupfd = n->ndup.dupfd;
7999 new->ndup.fd = n->ndup.fd;
8000 new->ndup.next = copynode(n->ndup.next);
8004 new->nhere.doc = copynode(n->nhere.doc);
8005 new->nhere.fd = n->nhere.fd;
8006 new->nhere.next = copynode(n->nhere.next);
8009 new->nnot.com = copynode(n->nnot.com);
8012 new->type = n->type;
8017 * Make a copy of a parse tree.
8019 static struct funcnode *
8020 copyfunc(union node *n)
8025 funcblocksize = offsetof(struct funcnode, n);
8028 blocksize = funcblocksize;
8029 f = ckmalloc(blocksize + funcstringsize);
8030 funcblock = (char *) f + offsetof(struct funcnode, n);
8031 funcstring = (char *) f + blocksize;
8038 * Define a shell function.
8041 defun(char *name, union node *func)
8043 struct cmdentry entry;
8046 entry.cmdtype = CMDFUNCTION;
8047 entry.u.func = copyfunc(func);
8048 addcmdentry(name, &entry);
8052 /* Reasons for skipping commands (see comment on breakcmd routine) */
8053 #define SKIPBREAK (1 << 0)
8054 #define SKIPCONT (1 << 1)
8055 #define SKIPFUNC (1 << 2)
8056 #define SKIPFILE (1 << 3)
8057 #define SKIPEVAL (1 << 4)
8058 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8059 static int skipcount; /* number of levels to skip */
8060 static int funcnest; /* depth of function calls */
8061 static int loopnest; /* current loop nesting level */
8063 /* Forward decl way out to parsing code - dotrap needs it */
8064 static int evalstring(char *s, int mask);
8066 /* Called to execute a trap.
8067 * Single callsite - at the end of evaltree().
8068 * If we return non-zero, exaltree raises EXEXIT exception.
8070 * Perhaps we should avoid entering new trap handlers
8071 * while we are executing a trap handler. [is it a TODO?]
8080 savestatus = exitstatus;
8084 TRACE(("dotrap entered\n"));
8085 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8092 /* non-trapped SIGINT is handled separately by raise_interrupt,
8093 * don't upset it by resetting gotsig[SIGINT-1] */
8094 if (sig == SIGINT && !t)
8097 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8101 want_exexit = evalstring(t, SKIPEVAL);
8102 exitstatus = savestatus;
8104 TRACE(("dotrap returns %d\n", want_exexit));
8109 TRACE(("dotrap returns 0\n"));
8113 /* forward declarations - evaluation is fairly recursive business... */
8114 static void evalloop(union node *, int);
8115 static void evalfor(union node *, int);
8116 static void evalcase(union node *, int);
8117 static void evalsubshell(union node *, int);
8118 static void expredir(union node *);
8119 static void evalpipe(union node *, int);
8120 static void evalcommand(union node *, int);
8121 static int evalbltin(const struct builtincmd *, int, char **);
8122 static void prehash(union node *);
8125 * Evaluate a parse tree. The value is left in the global variable
8129 evaltree(union node *n, int flags)
8131 struct jmploc *volatile savehandler = exception_handler;
8132 struct jmploc jmploc;
8134 void (*evalfn)(union node *, int);
8138 SAVE_INT(int_level);
8141 TRACE(("evaltree(NULL) called\n"));
8144 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8146 exception_handler = &jmploc;
8148 int err = setjmp(jmploc.loc);
8150 /* if it was a signal, check for trap handlers */
8151 if (exception_type == EXSIG) {
8152 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8153 exception_type, err));
8156 /* continue on the way out */
8157 TRACE(("exception %d in evaltree, propagating err=%d\n",
8158 exception_type, err));
8159 exception_handler = savehandler;
8160 longjmp(exception_handler->loc, err);
8167 out1fmt("Node type = %d\n", n->type);
8172 evaltree(n->nnot.com, EV_TESTED);
8173 status = !exitstatus;
8176 expredir(n->nredir.redirect);
8177 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8179 evaltree(n->nredir.n, flags & EV_TESTED);
8180 status = exitstatus;
8182 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8185 evalfn = evalcommand;
8187 if (eflag && !(flags & EV_TESTED))
8199 evalfn = evalsubshell;
8212 #error NAND + 1 != NOR
8214 #if NOR + 1 != NSEMI
8215 #error NOR + 1 != NSEMI
8217 unsigned is_or = n->type - NAND;
8220 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8222 if (!exitstatus == is_or)
8235 evaltree(n->nif.test, EV_TESTED);
8238 if (exitstatus == 0) {
8242 if (n->nif.elsepart) {
8243 n = n->nif.elsepart;
8248 defun(n->narg.text, n->narg.next);
8252 exitstatus = status;
8257 exception_handler = savehandler;
8259 if (checkexit & exitstatus)
8260 evalskip |= SKIPEVAL;
8261 else if (pending_sig && dotrap())
8264 if (flags & EV_EXIT) {
8266 raise_exception(EXEXIT);
8269 RESTORE_INT(int_level);
8270 TRACE(("leaving evaltree (no interrupts)\n"));
8273 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8276 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8279 evalloop(union node *n, int flags)
8289 evaltree(n->nbinary.ch1, EV_TESTED);
8292 if (evalskip == SKIPCONT && --skipcount <= 0) {
8296 if (evalskip == SKIPBREAK && --skipcount <= 0)
8301 if (n->type != NWHILE)
8305 evaltree(n->nbinary.ch2, flags);
8306 status = exitstatus;
8311 exitstatus = status;
8315 evalfor(union node *n, int flags)
8317 struct arglist arglist;
8320 struct stackmark smark;
8322 setstackmark(&smark);
8323 arglist.list = NULL;
8324 arglist.lastp = &arglist.list;
8325 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8326 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8331 *arglist.lastp = NULL;
8336 for (sp = arglist.list; sp; sp = sp->next) {
8337 setvar(n->nfor.var, sp->text, 0);
8338 evaltree(n->nfor.body, flags);
8340 if (evalskip == SKIPCONT && --skipcount <= 0) {
8344 if (evalskip == SKIPBREAK && --skipcount <= 0)
8351 popstackmark(&smark);
8355 evalcase(union node *n, int flags)
8359 struct arglist arglist;
8360 struct stackmark smark;
8362 setstackmark(&smark);
8363 arglist.list = NULL;
8364 arglist.lastp = &arglist.list;
8365 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8367 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8368 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8369 if (casematch(patp, arglist.list->text)) {
8370 if (evalskip == 0) {
8371 evaltree(cp->nclist.body, flags);
8378 popstackmark(&smark);
8382 * Kick off a subshell to evaluate a tree.
8385 evalsubshell(union node *n, int flags)
8388 int backgnd = (n->type == NBACKGND);
8391 expredir(n->nredir.redirect);
8392 if (!backgnd && flags & EV_EXIT && !trap[0])
8395 jp = makejob(/*n,*/ 1);
8396 if (forkshell(jp, n, backgnd) == 0) {
8400 flags &=~ EV_TESTED;
8402 redirect(n->nredir.redirect, 0);
8403 evaltreenr(n->nredir.n, flags);
8408 status = waitforjob(jp);
8409 exitstatus = status;
8414 * Compute the names of the files in a redirection list.
8416 static void fixredir(union node *, const char *, int);
8418 expredir(union node *n)
8422 for (redir = n; redir; redir = redir->nfile.next) {
8426 fn.lastp = &fn.list;
8427 switch (redir->type) {
8431 #if ENABLE_ASH_BASH_COMPAT
8436 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8437 #if ENABLE_ASH_BASH_COMPAT
8440 redir->nfile.expfname = fn.list->text;
8443 case NTOFD: /* >& */
8444 if (redir->ndup.vname) {
8445 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8446 if (fn.list == NULL)
8447 ash_msg_and_raise_error("redir error");
8448 #if ENABLE_ASH_BASH_COMPAT
8449 //FIXME: we used expandarg with different args!
8450 if (!isdigit_str9(fn.list->text)) {
8451 /* >&file, not >&fd */
8452 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8453 ash_msg_and_raise_error("redir error");
8455 goto store_expfname;
8458 fixredir(redir, fn.list->text, 1);
8466 * Evaluate a pipeline. All the processes in the pipeline are children
8467 * of the process creating the pipeline. (This differs from some versions
8468 * of the shell, which make the last process in a pipeline the parent
8472 evalpipe(union node *n, int flags)
8475 struct nodelist *lp;
8480 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8482 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8486 jp = makejob(/*n,*/ pipelen);
8488 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8492 if (pipe(pip) < 0) {
8494 ash_msg_and_raise_error("pipe call failed");
8497 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8510 evaltreenr(lp->n, flags);
8516 /* Don't want to trigger debugging */
8520 if (n->npipe.pipe_backgnd == 0) {
8521 exitstatus = waitforjob(jp);
8522 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8528 * Controls whether the shell is interactive or not.
8531 setinteractive(int on)
8533 static smallint is_interactive;
8535 if (++on == is_interactive)
8537 is_interactive = on;
8541 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8542 if (is_interactive > 1) {
8543 /* Looks like they want an interactive shell */
8544 static smallint did_banner;
8547 /* note: ash and hush share this string */
8548 out1fmt("\n\n%s %s\n"
8549 "Enter 'help' for a list of built-in commands."
8552 "built-in shell (ash)"
8566 setinteractive(iflag);
8568 #if ENABLE_FEATURE_EDITING_VI
8570 line_input_state->flags |= VI_MODE;
8572 line_input_state->flags &= ~VI_MODE;
8574 viflag = 0; /* forcibly keep the option off */
8578 static struct localvar *localvars;
8581 * Called after a function returns.
8582 * Interrupts must be off.
8587 struct localvar *lvp;
8590 while ((lvp = localvars) != NULL) {
8591 localvars = lvp->next;
8593 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8594 if (vp == NULL) { /* $- saved */
8595 memcpy(optlist, lvp->text, sizeof(optlist));
8596 free((char*)lvp->text);
8598 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8602 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8603 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8604 free((char*)vp->text);
8605 vp->flags = lvp->flags;
8606 vp->text = lvp->text;
8613 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8615 volatile struct shparam saveparam;
8616 struct localvar *volatile savelocalvars;
8617 struct jmploc *volatile savehandler;
8618 struct jmploc jmploc;
8621 saveparam = shellparam;
8622 savelocalvars = localvars;
8623 e = setjmp(jmploc.loc);
8628 savehandler = exception_handler;
8629 exception_handler = &jmploc;
8631 shellparam.malloced = 0;
8635 shellparam.nparam = argc - 1;
8636 shellparam.p = argv + 1;
8637 #if ENABLE_ASH_GETOPTS
8638 shellparam.optind = 1;
8639 shellparam.optoff = -1;
8641 evaltree(&func->n, flags & EV_TESTED);
8647 localvars = savelocalvars;
8648 freeparam(&shellparam);
8649 shellparam = saveparam;
8650 exception_handler = savehandler;
8652 evalskip &= ~SKIPFUNC;
8656 #if ENABLE_ASH_CMDCMD
8658 parse_command_args(char **argv, const char **path)
8671 if (c == '-' && !*cp) {
8678 *path = bb_default_path;
8681 /* run 'typecmd' for other options */
8692 * Make a variable a local variable. When a variable is made local, it's
8693 * value and flags are saved in a localvar structure. The saved values
8694 * will be restored when the shell function returns. We handle the name
8695 * "-" as a special case.
8700 struct localvar *lvp;
8705 lvp = ckzalloc(sizeof(struct localvar));
8706 if (LONE_DASH(name)) {
8708 p = ckmalloc(sizeof(optlist));
8709 lvp->text = memcpy(p, optlist, sizeof(optlist));
8714 vpp = hashvar(name);
8715 vp = *findvar(vpp, name);
8716 eq = strchr(name, '=');
8719 setvareq(name, VSTRFIXED);
8721 setvar(name, NULL, VSTRFIXED);
8722 vp = *vpp; /* the new variable */
8723 lvp->flags = VUNSET;
8725 lvp->text = vp->text;
8726 lvp->flags = vp->flags;
8727 vp->flags |= VSTRFIXED|VTEXTFIXED;
8733 lvp->next = localvars;
8739 * The "local" command.
8741 static int FAST_FUNC
8742 localcmd(int argc UNUSED_PARAM, char **argv)
8747 while ((name = *argv++) != NULL) {
8753 static int FAST_FUNC
8754 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8759 static int FAST_FUNC
8760 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8765 static int FAST_FUNC
8766 execcmd(int argc UNUSED_PARAM, char **argv)
8769 iflag = 0; /* exit on error */
8772 shellexec(argv + 1, pathval(), 0);
8778 * The return command.
8780 static int FAST_FUNC
8781 returncmd(int argc UNUSED_PARAM, char **argv)
8784 * If called outside a function, do what ksh does;
8785 * skip the rest of the file.
8787 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8788 return argv[1] ? number(argv[1]) : exitstatus;
8791 /* Forward declarations for builtintab[] */
8792 static int breakcmd(int, char **) FAST_FUNC;
8793 static int dotcmd(int, char **) FAST_FUNC;
8794 static int evalcmd(int, char **) FAST_FUNC;
8795 static int exitcmd(int, char **) FAST_FUNC;
8796 static int exportcmd(int, char **) FAST_FUNC;
8797 #if ENABLE_ASH_GETOPTS
8798 static int getoptscmd(int, char **) FAST_FUNC;
8800 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8801 static int helpcmd(int, char **) FAST_FUNC;
8803 #if ENABLE_SH_MATH_SUPPORT
8804 static int letcmd(int, char **) FAST_FUNC;
8806 static int readcmd(int, char **) FAST_FUNC;
8807 static int setcmd(int, char **) FAST_FUNC;
8808 static int shiftcmd(int, char **) FAST_FUNC;
8809 static int timescmd(int, char **) FAST_FUNC;
8810 static int trapcmd(int, char **) FAST_FUNC;
8811 static int umaskcmd(int, char **) FAST_FUNC;
8812 static int unsetcmd(int, char **) FAST_FUNC;
8813 static int ulimitcmd(int, char **) FAST_FUNC;
8815 #define BUILTIN_NOSPEC "0"
8816 #define BUILTIN_SPECIAL "1"
8817 #define BUILTIN_REGULAR "2"
8818 #define BUILTIN_SPEC_REG "3"
8819 #define BUILTIN_ASSIGN "4"
8820 #define BUILTIN_SPEC_ASSG "5"
8821 #define BUILTIN_REG_ASSG "6"
8822 #define BUILTIN_SPEC_REG_ASSG "7"
8824 /* Stubs for calling non-FAST_FUNC's */
8825 #if ENABLE_ASH_BUILTIN_ECHO
8826 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8828 #if ENABLE_ASH_BUILTIN_PRINTF
8829 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8831 #if ENABLE_ASH_BUILTIN_TEST
8832 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8835 /* Keep these in proper order since it is searched via bsearch() */
8836 static const struct builtincmd builtintab[] = {
8837 { BUILTIN_SPEC_REG ".", dotcmd },
8838 { BUILTIN_SPEC_REG ":", truecmd },
8839 #if ENABLE_ASH_BUILTIN_TEST
8840 { BUILTIN_REGULAR "[", testcmd },
8841 #if ENABLE_ASH_BASH_COMPAT
8842 { BUILTIN_REGULAR "[[", testcmd },
8845 #if ENABLE_ASH_ALIAS
8846 { BUILTIN_REG_ASSG "alias", aliascmd },
8849 { BUILTIN_REGULAR "bg", fg_bgcmd },
8851 { BUILTIN_SPEC_REG "break", breakcmd },
8852 { BUILTIN_REGULAR "cd", cdcmd },
8853 { BUILTIN_NOSPEC "chdir", cdcmd },
8854 #if ENABLE_ASH_CMDCMD
8855 { BUILTIN_REGULAR "command", commandcmd },
8857 { BUILTIN_SPEC_REG "continue", breakcmd },
8858 #if ENABLE_ASH_BUILTIN_ECHO
8859 { BUILTIN_REGULAR "echo", echocmd },
8861 { BUILTIN_SPEC_REG "eval", evalcmd },
8862 { BUILTIN_SPEC_REG "exec", execcmd },
8863 { BUILTIN_SPEC_REG "exit", exitcmd },
8864 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8865 { BUILTIN_REGULAR "false", falsecmd },
8867 { BUILTIN_REGULAR "fg", fg_bgcmd },
8869 #if ENABLE_ASH_GETOPTS
8870 { BUILTIN_REGULAR "getopts", getoptscmd },
8872 { BUILTIN_NOSPEC "hash", hashcmd },
8873 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8874 { BUILTIN_NOSPEC "help", helpcmd },
8877 { BUILTIN_REGULAR "jobs", jobscmd },
8878 { BUILTIN_REGULAR "kill", killcmd },
8880 #if ENABLE_SH_MATH_SUPPORT
8881 { BUILTIN_NOSPEC "let", letcmd },
8883 { BUILTIN_ASSIGN "local", localcmd },
8884 #if ENABLE_ASH_BUILTIN_PRINTF
8885 { BUILTIN_REGULAR "printf", printfcmd },
8887 { BUILTIN_NOSPEC "pwd", pwdcmd },
8888 { BUILTIN_REGULAR "read", readcmd },
8889 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8890 { BUILTIN_SPEC_REG "return", returncmd },
8891 { BUILTIN_SPEC_REG "set", setcmd },
8892 { BUILTIN_SPEC_REG "shift", shiftcmd },
8893 { BUILTIN_SPEC_REG "source", dotcmd },
8894 #if ENABLE_ASH_BUILTIN_TEST
8895 { BUILTIN_REGULAR "test", testcmd },
8897 { BUILTIN_SPEC_REG "times", timescmd },
8898 { BUILTIN_SPEC_REG "trap", trapcmd },
8899 { BUILTIN_REGULAR "true", truecmd },
8900 { BUILTIN_NOSPEC "type", typecmd },
8901 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8902 { BUILTIN_REGULAR "umask", umaskcmd },
8903 #if ENABLE_ASH_ALIAS
8904 { BUILTIN_REGULAR "unalias", unaliascmd },
8906 { BUILTIN_SPEC_REG "unset", unsetcmd },
8907 { BUILTIN_REGULAR "wait", waitcmd },
8910 /* Should match the above table! */
8911 #define COMMANDCMD (builtintab + \
8913 1 * ENABLE_ASH_BUILTIN_TEST + \
8914 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8915 1 * ENABLE_ASH_ALIAS + \
8916 1 * ENABLE_ASH_JOB_CONTROL + \
8918 #define EXECCMD (builtintab + \
8920 1 * ENABLE_ASH_BUILTIN_TEST + \
8921 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8922 1 * ENABLE_ASH_ALIAS + \
8923 1 * ENABLE_ASH_JOB_CONTROL + \
8925 1 * ENABLE_ASH_CMDCMD + \
8927 ENABLE_ASH_BUILTIN_ECHO + \
8931 * Search the table of builtin commands.
8933 static struct builtincmd *
8934 find_builtin(const char *name)
8936 struct builtincmd *bp;
8939 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8946 * Execute a simple command.
8949 isassignment(const char *p)
8951 const char *q = endofname(p);
8956 static int FAST_FUNC
8957 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8959 /* Preserve exitstatus of a previous possible redirection
8960 * as POSIX mandates */
8961 return back_exitstatus;
8964 evalcommand(union node *cmd, int flags)
8966 static const struct builtincmd null_bltin = {
8967 "\0\0", bltincmd /* why three NULs? */
8969 struct stackmark smark;
8971 struct arglist arglist;
8972 struct arglist varlist;
8975 const struct strlist *sp;
8976 struct cmdentry cmdentry;
8983 struct builtincmd *bcmd;
8984 smallint cmd_is_exec;
8985 smallint pseudovarflag = 0;
8987 /* First expand the arguments. */
8988 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8989 setstackmark(&smark);
8990 back_exitstatus = 0;
8992 cmdentry.cmdtype = CMDBUILTIN;
8993 cmdentry.u.cmd = &null_bltin;
8994 varlist.lastp = &varlist.list;
8995 *varlist.lastp = NULL;
8996 arglist.lastp = &arglist.list;
8997 *arglist.lastp = NULL;
9000 if (cmd->ncmd.args) {
9001 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9002 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9005 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9006 struct strlist **spp;
9008 spp = arglist.lastp;
9009 if (pseudovarflag && isassignment(argp->narg.text))
9010 expandarg(argp, &arglist, EXP_VARTILDE);
9012 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9014 for (sp = *spp; sp; sp = sp->next)
9018 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9019 for (sp = arglist.list; sp; sp = sp->next) {
9020 TRACE(("evalcommand arg: %s\n", sp->text));
9021 *nargv++ = sp->text;
9026 if (iflag && funcnest == 0 && argc > 0)
9027 lastarg = nargv[-1];
9030 expredir(cmd->ncmd.redirect);
9031 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9034 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9035 struct strlist **spp;
9038 spp = varlist.lastp;
9039 expandarg(argp, &varlist, EXP_VARTILDE);
9042 * Modify the command lookup path, if a PATH= assignment
9046 if (varequal(p, path))
9050 /* Print the command if xflag is set. */
9053 const char *p = " %s";
9056 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9059 for (n = 0; n < 2; n++) {
9061 fdprintf(preverrout_fd, p, sp->text);
9069 safe_write(preverrout_fd, "\n", 1);
9075 /* Now locate the command. */
9077 const char *oldpath;
9078 int cmd_flag = DO_ERR;
9083 find_command(argv[0], &cmdentry, cmd_flag, path);
9084 if (cmdentry.cmdtype == CMDUNKNOWN) {
9085 flush_stdout_stderr();
9090 /* implement bltin and command here */
9091 if (cmdentry.cmdtype != CMDBUILTIN)
9094 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9095 if (cmdentry.u.cmd == EXECCMD)
9097 #if ENABLE_ASH_CMDCMD
9098 if (cmdentry.u.cmd == COMMANDCMD) {
9100 nargv = parse_command_args(argv, &path);
9103 argc -= nargv - argv;
9105 cmd_flag |= DO_NOFUNC;
9113 /* We have a redirection error. */
9115 raise_exception(EXERROR);
9117 exitstatus = status;
9121 /* Execute the command. */
9122 switch (cmdentry.cmdtype) {
9125 #if ENABLE_FEATURE_SH_NOFORK
9126 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9127 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9129 /* find_command() encodes applet_no as (-2 - applet_no) */
9130 int applet_no = (- cmdentry.u.index - 2);
9131 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9132 listsetvar(varlist.list, VEXPORT|VSTACK);
9133 /* run <applet>_main() */
9134 exitstatus = run_nofork_applet(applet_no, argv);
9139 /* Fork off a child process if necessary. */
9140 if (!(flags & EV_EXIT) || trap[0]) {
9142 jp = makejob(/*cmd,*/ 1);
9143 if (forkshell(jp, cmd, FORK_FG) != 0) {
9144 exitstatus = waitforjob(jp);
9146 TRACE(("forked child exited with %d\n", exitstatus));
9151 listsetvar(varlist.list, VEXPORT|VSTACK);
9152 shellexec(argv, path, cmdentry.u.index);
9156 cmdenviron = varlist.list;
9158 struct strlist *list = cmdenviron;
9160 if (spclbltin > 0 || argc == 0) {
9162 if (cmd_is_exec && argc > 1)
9165 listsetvar(list, i);
9167 /* Tight loop with builtins only:
9168 * "while kill -0 $child; do true; done"
9169 * will never exit even if $child died, unless we do this
9170 * to reap the zombie and make kill detect that it's gone: */
9171 dowait(DOWAIT_NONBLOCK, NULL);
9173 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9175 int i = exception_type;
9180 exit_status = 128 + SIGINT;
9182 exit_status = 128 + pending_sig;
9183 exitstatus = exit_status;
9184 if (i == EXINT || spclbltin > 0) {
9186 longjmp(exception_handler->loc, 1);
9193 listsetvar(varlist.list, 0);
9194 /* See above for the rationale */
9195 dowait(DOWAIT_NONBLOCK, NULL);
9196 if (evalfun(cmdentry.u.func, argc, argv, flags))
9202 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9204 /* dsl: I think this is intended to be used to support
9205 * '_' in 'vi' command mode during line editing...
9206 * However I implemented that within libedit itself.
9208 setvar("_", lastarg, 0);
9210 popstackmark(&smark);
9214 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9216 char *volatile savecmdname;
9217 struct jmploc *volatile savehandler;
9218 struct jmploc jmploc;
9221 savecmdname = commandname;
9222 i = setjmp(jmploc.loc);
9225 savehandler = exception_handler;
9226 exception_handler = &jmploc;
9227 commandname = argv[0];
9229 optptr = NULL; /* initialize nextopt */
9230 exitstatus = (*cmd->builtin)(argc, argv);
9231 flush_stdout_stderr();
9233 exitstatus |= ferror(stdout);
9235 commandname = savecmdname;
9236 exception_handler = savehandler;
9242 goodname(const char *p)
9244 return !*endofname(p);
9249 * Search for a command. This is called before we fork so that the
9250 * location of the command will be available in the parent as well as
9251 * the child. The check for "goodname" is an overly conservative
9252 * check that the name will not be subject to expansion.
9255 prehash(union node *n)
9257 struct cmdentry entry;
9259 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9260 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9264 /* ============ Builtin commands
9266 * Builtin commands whose functions are closely tied to evaluation
9267 * are implemented here.
9271 * Handle break and continue commands. Break, continue, and return are
9272 * all handled by setting the evalskip flag. The evaluation routines
9273 * above all check this flag, and if it is set they start skipping
9274 * commands rather than executing them. The variable skipcount is
9275 * the number of loops to break/continue, or the number of function
9276 * levels to return. (The latter is always 1.) It should probably
9277 * be an error to break out of more loops than exist, but it isn't
9278 * in the standard shell so we don't make it one here.
9280 static int FAST_FUNC
9281 breakcmd(int argc UNUSED_PARAM, char **argv)
9283 int n = argv[1] ? number(argv[1]) : 1;
9286 ash_msg_and_raise_error(msg_illnum, argv[1]);
9290 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9297 /* ============ input.c
9299 * This implements the input routines used by the parser.
9303 INPUT_PUSH_FILE = 1,
9304 INPUT_NOFILE_OK = 2,
9307 static smallint checkkwd;
9308 /* values of checkkwd variable */
9309 #define CHKALIAS 0x1
9314 * Push a string back onto the input at this current parsefile level.
9315 * We handle aliases this way.
9317 #if !ENABLE_ASH_ALIAS
9318 #define pushstring(s, ap) pushstring(s)
9321 pushstring(char *s, struct alias *ap)
9328 if (g_parsefile->strpush) {
9329 sp = ckzalloc(sizeof(*sp));
9330 sp->prev = g_parsefile->strpush;
9332 sp = &(g_parsefile->basestrpush);
9334 g_parsefile->strpush = sp;
9335 sp->prev_string = g_parsefile->next_to_pgetc;
9336 sp->prev_left_in_line = g_parsefile->left_in_line;
9337 #if ENABLE_ASH_ALIAS
9340 ap->flag |= ALIASINUSE;
9344 g_parsefile->next_to_pgetc = s;
9345 g_parsefile->left_in_line = len;
9352 struct strpush *sp = g_parsefile->strpush;
9355 #if ENABLE_ASH_ALIAS
9357 if (g_parsefile->next_to_pgetc[-1] == ' '
9358 || g_parsefile->next_to_pgetc[-1] == '\t'
9360 checkkwd |= CHKALIAS;
9362 if (sp->string != sp->ap->val) {
9365 sp->ap->flag &= ~ALIASINUSE;
9366 if (sp->ap->flag & ALIASDEAD) {
9367 unalias(sp->ap->name);
9371 g_parsefile->next_to_pgetc = sp->prev_string;
9372 g_parsefile->left_in_line = sp->prev_left_in_line;
9373 g_parsefile->strpush = sp->prev;
9374 if (sp != &(g_parsefile->basestrpush))
9379 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9380 //it peeks whether it is &>, and then pushes back both chars.
9381 //This function needs to save last *next_to_pgetc to buf[0]
9382 //to make two pungetc() reliable. Currently,
9383 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9388 char *buf = g_parsefile->buf;
9390 g_parsefile->next_to_pgetc = buf;
9391 #if ENABLE_FEATURE_EDITING
9393 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9394 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9396 #if ENABLE_FEATURE_TAB_COMPLETION
9397 line_input_state->path_lookup = pathval();
9399 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9401 /* Ctrl+C pressed */
9410 if (nr < 0 && errno == 0) {
9411 /* Ctrl+D pressed */
9416 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9420 /* nonblock_safe_read() handles this problem */
9422 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9423 int flags = fcntl(0, F_GETFL);
9424 if (flags >= 0 && (flags & O_NONBLOCK)) {
9425 flags &= ~O_NONBLOCK;
9426 if (fcntl(0, F_SETFL, flags) >= 0) {
9427 out2str("sh: turning off NDELAY mode\n");
9438 * Refill the input buffer and return the next input character:
9440 * 1) If a string was pushed back on the input, pop it;
9441 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9442 * or we are reading from a string so we can't refill the buffer,
9444 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9445 * 4) Process input up to the next newline, deleting nul characters.
9447 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9448 #define pgetc_debug(...) ((void)0)
9455 while (g_parsefile->strpush) {
9456 #if ENABLE_ASH_ALIAS
9457 if (g_parsefile->left_in_line == -1
9458 && g_parsefile->strpush->ap
9459 && g_parsefile->next_to_pgetc[-1] != ' '
9460 && g_parsefile->next_to_pgetc[-1] != '\t'
9462 pgetc_debug("preadbuffer PEOA");
9467 /* try "pgetc" now: */
9468 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9469 g_parsefile->left_in_line,
9470 g_parsefile->next_to_pgetc,
9471 g_parsefile->next_to_pgetc);
9472 if (--g_parsefile->left_in_line >= 0)
9473 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9475 /* on both branches above g_parsefile->left_in_line < 0.
9476 * "pgetc" needs refilling.
9479 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9480 * pungetc() may increment it a few times.
9481 * Assuming it won't increment it to less than -90.
9483 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9484 pgetc_debug("preadbuffer PEOF1");
9485 /* even in failure keep left_in_line and next_to_pgetc
9486 * in lock step, for correct multi-layer pungetc.
9487 * left_in_line was decremented before preadbuffer(),
9488 * must inc next_to_pgetc: */
9489 g_parsefile->next_to_pgetc++;
9493 more = g_parsefile->left_in_buffer;
9495 flush_stdout_stderr();
9499 /* don't try reading again */
9500 g_parsefile->left_in_line = -99;
9501 pgetc_debug("preadbuffer PEOF2");
9502 g_parsefile->next_to_pgetc++;
9507 /* Find out where's the end of line.
9508 * Set g_parsefile->left_in_line
9509 * and g_parsefile->left_in_buffer acordingly.
9510 * NUL chars are deleted.
9512 q = g_parsefile->next_to_pgetc;
9520 memmove(q, q + 1, more);
9524 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9530 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9531 if (g_parsefile->left_in_line < 0)
9536 g_parsefile->left_in_buffer = more;
9541 out2str(g_parsefile->next_to_pgetc);
9545 pgetc_debug("preadbuffer at %d:%p'%s'",
9546 g_parsefile->left_in_line,
9547 g_parsefile->next_to_pgetc,
9548 g_parsefile->next_to_pgetc);
9549 return (unsigned char)*g_parsefile->next_to_pgetc++;
9552 #define pgetc_as_macro() \
9553 (--g_parsefile->left_in_line >= 0 \
9554 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9561 pgetc_debug("pgetc_fast at %d:%p'%s'",
9562 g_parsefile->left_in_line,
9563 g_parsefile->next_to_pgetc,
9564 g_parsefile->next_to_pgetc);
9565 return pgetc_as_macro();
9568 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9569 # define pgetc_fast() pgetc()
9571 # define pgetc_fast() pgetc_as_macro()
9574 #if ENABLE_ASH_ALIAS
9576 pgetc_without_PEOA(void)
9580 pgetc_debug("pgetc_fast at %d:%p'%s'",
9581 g_parsefile->left_in_line,
9582 g_parsefile->next_to_pgetc,
9583 g_parsefile->next_to_pgetc);
9585 } while (c == PEOA);
9589 # define pgetc_without_PEOA() pgetc()
9593 * Read a line from the script.
9596 pfgets(char *line, int len)
9602 while (--nleft > 0) {
9603 c = pgetc_without_PEOA();
9618 * Undo the last call to pgetc. Only one character may be pushed back.
9619 * PEOF may be pushed back.
9624 g_parsefile->left_in_line++;
9625 g_parsefile->next_to_pgetc--;
9626 pgetc_debug("pushed back to %d:%p'%s'",
9627 g_parsefile->left_in_line,
9628 g_parsefile->next_to_pgetc,
9629 g_parsefile->next_to_pgetc);
9633 * To handle the "." command, a stack of input files is used. Pushfile
9634 * adds a new entry to the stack and popfile restores the previous level.
9639 struct parsefile *pf;
9641 pf = ckzalloc(sizeof(*pf));
9642 pf->prev = g_parsefile;
9644 /*pf->strpush = NULL; - ckzalloc did it */
9645 /*pf->basestrpush.prev = NULL;*/
9652 struct parsefile *pf = g_parsefile;
9660 g_parsefile = pf->prev;
9666 * Return to top level.
9671 while (g_parsefile != &basepf)
9676 * Close the file(s) that the shell is reading commands from. Called
9677 * after a fork is done.
9683 if (g_parsefile->fd > 0) {
9684 close(g_parsefile->fd);
9685 g_parsefile->fd = 0;
9690 * Like setinputfile, but takes an open file descriptor. Call this with
9694 setinputfd(int fd, int push)
9696 close_on_exec_on(fd);
9699 g_parsefile->buf = NULL;
9701 g_parsefile->fd = fd;
9702 if (g_parsefile->buf == NULL)
9703 g_parsefile->buf = ckmalloc(IBUFSIZ);
9704 g_parsefile->left_in_buffer = 0;
9705 g_parsefile->left_in_line = 0;
9706 g_parsefile->linno = 1;
9710 * Set the input to take input from a file. If push is set, push the
9711 * old input onto the stack first.
9714 setinputfile(const char *fname, int flags)
9720 fd = open(fname, O_RDONLY);
9722 if (flags & INPUT_NOFILE_OK)
9724 ash_msg_and_raise_error("can't open '%s'", fname);
9727 fd2 = copyfd(fd, 10);
9730 ash_msg_and_raise_error("out of file descriptors");
9733 setinputfd(fd, flags & INPUT_PUSH_FILE);
9740 * Like setinputfile, but takes input from a string.
9743 setinputstring(char *string)
9747 g_parsefile->next_to_pgetc = string;
9748 g_parsefile->left_in_line = strlen(string);
9749 g_parsefile->buf = NULL;
9750 g_parsefile->linno = 1;
9755 /* ============ mail.c
9757 * Routines to check for mail.
9762 #define MAXMBOXES 10
9764 /* times of mailboxes */
9765 static time_t mailtime[MAXMBOXES];
9766 /* Set if MAIL or MAILPATH is changed. */
9767 static smallint mail_var_path_changed;
9770 * Print appropriate message(s) if mail has arrived.
9771 * If mail_var_path_changed is set,
9772 * then the value of MAIL has mail_var_path_changed,
9773 * so we just update the values.
9782 struct stackmark smark;
9785 setstackmark(&smark);
9786 mpath = mpathset() ? mpathval() : mailval();
9787 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9788 p = path_advance(&mpath, nullstr);
9793 for (q = p; *q; q++)
9799 q[-1] = '\0'; /* delete trailing '/' */
9800 if (stat(p, &statb) < 0) {
9804 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9807 pathopt ? pathopt : "you have mail"
9810 *mtp = statb.st_mtime;
9812 mail_var_path_changed = 0;
9813 popstackmark(&smark);
9816 static void FAST_FUNC
9817 changemail(const char *val UNUSED_PARAM)
9819 mail_var_path_changed = 1;
9822 #endif /* ASH_MAIL */
9825 /* ============ ??? */
9828 * Set the shell parameters.
9831 setparam(char **argv)
9837 for (nparam = 0; argv[nparam]; nparam++)
9839 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9841 *ap++ = ckstrdup(*argv++);
9844 freeparam(&shellparam);
9845 shellparam.malloced = 1;
9846 shellparam.nparam = nparam;
9847 shellparam.p = newparam;
9848 #if ENABLE_ASH_GETOPTS
9849 shellparam.optind = 1;
9850 shellparam.optoff = -1;
9855 * Process shell options. The global variable argptr contains a pointer
9856 * to the argument list; we advance it past the options.
9858 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9859 * For a non-interactive shell, an error condition encountered
9860 * by a special built-in ... shall cause the shell to write a diagnostic message
9861 * to standard error and exit as shown in the following table:
9862 * Error Special Built-In
9864 * Utility syntax error (option or operand error) Shall exit
9866 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9867 * we see that bash does not do that (set "finishes" with error code 1 instead,
9868 * and shell continues), and people rely on this behavior!
9870 * set -o barfoo 2>/dev/null
9873 * Oh well. Let's mimic that.
9876 plus_minus_o(char *name, int val)
9881 for (i = 0; i < NOPTS; i++) {
9882 if (strcmp(name, optnames(i)) == 0) {
9887 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9890 for (i = 0; i < NOPTS; i++) {
9892 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9894 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9900 setoption(int flag, int val)
9904 for (i = 0; i < NOPTS; i++) {
9905 if (optletters(i) == flag) {
9910 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9914 options(int cmdline)
9922 while ((p = *argptr) != NULL) {
9924 if (c != '-' && c != '+')
9927 val = 0; /* val = 0 if c == '+' */
9930 if (p[0] == '\0' || LONE_DASH(p)) {
9932 /* "-" means turn off -x and -v */
9935 /* "--" means reset params */
9936 else if (*argptr == NULL)
9939 break; /* "-" or "--" terminates options */
9942 /* first char was + or - */
9943 while ((c = *p++) != '\0') {
9944 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9945 if (c == 'c' && cmdline) {
9946 minusc = p; /* command is after shell args */
9947 } else if (c == 'o') {
9948 if (plus_minus_o(*argptr, val)) {
9949 /* it already printed err message */
9950 return 1; /* error */
9954 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9956 /* bash does not accept +-login, we also won't */
9957 } else if (cmdline && val && (c == '-')) { /* long options */
9958 if (strcmp(p, "login") == 0)
9970 * The shift builtin command.
9972 static int FAST_FUNC
9973 shiftcmd(int argc UNUSED_PARAM, char **argv)
9980 n = number(argv[1]);
9981 if (n > shellparam.nparam)
9982 n = 0; /* bash compat, was = shellparam.nparam; */
9984 shellparam.nparam -= n;
9985 for (ap1 = shellparam.p; --n >= 0; ap1++) {
9986 if (shellparam.malloced)
9990 while ((*ap2++ = *ap1++) != NULL)
9992 #if ENABLE_ASH_GETOPTS
9993 shellparam.optind = 1;
9994 shellparam.optoff = -1;
10001 * POSIX requires that 'set' (but not export or readonly) output the
10002 * variables in lexicographic order - by the locale's collating order (sigh).
10003 * Maybe we could keep them in an ordered balanced binary tree
10004 * instead of hashed lists.
10005 * For now just roll 'em through qsort for printing...
10008 showvars(const char *sep_prefix, int on, int off)
10011 char **ep, **epend;
10013 ep = listvars(on, off, &epend);
10014 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10016 sep = *sep_prefix ? " " : sep_prefix;
10018 for (; ep < epend; ep++) {
10022 p = strchrnul(*ep, '=');
10025 q = single_quote(++p);
10026 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10032 * The set command builtin.
10034 static int FAST_FUNC
10035 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10040 return showvars(nullstr, 0, VUNSET);
10043 if (!options(0)) { /* if no parse error... */
10046 if (*argptr != NULL) {
10054 #if ENABLE_ASH_RANDOM_SUPPORT
10055 static void FAST_FUNC
10056 change_random(const char *value)
10060 if (value == NULL) {
10061 /* "get", generate */
10062 t = next_random(&random_gen);
10063 /* set without recursion */
10064 setvar(vrandom.text, utoa(t), VNOFUNC);
10065 vrandom.flags &= ~VNOFUNC;
10068 t = strtoul(value, NULL, 10);
10069 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10074 #if ENABLE_ASH_GETOPTS
10076 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10085 if (*param_optind < 1)
10087 optnext = optfirst + *param_optind - 1;
10089 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10092 p = optnext[-1] + *optoff;
10093 if (p == NULL || *p == '\0') {
10094 /* Current word is done, advance */
10096 if (p == NULL || *p != '-' || *++p == '\0') {
10103 if (LONE_DASH(p)) /* check for "--" */
10108 for (q = optstr; *q != c;) {
10110 if (optstr[0] == ':') {
10113 err |= setvarsafe("OPTARG", s, 0);
10115 fprintf(stderr, "Illegal option -%c\n", c);
10116 unsetvar("OPTARG");
10126 if (*p == '\0' && (p = *optnext) == NULL) {
10127 if (optstr[0] == ':') {
10130 err |= setvarsafe("OPTARG", s, 0);
10133 fprintf(stderr, "No arg for -%c option\n", c);
10134 unsetvar("OPTARG");
10142 err |= setvarsafe("OPTARG", p, 0);
10145 err |= setvarsafe("OPTARG", nullstr, 0);
10147 *optoff = p ? p - *(optnext - 1) : -1;
10148 *param_optind = optnext - optfirst + 1;
10149 fmtstr(s, sizeof(s), "%d", *param_optind);
10150 err |= setvarsafe("OPTIND", s, VNOFUNC);
10153 err |= setvarsafe(optvar, s, 0);
10157 flush_stdout_stderr();
10158 raise_exception(EXERROR);
10164 * The getopts builtin. Shellparam.optnext points to the next argument
10165 * to be processed. Shellparam.optptr points to the next character to
10166 * be processed in the current argument. If shellparam.optnext is NULL,
10167 * then it's the first time getopts has been called.
10169 static int FAST_FUNC
10170 getoptscmd(int argc, char **argv)
10175 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10177 optbase = shellparam.p;
10178 if (shellparam.optind > shellparam.nparam + 1) {
10179 shellparam.optind = 1;
10180 shellparam.optoff = -1;
10183 optbase = &argv[3];
10184 if (shellparam.optind > argc - 2) {
10185 shellparam.optind = 1;
10186 shellparam.optoff = -1;
10190 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10191 &shellparam.optoff);
10193 #endif /* ASH_GETOPTS */
10196 /* ============ Shell parser */
10199 struct heredoc *next; /* next here document in list */
10200 union node *here; /* redirection node */
10201 char *eofmark; /* string indicating end of input */
10202 smallint striptabs; /* if set, strip leading tabs */
10205 static smallint tokpushback; /* last token pushed back */
10206 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10207 static smallint quoteflag; /* set if (part of) last token was quoted */
10208 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10209 static struct heredoc *heredoclist; /* list of here documents to read */
10210 static char *wordtext; /* text of last word returned by readtoken */
10211 static struct nodelist *backquotelist;
10212 static union node *redirnode;
10213 static struct heredoc *heredoc;
10216 * Called when an unexpected token is read during the parse. The argument
10217 * is the token that is expected, or -1 if more than one type of token can
10218 * occur at this point.
10220 static void raise_error_unexpected_syntax(int) NORETURN;
10222 raise_error_unexpected_syntax(int token)
10227 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10229 sprintf(msg + l, " (expecting %s)", tokname(token));
10230 raise_error_syntax(msg);
10234 #define EOFMARKLEN 79
10236 /* parsing is heavily cross-recursive, need these forward decls */
10237 static union node *andor(void);
10238 static union node *pipeline(void);
10239 static union node *parse_command(void);
10240 static void parseheredoc(void);
10241 static char peektoken(void);
10242 static int readtoken(void);
10244 static union node *
10247 union node *n1, *n2, *n3;
10250 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10251 if (nlflag == 2 && peektoken())
10257 if (tok == TBACKGND) {
10258 if (n2->type == NPIPE) {
10259 n2->npipe.pipe_backgnd = 1;
10261 if (n2->type != NREDIR) {
10262 n3 = stzalloc(sizeof(struct nredir));
10264 /*n3->nredir.redirect = NULL; - stzalloc did it */
10267 n2->type = NBACKGND;
10273 n3 = stzalloc(sizeof(struct nbinary));
10275 n3->nbinary.ch1 = n1;
10276 n3->nbinary.ch2 = n2;
10292 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10300 pungetc(); /* push back EOF on input */
10304 raise_error_unexpected_syntax(-1);
10311 static union node *
10314 union node *n1, *n2, *n3;
10322 } else if (t == TOR) {
10328 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10330 n3 = stzalloc(sizeof(struct nbinary));
10332 n3->nbinary.ch1 = n1;
10333 n3->nbinary.ch2 = n2;
10338 static union node *
10341 union node *n1, *n2, *pipenode;
10342 struct nodelist *lp, *prev;
10346 TRACE(("pipeline: entered\n"));
10347 if (readtoken() == TNOT) {
10349 checkkwd = CHKKWD | CHKALIAS;
10352 n1 = parse_command();
10353 if (readtoken() == TPIPE) {
10354 pipenode = stzalloc(sizeof(struct npipe));
10355 pipenode->type = NPIPE;
10356 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10357 lp = stzalloc(sizeof(struct nodelist));
10358 pipenode->npipe.cmdlist = lp;
10362 lp = stzalloc(sizeof(struct nodelist));
10363 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10364 lp->n = parse_command();
10366 } while (readtoken() == TPIPE);
10372 n2 = stzalloc(sizeof(struct nnot));
10380 static union node *
10385 n = stzalloc(sizeof(struct narg));
10387 /*n->narg.next = NULL; - stzalloc did it */
10388 n->narg.text = wordtext;
10389 n->narg.backquote = backquotelist;
10394 fixredir(union node *n, const char *text, int err)
10398 TRACE(("Fix redir %s %d\n", text, err));
10400 n->ndup.vname = NULL;
10402 fd = bb_strtou(text, NULL, 10);
10403 if (!errno && fd >= 0)
10404 n->ndup.dupfd = fd;
10405 else if (LONE_DASH(text))
10406 n->ndup.dupfd = -1;
10409 raise_error_syntax("bad fd number");
10410 n->ndup.vname = makename();
10415 * Returns true if the text contains nothing to expand (no dollar signs
10419 noexpand(const char *text)
10423 while ((c = *text++) != '\0') {
10424 if (c == CTLQUOTEMARK)
10428 else if (SIT(c, BASESYNTAX) == CCTL)
10437 union node *n = redirnode;
10439 if (readtoken() != TWORD)
10440 raise_error_unexpected_syntax(-1);
10441 if (n->type == NHERE) {
10442 struct heredoc *here = heredoc;
10446 if (quoteflag == 0)
10448 TRACE(("Here document %d\n", n->type));
10449 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10450 raise_error_syntax("illegal eof marker for << redirection");
10451 rmescapes(wordtext, 0);
10452 here->eofmark = wordtext;
10454 if (heredoclist == NULL)
10455 heredoclist = here;
10457 for (p = heredoclist; p->next; p = p->next)
10461 } else if (n->type == NTOFD || n->type == NFROMFD) {
10462 fixredir(n, wordtext, 0);
10464 n->nfile.fname = makename();
10468 static union node *
10471 union node *args, **app;
10472 union node *n = NULL;
10473 union node *vars, **vpp;
10474 union node **rpp, *redir;
10476 #if ENABLE_ASH_BASH_COMPAT
10477 smallint double_brackets_flag = 0;
10487 savecheckkwd = CHKALIAS;
10490 checkkwd = savecheckkwd;
10493 #if ENABLE_ASH_BASH_COMPAT
10494 case TAND: /* "&&" */
10495 case TOR: /* "||" */
10496 if (!double_brackets_flag) {
10500 wordtext = (char *) (t == TAND ? "-a" : "-o");
10503 n = stzalloc(sizeof(struct narg));
10505 /*n->narg.next = NULL; - stzalloc did it */
10506 n->narg.text = wordtext;
10507 #if ENABLE_ASH_BASH_COMPAT
10508 if (strcmp("[[", wordtext) == 0)
10509 double_brackets_flag = 1;
10510 else if (strcmp("]]", wordtext) == 0)
10511 double_brackets_flag = 0;
10513 n->narg.backquote = backquotelist;
10514 if (savecheckkwd && isassignment(wordtext)) {
10516 vpp = &n->narg.next;
10519 app = &n->narg.next;
10524 *rpp = n = redirnode;
10525 rpp = &n->nfile.next;
10526 parsefname(); /* read name of redirection file */
10529 if (args && app == &args->narg.next
10532 struct builtincmd *bcmd;
10535 /* We have a function */
10536 if (readtoken() != TRP)
10537 raise_error_unexpected_syntax(TRP);
10538 name = n->narg.text;
10539 if (!goodname(name)
10540 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10542 raise_error_syntax("bad function name");
10545 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10546 n->narg.next = parse_command();
10559 n = stzalloc(sizeof(struct ncmd));
10561 n->ncmd.args = args;
10562 n->ncmd.assign = vars;
10563 n->ncmd.redirect = redir;
10567 static union node *
10568 parse_command(void)
10570 union node *n1, *n2;
10571 union node *ap, **app;
10572 union node *cp, **cpp;
10573 union node *redir, **rpp;
10580 switch (readtoken()) {
10582 raise_error_unexpected_syntax(-1);
10585 n1 = stzalloc(sizeof(struct nif));
10587 n1->nif.test = list(0);
10588 if (readtoken() != TTHEN)
10589 raise_error_unexpected_syntax(TTHEN);
10590 n1->nif.ifpart = list(0);
10592 while (readtoken() == TELIF) {
10593 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10594 n2 = n2->nif.elsepart;
10596 n2->nif.test = list(0);
10597 if (readtoken() != TTHEN)
10598 raise_error_unexpected_syntax(TTHEN);
10599 n2->nif.ifpart = list(0);
10601 if (lasttoken == TELSE)
10602 n2->nif.elsepart = list(0);
10604 n2->nif.elsepart = NULL;
10612 n1 = stzalloc(sizeof(struct nbinary));
10613 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10614 n1->nbinary.ch1 = list(0);
10617 TRACE(("expecting DO got %s %s\n", tokname(got),
10618 got == TWORD ? wordtext : ""));
10619 raise_error_unexpected_syntax(TDO);
10621 n1->nbinary.ch2 = list(0);
10626 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10627 raise_error_syntax("bad for loop variable");
10628 n1 = stzalloc(sizeof(struct nfor));
10630 n1->nfor.var = wordtext;
10631 checkkwd = CHKKWD | CHKALIAS;
10632 if (readtoken() == TIN) {
10634 while (readtoken() == TWORD) {
10635 n2 = stzalloc(sizeof(struct narg));
10637 /*n2->narg.next = NULL; - stzalloc did it */
10638 n2->narg.text = wordtext;
10639 n2->narg.backquote = backquotelist;
10641 app = &n2->narg.next;
10644 n1->nfor.args = ap;
10645 if (lasttoken != TNL && lasttoken != TSEMI)
10646 raise_error_unexpected_syntax(-1);
10648 n2 = stzalloc(sizeof(struct narg));
10650 /*n2->narg.next = NULL; - stzalloc did it */
10651 n2->narg.text = (char *)dolatstr;
10652 /*n2->narg.backquote = NULL;*/
10653 n1->nfor.args = n2;
10655 * Newline or semicolon here is optional (but note
10656 * that the original Bourne shell only allowed NL).
10658 if (lasttoken != TNL && lasttoken != TSEMI)
10661 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10662 if (readtoken() != TDO)
10663 raise_error_unexpected_syntax(TDO);
10664 n1->nfor.body = list(0);
10668 n1 = stzalloc(sizeof(struct ncase));
10670 if (readtoken() != TWORD)
10671 raise_error_unexpected_syntax(TWORD);
10672 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10674 /*n2->narg.next = NULL; - stzalloc did it */
10675 n2->narg.text = wordtext;
10676 n2->narg.backquote = backquotelist;
10678 checkkwd = CHKKWD | CHKALIAS;
10679 } while (readtoken() == TNL);
10680 if (lasttoken != TIN)
10681 raise_error_unexpected_syntax(TIN);
10682 cpp = &n1->ncase.cases;
10684 checkkwd = CHKNL | CHKKWD;
10686 while (t != TESAC) {
10687 if (lasttoken == TLP)
10689 *cpp = cp = stzalloc(sizeof(struct nclist));
10691 app = &cp->nclist.pattern;
10693 *app = ap = stzalloc(sizeof(struct narg));
10695 /*ap->narg.next = NULL; - stzalloc did it */
10696 ap->narg.text = wordtext;
10697 ap->narg.backquote = backquotelist;
10698 if (readtoken() != TPIPE)
10700 app = &ap->narg.next;
10703 //ap->narg.next = NULL;
10704 if (lasttoken != TRP)
10705 raise_error_unexpected_syntax(TRP);
10706 cp->nclist.body = list(2);
10708 cpp = &cp->nclist.next;
10710 checkkwd = CHKNL | CHKKWD;
10714 raise_error_unexpected_syntax(TENDCASE);
10721 n1 = stzalloc(sizeof(struct nredir));
10722 n1->type = NSUBSHELL;
10723 n1->nredir.n = list(0);
10724 /*n1->nredir.redirect = NULL; - stzalloc did it */
10734 return simplecmd();
10737 if (readtoken() != t)
10738 raise_error_unexpected_syntax(t);
10741 /* Now check for redirection which may follow command */
10742 checkkwd = CHKKWD | CHKALIAS;
10744 while (readtoken() == TREDIR) {
10745 *rpp = n2 = redirnode;
10746 rpp = &n2->nfile.next;
10752 if (n1->type != NSUBSHELL) {
10753 n2 = stzalloc(sizeof(struct nredir));
10758 n1->nredir.redirect = redir;
10763 #if ENABLE_ASH_BASH_COMPAT
10764 static int decode_dollar_squote(void)
10766 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10772 p = strchr(C_escapes, c);
10777 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10781 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10783 } else if (c == 'x') { /* \xHH */
10787 } while (isxdigit(c) && --cnt);
10789 if (cnt == 3) { /* \x but next char is "bad" */
10793 } else { /* simple seq like \\ or \t */
10798 c = bb_process_escape_sequence((void*)&p);
10799 } else { /* unrecognized "\z": print both chars unless ' or " */
10800 if (c != '\'' && c != '"') {
10802 c |= 0x100; /* "please encode \, then me" */
10810 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10811 * is not NULL, read a here document. In the latter case, eofmark is the
10812 * word which marks the end of the document and striptabs is true if
10813 * leading tabs should be stripped from the document. The argument c
10814 * is the first character of the input token or document.
10816 * Because C does not have internal subroutines, I have simulated them
10817 * using goto's to implement the subroutine linkage. The following macros
10818 * will run code that appears at the end of readtoken1.
10820 #define CHECKEND() {goto checkend; checkend_return:;}
10821 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10822 #define PARSESUB() {goto parsesub; parsesub_return:;}
10823 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10824 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10825 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10827 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10829 /* NB: syntax parameter fits into smallint */
10830 /* c parameter is an unsigned char or PEOF or PEOA */
10833 char line[EOFMARKLEN + 1];
10834 struct nodelist *bqlist;
10838 smallint prevsyntax; /* syntax before arithmetic */
10839 #if ENABLE_ASH_EXPAND_PRMT
10840 smallint pssyntax; /* we are expanding a prompt string */
10842 int varnest; /* levels of variables expansion */
10843 int arinest; /* levels of arithmetic expansion */
10844 int parenlevel; /* levels of parens in arithmetic */
10845 int dqvarnest; /* levels of variables expansion within double quotes */
10847 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10850 /* Avoid longjmp clobbering */
10856 (void) &parenlevel;
10859 (void) &prevsyntax;
10862 startlinno = g_parsefile->linno;
10867 #if ENABLE_ASH_EXPAND_PRMT
10868 pssyntax = (syntax == PSSYNTAX);
10872 dblquote = (syntax == DQSYNTAX);
10878 STARTSTACKSTR(out);
10880 /* For each line, until end of word */
10882 CHECKEND(); /* set c to PEOF if at end of here document */
10883 for (;;) { /* until end of line or end of word */
10884 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10885 switch (SIT(c, syntax)) {
10886 case CNL: /* '\n' */
10887 if (syntax == BASESYNTAX)
10888 goto endword; /* exit outer loop */
10890 g_parsefile->linno++;
10894 goto loop; /* continue outer loop */
10899 if (eofmark == NULL || dblquote)
10900 USTPUTC(CTLESC, out);
10901 #if ENABLE_ASH_BASH_COMPAT
10902 if (c == '\\' && bash_dollar_squote) {
10903 c = decode_dollar_squote();
10905 USTPUTC('\\', out);
10906 c = (unsigned char)c;
10912 case CBACK: /* backslash */
10913 c = pgetc_without_PEOA();
10915 USTPUTC(CTLESC, out);
10916 USTPUTC('\\', out);
10918 } else if (c == '\n') {
10922 #if ENABLE_ASH_EXPAND_PRMT
10923 if (c == '$' && pssyntax) {
10924 USTPUTC(CTLESC, out);
10925 USTPUTC('\\', out);
10928 if (dblquote && c != '\\'
10929 && c != '`' && c != '$'
10930 && (c != '"' || eofmark != NULL)
10932 USTPUTC(CTLESC, out);
10933 USTPUTC('\\', out);
10935 if (SIT(c, SQSYNTAX) == CCTL)
10936 USTPUTC(CTLESC, out);
10944 if (eofmark == NULL) {
10945 USTPUTC(CTLQUOTEMARK, out);
10953 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10954 if (eofmark != NULL && arinest == 0
10959 if (dqvarnest == 0) {
10960 syntax = BASESYNTAX;
10967 case CVAR: /* '$' */
10968 PARSESUB(); /* parse substitution */
10970 case CENDVAR: /* '}' */
10973 if (dqvarnest > 0) {
10976 USTPUTC(CTLENDVAR, out);
10981 #if ENABLE_SH_MATH_SUPPORT
10982 case CLP: /* '(' in arithmetic */
10986 case CRP: /* ')' in arithmetic */
10987 if (parenlevel > 0) {
10991 if (pgetc() == ')') {
10992 if (--arinest == 0) {
10993 USTPUTC(CTLENDARI, out);
10994 syntax = prevsyntax;
10995 dblquote = (syntax == DQSYNTAX);
11000 * unbalanced parens
11001 * (don't 2nd guess - no error)
11009 case CBQUOTE: /* '`' */
11013 goto endword; /* exit outer loop */
11017 if (varnest == 0) {
11018 #if ENABLE_ASH_BASH_COMPAT
11020 if (pgetc() == '>')
11021 c = 0x100 + '>'; /* flag &> */
11025 goto endword; /* exit outer loop */
11027 IF_ASH_ALIAS(if (c != PEOA))
11035 #if ENABLE_SH_MATH_SUPPORT
11036 if (syntax == ARISYNTAX)
11037 raise_error_syntax("missing '))'");
11039 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11040 raise_error_syntax("unterminated quoted string");
11041 if (varnest != 0) {
11042 startlinno = g_parsefile->linno;
11044 raise_error_syntax("missing '}'");
11046 USTPUTC('\0', out);
11047 len = out - (char *)stackblock();
11048 out = stackblock();
11049 if (eofmark == NULL) {
11050 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11053 if (isdigit_str9(out)) {
11054 PARSEREDIR(); /* passed as params: out, c */
11055 lasttoken = TREDIR;
11058 /* else: non-number X seen, interpret it
11059 * as "NNNX>file" = "NNNX >file" */
11063 quoteflag = quotef;
11064 backquotelist = bqlist;
11065 grabstackblock(len);
11069 /* end of readtoken routine */
11072 * Check to see whether we are at the end of the here document. When this
11073 * is called, c is set to the first character of the next input line. If
11074 * we are at the end of the here document, this routine sets the c to PEOF.
11078 #if ENABLE_ASH_ALIAS
11080 c = pgetc_without_PEOA();
11083 while (c == '\t') {
11084 c = pgetc_without_PEOA();
11087 if (c == *eofmark) {
11088 if (pfgets(line, sizeof(line)) != NULL) {
11092 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11094 if (*p == '\n' && *q == '\0') {
11096 g_parsefile->linno++;
11097 needprompt = doprompt;
11099 pushstring(line, NULL);
11104 goto checkend_return;
11108 * Parse a redirection operator. The variable "out" points to a string
11109 * specifying the fd to be redirected. The variable "c" contains the
11110 * first character of the redirection operator.
11113 /* out is already checked to be a valid number or "" */
11114 int fd = (*out == '\0' ? -1 : atoi(out));
11117 np = stzalloc(sizeof(struct nfile));
11122 np->type = NAPPEND;
11124 np->type = NCLOBBER;
11127 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11133 #if ENABLE_ASH_BASH_COMPAT
11134 else if (c == 0x100 + '>') { /* this flags &> redirection */
11136 pgetc(); /* this is '>', no need to check */
11140 else { /* c == '<' */
11141 /*np->nfile.fd = 0; - stzalloc did it */
11145 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11146 np = stzalloc(sizeof(struct nhere));
11147 /*np->nfile.fd = 0; - stzalloc did it */
11150 heredoc = stzalloc(sizeof(struct heredoc));
11151 heredoc->here = np;
11154 heredoc->striptabs = 1;
11156 /*heredoc->striptabs = 0; - stzalloc did it */
11162 np->type = NFROMFD;
11166 np->type = NFROMTO;
11178 goto parseredir_return;
11182 * Parse a substitution. At this point, we have read the dollar sign
11183 * and nothing else.
11186 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11187 * (assuming ascii char codes, as the original implementation did) */
11188 #define is_special(c) \
11189 (((unsigned)(c) - 33 < 32) \
11190 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11192 unsigned char subtype;
11196 static const char types[] ALIGN1 = "}-+?=";
11199 if (c > 255 /* PEOA or PEOF */
11200 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11202 #if ENABLE_ASH_BASH_COMPAT
11204 bash_dollar_squote = 1;
11209 } else if (c == '(') { /* $(command) or $((arith)) */
11210 if (pgetc() == '(') {
11211 #if ENABLE_SH_MATH_SUPPORT
11214 raise_error_syntax("you disabled math support for $((arith)) syntax");
11221 USTPUTC(CTLVAR, out);
11222 typeloc = out - (char *)stackblock();
11223 USTPUTC(VSNORMAL, out);
11224 subtype = VSNORMAL;
11232 subtype = VSLENGTH;
11236 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11240 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11241 } else if (isdigit(c)) {
11245 } while (isdigit(c));
11246 } else if (is_special(c)) {
11251 raise_error_syntax("bad substitution");
11253 if (c != '}' && subtype == VSLENGTH)
11258 if (subtype == 0) {
11262 #if ENABLE_ASH_BASH_COMPAT
11263 if (c == ':' || c == '$' || isdigit(c)) {
11265 subtype = VSSUBSTR;
11272 p = strchr(types, c);
11275 subtype = p - types + VSNORMAL;
11280 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11288 #if ENABLE_ASH_BASH_COMPAT
11290 subtype = VSREPLACE;
11293 subtype++; /* VSREPLACEALL */
11302 if (dblquote || arinest)
11304 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11305 if (subtype != VSNORMAL) {
11307 if (dblquote || arinest) {
11312 goto parsesub_return;
11316 * Called to parse command substitutions. Newstyle is set if the command
11317 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11318 * list of commands (passed by reference), and savelen is the number of
11319 * characters on the top of the stack which must be preserved.
11322 struct nodelist **nlpp;
11325 char *volatile str;
11326 struct jmploc jmploc;
11327 struct jmploc *volatile savehandler;
11329 smallint saveprompt = 0;
11332 (void) &saveprompt;
11334 savepbq = parsebackquote;
11335 if (setjmp(jmploc.loc)) {
11337 parsebackquote = 0;
11338 exception_handler = savehandler;
11339 longjmp(exception_handler->loc, 1);
11343 savelen = out - (char *)stackblock();
11345 str = ckmalloc(savelen);
11346 memcpy(str, stackblock(), savelen);
11348 savehandler = exception_handler;
11349 exception_handler = &jmploc;
11352 /* We must read until the closing backquote, giving special
11353 treatment to some slashes, and then push the string and
11354 reread it as input, interpreting it normally. */
11361 STARTSTACKSTR(pout);
11374 g_parsefile->linno++;
11378 * If eating a newline, avoid putting
11379 * the newline into the new character
11380 * stream (via the STPUTC after the
11385 if (pc != '\\' && pc != '`' && pc != '$'
11386 && (!dblquote || pc != '"')
11388 STPUTC('\\', pout);
11390 if (pc <= 255 /* not PEOA or PEOF */) {
11396 IF_ASH_ALIAS(case PEOA:)
11397 startlinno = g_parsefile->linno;
11398 raise_error_syntax("EOF in backquote substitution");
11401 g_parsefile->linno++;
11402 needprompt = doprompt;
11411 STPUTC('\0', pout);
11412 psavelen = pout - (char *)stackblock();
11413 if (psavelen > 0) {
11414 pstr = grabstackstr(pout);
11415 setinputstring(pstr);
11420 nlpp = &(*nlpp)->next;
11421 *nlpp = stzalloc(sizeof(**nlpp));
11422 /* (*nlpp)->next = NULL; - stzalloc did it */
11423 parsebackquote = oldstyle;
11426 saveprompt = doprompt;
11433 doprompt = saveprompt;
11434 else if (readtoken() != TRP)
11435 raise_error_unexpected_syntax(TRP);
11440 * Start reading from old file again, ignoring any pushed back
11441 * tokens left from the backquote parsing
11446 while (stackblocksize() <= savelen)
11448 STARTSTACKSTR(out);
11450 memcpy(out, str, savelen);
11451 STADJUST(savelen, out);
11457 parsebackquote = savepbq;
11458 exception_handler = savehandler;
11459 if (arinest || dblquote)
11460 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11462 USTPUTC(CTLBACKQ, out);
11464 goto parsebackq_oldreturn;
11465 goto parsebackq_newreturn;
11468 #if ENABLE_SH_MATH_SUPPORT
11470 * Parse an arithmetic expansion (indicate start of one and set state)
11473 if (++arinest == 1) {
11474 prevsyntax = syntax;
11475 syntax = ARISYNTAX;
11476 USTPUTC(CTLARI, out);
11483 * we collapse embedded arithmetic expansion to
11484 * parenthesis, which should be equivalent
11488 goto parsearith_return;
11492 } /* end of readtoken */
11495 * Read the next input token.
11496 * If the token is a word, we set backquotelist to the list of cmds in
11497 * backquotes. We set quoteflag to true if any part of the word was
11499 * If the token is TREDIR, then we set redirnode to a structure containing
11501 * In all cases, the variable startlinno is set to the number of the line
11502 * on which the token starts.
11504 * [Change comment: here documents and internal procedures]
11505 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11506 * word parsing code into a separate routine. In this case, readtoken
11507 * doesn't need to have any internal procedures, but parseword does.
11508 * We could also make parseoperator in essence the main routine, and
11509 * have parseword (readtoken1?) handle both words and redirection.]
11511 #define NEW_xxreadtoken
11512 #ifdef NEW_xxreadtoken
11513 /* singles must be first! */
11514 static const char xxreadtoken_chars[7] ALIGN1 = {
11515 '\n', '(', ')', /* singles */
11516 '&', '|', ';', /* doubles */
11520 #define xxreadtoken_singles 3
11521 #define xxreadtoken_doubles 3
11523 static const char xxreadtoken_tokens[] ALIGN1 = {
11524 TNL, TLP, TRP, /* only single occurrence allowed */
11525 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11526 TEOF, /* corresponds to trailing nul */
11527 TAND, TOR, TENDCASE /* if double occurrence */
11542 startlinno = g_parsefile->linno;
11543 for (;;) { /* until token or start of word found */
11545 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11549 while ((c = pgetc()) != '\n' && c != PEOF)
11552 } else if (c == '\\') {
11553 if (pgetc() != '\n') {
11555 break; /* return readtoken1(...) */
11557 startlinno = ++g_parsefile->linno;
11563 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11566 g_parsefile->linno++;
11567 needprompt = doprompt;
11570 p = strchr(xxreadtoken_chars, c);
11572 break; /* return readtoken1(...) */
11574 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11576 if (cc == c) { /* double occurrence? */
11577 p += xxreadtoken_doubles + 1;
11580 #if ENABLE_ASH_BASH_COMPAT
11581 if (c == '&' && cc == '>') /* &> */
11582 break; /* return readtoken1(...) */
11587 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11592 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11594 #else /* old xxreadtoken */
11595 #define RETURN(token) return lasttoken = token
11608 startlinno = g_parsefile->linno;
11609 for (;;) { /* until token or start of word found */
11612 case ' ': case '\t':
11613 IF_ASH_ALIAS(case PEOA:)
11616 while ((c = pgetc()) != '\n' && c != PEOF)
11621 if (pgetc() == '\n') {
11622 startlinno = ++g_parsefile->linno;
11630 g_parsefile->linno++;
11631 needprompt = doprompt;
11636 if (pgetc() == '&')
11641 if (pgetc() == '|')
11646 if (pgetc() == ';')
11659 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11662 #endif /* old xxreadtoken */
11669 smallint alreadyseen = tokpushback;
11672 #if ENABLE_ASH_ALIAS
11681 if (checkkwd & CHKNL) {
11688 if (t != TWORD || quoteflag) {
11693 * check for keywords
11695 if (checkkwd & CHKKWD) {
11696 const char *const *pp;
11698 pp = findkwd(wordtext);
11700 lasttoken = t = pp - tokname_array;
11701 TRACE(("keyword %s recognized\n", tokname(t)));
11706 if (checkkwd & CHKALIAS) {
11707 #if ENABLE_ASH_ALIAS
11709 ap = lookupalias(wordtext, 1);
11712 pushstring(ap->val, ap);
11722 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11724 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11736 return tokname_array[t][0];
11740 * Read and parse a command. Returns NODE_EOF on end of file.
11741 * (NULL is a valid parse tree indicating a blank line.)
11743 static union node *
11744 parsecmd(int interact)
11749 doprompt = interact;
11751 setprompt(doprompt);
11763 * Input any here documents.
11768 struct heredoc *here;
11771 here = heredoclist;
11772 heredoclist = NULL;
11778 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11779 here->eofmark, here->striptabs);
11780 n = stzalloc(sizeof(struct narg));
11781 n->narg.type = NARG;
11782 /*n->narg.next = NULL; - stzalloc did it */
11783 n->narg.text = wordtext;
11784 n->narg.backquote = backquotelist;
11785 here->here->nhere.doc = n;
11792 * called by editline -- any expansions to the prompt should be added here.
11794 #if ENABLE_ASH_EXPAND_PRMT
11795 static const char *
11796 expandstr(const char *ps)
11800 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11801 * and token processing _can_ alter it (delete NULs etc). */
11802 setinputstring((char *)ps);
11803 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11806 n.narg.type = NARG;
11807 n.narg.next = NULL;
11808 n.narg.text = wordtext;
11809 n.narg.backquote = backquotelist;
11811 expandarg(&n, NULL, 0);
11812 return stackblock();
11817 * Execute a command or commands contained in a string.
11820 evalstring(char *s, int mask)
11823 struct stackmark smark;
11827 setstackmark(&smark);
11830 while ((n = parsecmd(0)) != NODE_EOF) {
11832 popstackmark(&smark);
11845 * The eval command.
11847 static int FAST_FUNC
11848 evalcmd(int argc UNUSED_PARAM, char **argv)
11857 STARTSTACKSTR(concat);
11859 concat = stack_putstr(p, concat);
11863 STPUTC(' ', concat);
11865 STPUTC('\0', concat);
11866 p = grabstackstr(concat);
11868 evalstring(p, ~SKIPEVAL);
11875 * Read and execute commands.
11876 * "Top" is nonzero for the top level command loop;
11877 * it turns on prompting if the shell is interactive.
11883 struct stackmark smark;
11887 TRACE(("cmdloop(%d) called\n", top));
11891 setstackmark(&smark);
11894 showjobs(stderr, SHOW_CHANGED);
11897 if (iflag && top) {
11899 #if ENABLE_ASH_MAIL
11903 n = parsecmd(inter);
11905 if (DEBUG > 2 && debug && (n != NODE_EOF))
11908 if (n == NODE_EOF) {
11909 if (!top || numeof >= 50)
11911 if (!stoppedjobs()) {
11914 out2str("\nUse \"exit\" to leave shell.\n");
11917 } else if (nflag == 0) {
11918 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11923 popstackmark(&smark);
11928 return skip & SKIPEVAL;
11935 * Take commands from a file. To be compatible we should do a path
11936 * search for the file, which is necessary to find sub-commands.
11939 find_dot_file(char *name)
11942 const char *path = pathval();
11945 /* don't try this for absolute or relative paths */
11946 if (strchr(name, '/'))
11949 /* IIRC standards do not say whether . is to be searched.
11950 * And it is even smaller this way, making it unconditional for now:
11952 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11957 while ((fullname = path_advance(&path, name)) != NULL) {
11959 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11961 * Don't bother freeing here, since it will
11962 * be freed by the caller.
11966 if (fullname != name)
11967 stunalloc(fullname);
11970 /* not found in the PATH */
11971 ash_msg_and_raise_error("%s: not found", name);
11975 static int FAST_FUNC
11976 dotcmd(int argc, char **argv)
11978 struct strlist *sp;
11979 volatile struct shparam saveparam;
11982 for (sp = cmdenviron; sp; sp = sp->next)
11983 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
11985 if (argv[1]) { /* That's what SVR2 does */
11986 char *fullname = find_dot_file(argv[1]);
11989 if (argc) { /* argc > 0, argv[0] != NULL */
11990 saveparam = shellparam;
11991 shellparam.malloced = 0;
11992 shellparam.nparam = argc;
11993 shellparam.p = argv;
11996 setinputfile(fullname, INPUT_PUSH_FILE);
11997 commandname = fullname;
12002 freeparam(&shellparam);
12003 shellparam = saveparam;
12005 status = exitstatus;
12010 static int FAST_FUNC
12011 exitcmd(int argc UNUSED_PARAM, char **argv)
12016 exitstatus = number(argv[1]);
12017 raise_exception(EXEXIT);
12022 * Read a file containing shell functions.
12025 readcmdfile(char *name)
12027 setinputfile(name, INPUT_PUSH_FILE);
12033 /* ============ find_command inplementation */
12036 * Resolve a command name. If you change this routine, you may have to
12037 * change the shellexec routine as well.
12040 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12042 struct tblentry *cmdp;
12049 struct builtincmd *bcmd;
12051 /* If name contains a slash, don't use PATH or hash table */
12052 if (strchr(name, '/') != NULL) {
12053 entry->u.index = -1;
12054 if (act & DO_ABS) {
12055 while (stat(name, &statb) < 0) {
12057 if (errno == EINTR)
12060 entry->cmdtype = CMDUNKNOWN;
12064 entry->cmdtype = CMDNORMAL;
12068 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12070 updatetbl = (path == pathval());
12073 if (strstr(path, "%builtin") != NULL)
12074 act |= DO_ALTBLTIN;
12077 /* If name is in the table, check answer will be ok */
12078 cmdp = cmdlookup(name, 0);
12079 if (cmdp != NULL) {
12082 switch (cmdp->cmdtype) {
12100 } else if (cmdp->rehash == 0)
12101 /* if not invalidated by cd, we're done */
12105 /* If %builtin not in path, check for builtin next */
12106 bcmd = find_builtin(name);
12108 if (IS_BUILTIN_REGULAR(bcmd))
12109 goto builtin_success;
12110 if (act & DO_ALTPATH) {
12111 if (!(act & DO_ALTBLTIN))
12112 goto builtin_success;
12113 } else if (builtinloc <= 0) {
12114 goto builtin_success;
12118 #if ENABLE_FEATURE_SH_STANDALONE
12120 int applet_no = find_applet_by_name(name);
12121 if (applet_no >= 0) {
12122 entry->cmdtype = CMDNORMAL;
12123 entry->u.index = -2 - applet_no;
12129 /* We have to search path. */
12130 prev = -1; /* where to start */
12131 if (cmdp && cmdp->rehash) { /* doing a rehash */
12132 if (cmdp->cmdtype == CMDBUILTIN)
12135 prev = cmdp->param.index;
12141 while ((fullname = path_advance(&path, name)) != NULL) {
12142 stunalloc(fullname);
12143 /* NB: code below will still use fullname
12144 * despite it being "unallocated" */
12147 if (prefix(pathopt, "builtin")) {
12149 goto builtin_success;
12152 if ((act & DO_NOFUNC)
12153 || !prefix(pathopt, "func")
12154 ) { /* ignore unimplemented options */
12158 /* if rehash, don't redo absolute path names */
12159 if (fullname[0] == '/' && idx <= prev) {
12162 TRACE(("searchexec \"%s\": no change\n", name));
12165 while (stat(fullname, &statb) < 0) {
12167 if (errno == EINTR)
12170 if (errno != ENOENT && errno != ENOTDIR)
12174 e = EACCES; /* if we fail, this will be the error */
12175 if (!S_ISREG(statb.st_mode))
12177 if (pathopt) { /* this is a %func directory */
12178 stalloc(strlen(fullname) + 1);
12179 /* NB: stalloc will return space pointed by fullname
12180 * (because we don't have any intervening allocations
12181 * between stunalloc above and this stalloc) */
12182 readcmdfile(fullname);
12183 cmdp = cmdlookup(name, 0);
12184 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12185 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12186 stunalloc(fullname);
12189 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12191 entry->cmdtype = CMDNORMAL;
12192 entry->u.index = idx;
12196 cmdp = cmdlookup(name, 1);
12197 cmdp->cmdtype = CMDNORMAL;
12198 cmdp->param.index = idx;
12203 /* We failed. If there was an entry for this command, delete it */
12204 if (cmdp && updatetbl)
12205 delete_cmd_entry();
12207 ash_msg("%s: %s", name, errmsg(e, "not found"));
12208 entry->cmdtype = CMDUNKNOWN;
12213 entry->cmdtype = CMDBUILTIN;
12214 entry->u.cmd = bcmd;
12218 cmdp = cmdlookup(name, 1);
12219 cmdp->cmdtype = CMDBUILTIN;
12220 cmdp->param.cmd = bcmd;
12224 entry->cmdtype = cmdp->cmdtype;
12225 entry->u = cmdp->param;
12229 /* ============ trap.c */
12232 * The trap builtin.
12234 static int FAST_FUNC
12235 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12244 for (signo = 0; signo < NSIG; signo++) {
12245 char *tr = trap_ptr[signo];
12247 /* note: bash adds "SIG", but only if invoked
12248 * as "bash". If called as "sh", or if set -o posix,
12249 * then it prints short signal names.
12250 * We are printing short names: */
12251 out1fmt("trap -- %s %s\n",
12253 get_signame(signo));
12254 /* trap_ptr != trap only if we are in special-cased `trap` code.
12255 * In this case, we will exit very soon, no need to free(). */
12256 /* if (trap_ptr != trap && tp[0]) */
12261 if (trap_ptr != trap) {
12273 signo = get_signum(*ap);
12275 ash_msg_and_raise_error("%s: bad trap", *ap);
12278 if (LONE_DASH(action))
12281 action = ckstrdup(action);
12284 trap[signo] = action;
12294 /* ============ Builtins */
12296 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12298 * Lists available builtins
12300 static int FAST_FUNC
12301 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12307 "Built-in commands:\n"
12308 "------------------\n");
12309 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12310 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12311 builtintab[i].name + 1);
12317 #if ENABLE_FEATURE_SH_STANDALONE
12319 const char *a = applet_names;
12321 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12326 a += strlen(a) + 1;
12331 return EXIT_SUCCESS;
12333 #endif /* FEATURE_SH_EXTRA_QUIET */
12336 * The export and readonly commands.
12338 static int FAST_FUNC
12339 exportcmd(int argc UNUSED_PARAM, char **argv)
12345 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12347 if (nextopt("p") != 'p') {
12352 p = strchr(name, '=');
12356 vp = *findvar(hashvar(name), name);
12362 setvar(name, p, flag);
12363 } while ((name = *++aptr) != NULL);
12367 showvars(argv[0], flag, 0);
12372 * Delete a function if it exists.
12375 unsetfunc(const char *name)
12377 struct tblentry *cmdp;
12379 cmdp = cmdlookup(name, 0);
12380 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12381 delete_cmd_entry();
12385 * The unset builtin command. We unset the function before we unset the
12386 * variable to allow a function to be unset when there is a readonly variable
12387 * with the same name.
12389 static int FAST_FUNC
12390 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12397 while ((i = nextopt("vf")) != '\0') {
12401 for (ap = argptr; *ap; ap++) {
12417 #include <sys/times.h>
12419 static const unsigned char timescmd_str[] ALIGN1 = {
12420 ' ', offsetof(struct tms, tms_utime),
12421 '\n', offsetof(struct tms, tms_stime),
12422 ' ', offsetof(struct tms, tms_cutime),
12423 '\n', offsetof(struct tms, tms_cstime),
12427 static int FAST_FUNC
12428 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12430 long clk_tck, s, t;
12431 const unsigned char *p;
12434 clk_tck = sysconf(_SC_CLK_TCK);
12439 t = *(clock_t *)(((char *) &buf) + p[1]);
12441 out1fmt("%ldm%ld.%.3lds%c",
12443 ((t - s * clk_tck) * 1000) / clk_tck,
12445 } while (*(p += 2));
12450 #if ENABLE_SH_MATH_SUPPORT
12452 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12453 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12455 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12457 static int FAST_FUNC
12458 letcmd(int argc UNUSED_PARAM, char **argv)
12464 ash_msg_and_raise_error("expression expected");
12466 i = ash_arith(*argv);
12471 #endif /* SH_MATH_SUPPORT */
12474 /* ============ miscbltin.c
12476 * Miscellaneous builtins.
12481 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12482 typedef enum __rlimit_resource rlim_t;
12486 * The read builtin. Options:
12487 * -r Do not interpret '\' specially
12488 * -s Turn off echo (tty only)
12489 * -n NCHARS Read NCHARS max
12490 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12491 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12492 * -u FD Read from given FD instead of fd 0
12493 * This uses unbuffered input, which may be avoidable in some cases.
12494 * TODO: bash also has:
12495 * -a ARRAY Read into array[0],[1],etc
12496 * -d DELIM End on DELIM char, not newline
12497 * -e Use line editing (tty only)
12499 static int FAST_FUNC
12500 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12502 static const char *const arg_REPLY[] = { "REPLY", NULL };
12515 #if ENABLE_ASH_READ_NCHARS
12516 int nchars = 0; /* if != 0, -n is in effect */
12518 struct termios tty, old_tty;
12520 #if ENABLE_ASH_READ_TIMEOUT
12521 unsigned end_ms = 0;
12522 unsigned timeout = 0;
12527 while ((i = nextopt("p:u:r"
12528 IF_ASH_READ_TIMEOUT("t:")
12529 IF_ASH_READ_NCHARS("n:s")
12533 prompt = optionarg;
12535 #if ENABLE_ASH_READ_NCHARS
12537 nchars = bb_strtou(optionarg, NULL, 10);
12538 if (nchars < 0 || errno)
12539 ash_msg_and_raise_error("invalid count");
12540 /* nchars == 0: off (bash 3.2 does this too) */
12546 #if ENABLE_ASH_READ_TIMEOUT
12548 timeout = bb_strtou(optionarg, NULL, 10);
12549 if (errno || timeout > UINT_MAX / 2048)
12550 ash_msg_and_raise_error("invalid timeout");
12552 #if 0 /* even bash have no -t N.NNN support */
12553 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12555 /* EINVAL means number is ok, but not terminated by NUL */
12556 if (*p == '.' && errno == EINVAL) {
12560 ts.tv_usec = bb_strtou(p, &p2, 10);
12562 ash_msg_and_raise_error("invalid timeout");
12564 /* normalize to usec */
12566 ash_msg_and_raise_error("invalid timeout");
12567 while (scale++ < 6)
12570 } else if (ts.tv_sec < 0 || errno) {
12571 ash_msg_and_raise_error("invalid timeout");
12573 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12574 ash_msg_and_raise_error("invalid timeout");
12583 fd = bb_strtou(optionarg, NULL, 10);
12584 if (fd < 0 || errno)
12585 ash_msg_and_raise_error("invalid file descriptor");
12591 if (prompt && isatty(fd)) {
12596 ap = (char**)arg_REPLY;
12597 ifs = bltinlookup("IFS");
12600 #if ENABLE_ASH_READ_NCHARS
12601 tcgetattr(fd, &tty);
12603 if (nchars || silent) {
12605 tty.c_lflag &= ~ICANON;
12606 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12609 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12611 /* if tcgetattr failed, tcsetattr will fail too.
12612 * Ignoring, it's harmless. */
12613 tcsetattr(fd, TCSANOW, &tty);
12620 #if ENABLE_ASH_READ_TIMEOUT
12621 if (timeout) /* NB: ensuring end_ms is nonzero */
12622 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12626 const char *is_ifs;
12628 #if ENABLE_ASH_READ_TIMEOUT
12630 struct pollfd pfd[1];
12632 pfd[0].events = POLLIN;
12633 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12634 if ((int)timeout <= 0 /* already late? */
12635 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12636 ) { /* timed out! */
12637 #if ENABLE_ASH_READ_NCHARS
12638 tcsetattr(fd, TCSANOW, &old_tty);
12644 if (nonblock_safe_read(fd, &c, 1) != 1) {
12656 if (!rflag && c == '\\') {
12662 /* $IFS splitting */
12663 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12664 is_ifs = strchr(ifs, c);
12665 if (startword && is_ifs) {
12668 /* it is a non-space ifs char */
12670 if (startword == 1) /* first one? */
12671 continue; /* yes, it is not next word yet */
12674 if (ap[1] != NULL && is_ifs) {
12677 beg = stackblock();
12678 setvar(*ap, beg, 0);
12680 /* can we skip one non-space ifs char? (2: yes) */
12681 startword = isspace(c) ? 2 : 1;
12688 /* end of do {} while: */
12689 #if ENABLE_ASH_READ_NCHARS
12695 #if ENABLE_ASH_READ_NCHARS
12696 tcsetattr(fd, TCSANOW, &old_tty);
12700 /* Remove trailing space ifs chars */
12701 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12703 setvar(*ap, stackblock(), 0);
12704 while (*++ap != NULL)
12705 setvar(*ap, nullstr, 0);
12709 static int FAST_FUNC
12710 umaskcmd(int argc UNUSED_PARAM, char **argv)
12712 static const char permuser[3] ALIGN1 = "ugo";
12713 static const char permmode[3] ALIGN1 = "rwx";
12714 static const short permmask[] ALIGN2 = {
12715 S_IRUSR, S_IWUSR, S_IXUSR,
12716 S_IRGRP, S_IWGRP, S_IXGRP,
12717 S_IROTH, S_IWOTH, S_IXOTH
12720 /* TODO: use bb_parse_mode() instead */
12725 int symbolic_mode = 0;
12727 while (nextopt("S") != '\0') {
12738 if (symbolic_mode) {
12742 for (i = 0; i < 3; i++) {
12745 *p++ = permuser[i];
12747 for (j = 0; j < 3; j++) {
12748 if ((mask & permmask[3 * i + j]) == 0) {
12749 *p++ = permmode[j];
12757 out1fmt("%.4o\n", mask);
12760 if (isdigit((unsigned char) *ap)) {
12763 if (*ap >= '8' || *ap < '0')
12764 ash_msg_and_raise_error(msg_illnum, argv[1]);
12765 mask = (mask << 3) + (*ap - '0');
12766 } while (*++ap != '\0');
12769 mask = ~mask & 0777;
12770 if (!bb_parse_mode(ap, &mask)) {
12771 ash_msg_and_raise_error("illegal mode: %s", ap);
12773 umask(~mask & 0777);
12782 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12783 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12784 * ash by J.T. Conklin.
12789 uint8_t cmd; /* RLIMIT_xxx fit into it */
12790 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12794 static const struct limits limits_tbl[] = {
12796 { RLIMIT_CPU, 0, 't' },
12798 #ifdef RLIMIT_FSIZE
12799 { RLIMIT_FSIZE, 9, 'f' },
12802 { RLIMIT_DATA, 10, 'd' },
12804 #ifdef RLIMIT_STACK
12805 { RLIMIT_STACK, 10, 's' },
12808 { RLIMIT_CORE, 9, 'c' },
12811 { RLIMIT_RSS, 10, 'm' },
12813 #ifdef RLIMIT_MEMLOCK
12814 { RLIMIT_MEMLOCK, 10, 'l' },
12816 #ifdef RLIMIT_NPROC
12817 { RLIMIT_NPROC, 0, 'p' },
12819 #ifdef RLIMIT_NOFILE
12820 { RLIMIT_NOFILE, 0, 'n' },
12823 { RLIMIT_AS, 10, 'v' },
12825 #ifdef RLIMIT_LOCKS
12826 { RLIMIT_LOCKS, 0, 'w' },
12829 static const char limits_name[] =
12831 "time(seconds)" "\0"
12833 #ifdef RLIMIT_FSIZE
12834 "file(blocks)" "\0"
12839 #ifdef RLIMIT_STACK
12843 "coredump(blocks)" "\0"
12848 #ifdef RLIMIT_MEMLOCK
12849 "locked memory(kb)" "\0"
12851 #ifdef RLIMIT_NPROC
12854 #ifdef RLIMIT_NOFILE
12860 #ifdef RLIMIT_LOCKS
12865 enum limtype { SOFT = 0x1, HARD = 0x2 };
12868 printlim(enum limtype how, const struct rlimit *limit,
12869 const struct limits *l)
12873 val = limit->rlim_max;
12875 val = limit->rlim_cur;
12877 if (val == RLIM_INFINITY)
12878 out1fmt("unlimited\n");
12880 val >>= l->factor_shift;
12881 out1fmt("%lld\n", (long long) val);
12885 static int FAST_FUNC
12886 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12889 enum limtype how = SOFT | HARD;
12890 const struct limits *l;
12893 struct rlimit limit;
12896 while ((optc = nextopt("HSa"
12900 #ifdef RLIMIT_FSIZE
12906 #ifdef RLIMIT_STACK
12915 #ifdef RLIMIT_MEMLOCK
12918 #ifdef RLIMIT_NPROC
12921 #ifdef RLIMIT_NOFILE
12927 #ifdef RLIMIT_LOCKS
12945 for (l = limits_tbl; l->option != what; l++)
12948 set = *argptr ? 1 : 0;
12953 if (all || argptr[1])
12954 ash_msg_and_raise_error("too many arguments");
12955 if (strncmp(p, "unlimited\n", 9) == 0)
12956 val = RLIM_INFINITY;
12958 if (sizeof(val) == sizeof(int))
12959 val = bb_strtou(p, NULL, 10);
12960 else if (sizeof(val) == sizeof(long))
12961 val = bb_strtoul(p, NULL, 10);
12963 val = bb_strtoull(p, NULL, 10);
12965 ash_msg_and_raise_error("bad number");
12966 val <<= l->factor_shift;
12970 const char *lname = limits_name;
12971 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
12972 getrlimit(l->cmd, &limit);
12973 out1fmt("%-20s ", lname);
12974 lname += strlen(lname) + 1;
12975 printlim(how, &limit, l);
12980 getrlimit(l->cmd, &limit);
12983 limit.rlim_max = val;
12985 limit.rlim_cur = val;
12986 if (setrlimit(l->cmd, &limit) < 0)
12987 ash_msg_and_raise_error("error setting limit (%m)");
12989 printlim(how, &limit, l);
12994 /* ============ main() and helpers */
12997 * Called to exit the shell.
12999 static void exitshell(void) NORETURN;
13007 status = exitstatus;
13008 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13009 if (setjmp(loc.loc)) {
13010 if (exception_type == EXEXIT)
13011 /* dash bug: it just does _exit(exitstatus) here
13012 * but we have to do setjobctl(0) first!
13013 * (bug is still not fixed in dash-0.5.3 - if you run dash
13014 * under Midnight Commander, on exit from dash MC is backgrounded) */
13015 status = exitstatus;
13018 exception_handler = &loc;
13025 flush_stdout_stderr();
13035 /* from input.c: */
13036 basepf.next_to_pgetc = basepf.buf = basebuf;
13039 signal(SIGCHLD, SIG_DFL);
13040 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13041 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13043 signal(SIGHUP, SIG_DFL);
13049 struct stat st1, st2;
13052 for (envp = environ; envp && *envp; envp++) {
13053 if (strchr(*envp, '=')) {
13054 setvareq(*envp, VEXPORT|VTEXTFIXED);
13058 setvar("PPID", utoa(getppid()), 0);
13060 p = lookupvar("PWD");
13062 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13063 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13070 * Process the shell command line arguments.
13073 procargs(char **argv)
13076 const char *xminusc;
13081 /* if (xargv[0]) - mmm, this is always true! */
13083 for (i = 0; i < NOPTS; i++)
13087 /* it already printed err message */
13088 raise_exception(EXERROR);
13092 if (*xargv == NULL) {
13094 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13097 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13101 for (i = 0; i < NOPTS; i++)
13102 if (optlist[i] == 2)
13107 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13112 } else if (!sflag) {
13113 setinputfile(*xargv, 0);
13116 commandname = arg0;
13119 shellparam.p = xargv;
13120 #if ENABLE_ASH_GETOPTS
13121 shellparam.optind = 1;
13122 shellparam.optoff = -1;
13124 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13126 shellparam.nparam++;
13133 * Read /etc/profile or .profile.
13136 read_profile(const char *name)
13140 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13149 * This routine is called when an error or an interrupt occurs in an
13150 * interactive shell and control is returned to the main command loop.
13158 /* from input.c: */
13159 g_parsefile->left_in_buffer = 0;
13160 g_parsefile->left_in_line = 0; /* clear input buffer */
13162 /* from parser.c: */
13165 /* from redir.c: */
13166 clearredir(/*drop:*/ 0);
13170 static short profile_buf[16384];
13171 extern int etext();
13175 * Main routine. We initialize things, parse the arguments, execute
13176 * profiles if we're a login shell, and then call cmdloop to execute
13177 * commands. The setjmp call sets up the location to jump to when an
13178 * exception occurs. When an exception occurs the variable "state"
13179 * is used to figure out how far we had gotten.
13181 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13182 int ash_main(int argc UNUSED_PARAM, char **argv)
13184 const char *shinit;
13185 volatile smallint state;
13186 struct jmploc jmploc;
13187 struct stackmark smark;
13189 /* Initialize global data */
13193 #if ENABLE_ASH_ALIAS
13199 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13202 #if ENABLE_FEATURE_EDITING
13203 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13206 if (setjmp(jmploc.loc)) {
13212 e = exception_type;
13216 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13219 outcslow('\n', stderr);
13221 popstackmark(&smark);
13222 FORCE_INT_ON; /* enable interrupts */
13231 exception_handler = &jmploc;
13234 TRACE(("Shell args: "));
13235 trace_puts_args(argv);
13237 rootpid = getpid();
13240 setstackmark(&smark);
13243 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13245 const char *hp = lookupvar("HISTFILE");
13248 hp = lookupvar("HOME");
13250 char *defhp = concat_path_file(hp, ".ash_history");
13251 setvar("HISTFILE", defhp, 0);
13257 if (/* argv[0] && */ argv[0][0] == '-')
13261 read_profile("/etc/profile");
13264 read_profile(".profile");
13270 getuid() == geteuid() && getgid() == getegid() &&
13274 shinit = lookupvar("ENV");
13275 if (shinit != NULL && *shinit != '\0') {
13276 read_profile(shinit);
13282 /* evalstring pushes parsefile stack.
13283 * Ensure we don't falsely claim that 0 (stdin)
13284 * is one of stacked source fds.
13285 * Testcase: ash -c 'exec 1>&0' must not complain. */
13287 g_parsefile->fd = -1;
13288 evalstring(minusc, 0);
13291 if (sflag || minusc == NULL) {
13292 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13294 const char *hp = lookupvar("HISTFILE");
13296 line_input_state->hist_file = hp;
13299 state4: /* XXX ??? - why isn't this before the "if" statement */
13307 extern void _mcleanup(void);
13317 * Copyright (c) 1989, 1991, 1993, 1994
13318 * The Regents of the University of California. All rights reserved.
13320 * This code is derived from software contributed to Berkeley by
13321 * Kenneth Almquist.
13323 * Redistribution and use in source and binary forms, with or without
13324 * modification, are permitted provided that the following conditions
13326 * 1. Redistributions of source code must retain the above copyright
13327 * notice, this list of conditions and the following disclaimer.
13328 * 2. Redistributions in binary form must reproduce the above copyright
13329 * notice, this list of conditions and the following disclaimer in the
13330 * documentation and/or other materials provided with the distribution.
13331 * 3. Neither the name of the University nor the names of its contributors
13332 * may be used to endorse or promote products derived from this software
13333 * without specific prior written permission.
13335 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13336 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13337 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13338 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13339 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13340 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13341 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13342 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13343 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13344 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF