1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
9 * was re-ported from NetBSD and debianized.
11 * This code is derived from software contributed to Berkeley by
14 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
16 * Original BSD copyright notice is retained at the end of this file.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
39 #define JOBS ENABLE_ASH_JOB_CONTROL
47 #include "busybox.h" /* for applet_names */
48 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49 //#include "applet_tables.h" doesn't work
54 #if ENABLE_ASH_RANDOM_SUPPORT
58 #if defined SINGLE_APPLET_MAIN
59 /* STANDALONE does not make sense, and won't compile */
60 # undef CONFIG_FEATURE_SH_STANDALONE
61 # undef ENABLE_FEATURE_SH_STANDALONE
62 # undef IF_FEATURE_SH_STANDALONE
63 # undef IF_NOT_FEATURE_SH_STANDALONE(...)
64 # define ENABLE_FEATURE_SH_STANDALONE 0
65 # define IF_FEATURE_SH_STANDALONE(...)
66 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
70 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
73 #if defined(__uClinux__)
74 # error "Do not even bother, ash will not run on NOMMU machine"
78 /* ============ Hash table sizes. Configurable. */
82 #define CMDTABLESIZE 31 /* should be prime */
85 /* ============ Shell options */
87 static const char *const optletters_optnames[] = {
108 #define optletters(n) optletters_optnames[(n)][0]
109 #define optnames(n) (&optletters_optnames[(n)][1])
111 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
114 /* ============ Misc data */
116 static const char homestr[] ALIGN1 = "HOME";
117 static const char snlfmt[] ALIGN1 = "%s\n";
118 static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
121 * We enclose jmp_buf in a structure so that we can declare pointers to
122 * jump locations. The global variable handler contains the location to
123 * jump to when an exception occurs, and the global variable exception_type
124 * contains a code identifying the exception. To implement nested
125 * exception handlers, the user should save the value of handler on entry
126 * to an inner scope, set handler to point to a jmploc structure for the
127 * inner scope, and restore handler on exit from the scope.
133 struct globals_misc {
134 /* pid of main shell */
136 /* shell level: 0 for the main shell, 1 for its children, and so on */
138 #define rootshell (!shlvl)
139 char *minusc; /* argument to -c option */
141 char *curdir; // = nullstr; /* current working directory */
142 char *physdir; // = nullstr; /* physical working directory */
144 char *arg0; /* value of $0 */
146 struct jmploc *exception_handler;
148 volatile int suppress_int; /* counter */
149 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
150 /* last pending signal */
151 volatile /*sig_atomic_t*/ smallint pending_sig;
152 smallint exception_type; /* kind of exception (0..5) */
154 #define EXINT 0 /* SIGINT received */
155 #define EXERROR 1 /* a generic error */
156 #define EXSHELLPROC 2 /* execute a shell procedure */
157 #define EXEXEC 3 /* command execution failed */
158 #define EXEXIT 4 /* exit the shell */
159 #define EXSIG 5 /* trapped signal in wait(1) */
162 char nullstr[1]; /* zero length string */
165 #define eflag optlist[0]
166 #define fflag optlist[1]
167 #define Iflag optlist[2]
168 #define iflag optlist[3]
169 #define mflag optlist[4]
170 #define nflag optlist[5]
171 #define sflag optlist[6]
172 #define xflag optlist[7]
173 #define vflag optlist[8]
174 #define Cflag optlist[9]
175 #define aflag optlist[10]
176 #define bflag optlist[11]
177 #define uflag optlist[12]
178 #define viflag optlist[13]
180 #define nolog optlist[14]
181 #define debug optlist[15]
184 /* trap handler commands */
186 * Sigmode records the current value of the signal handlers for the various
187 * modes. A value of zero means that the current handler is not known.
188 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
190 char sigmode[NSIG - 1];
191 #define S_DFL 1 /* default signal handling (SIG_DFL) */
192 #define S_CATCH 2 /* signal is caught */
193 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
194 #define S_HARD_IGN 4 /* signal is ignored permenantly */
196 /* indicates specified signal received */
197 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
199 char **trap_ptr; /* used only by "trap hack" */
201 /* Rarely referenced stuff */
202 #if ENABLE_ASH_RANDOM_SUPPORT
205 pid_t backgndpid; /* pid of last background process */
206 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
208 extern struct globals_misc *const ash_ptr_to_globals_misc;
209 #define G_misc (*ash_ptr_to_globals_misc)
210 #define rootpid (G_misc.rootpid )
211 #define shlvl (G_misc.shlvl )
212 #define minusc (G_misc.minusc )
213 #define curdir (G_misc.curdir )
214 #define physdir (G_misc.physdir )
215 #define arg0 (G_misc.arg0 )
216 #define exception_handler (G_misc.exception_handler)
217 #define exception_type (G_misc.exception_type )
218 #define suppress_int (G_misc.suppress_int )
219 #define pending_int (G_misc.pending_int )
220 #define pending_sig (G_misc.pending_sig )
221 #define isloginsh (G_misc.isloginsh )
222 #define nullstr (G_misc.nullstr )
223 #define optlist (G_misc.optlist )
224 #define sigmode (G_misc.sigmode )
225 #define gotsig (G_misc.gotsig )
226 #define trap (G_misc.trap )
227 #define trap_ptr (G_misc.trap_ptr )
228 #define random_gen (G_misc.random_gen )
229 #define backgndpid (G_misc.backgndpid )
230 #define job_warning (G_misc.job_warning)
231 #define INIT_G_misc() do { \
232 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
240 /* ============ DEBUG */
242 static void trace_printf(const char *fmt, ...);
243 static void trace_vprintf(const char *fmt, va_list va);
244 # define TRACE(param) trace_printf param
245 # define TRACEV(param) trace_vprintf param
246 # define close(fd) do { \
248 if (close(dfd) < 0) \
249 bb_error_msg("bug on %d: closing %d(0x%x)", \
250 __LINE__, dfd, dfd); \
253 # define TRACE(param)
254 # define TRACEV(param)
258 /* ============ Utility functions */
259 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
261 /* C99 says: "char" declaration may be signed or unsigned by default */
262 #define signed_char2int(sc) ((int)(signed char)(sc))
264 static int isdigit_str9(const char *str)
266 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
267 while (--maxlen && isdigit(*str))
269 return (*str == '\0');
273 /* ============ Interrupts / exceptions */
275 * These macros allow the user to suspend the handling of interrupt signals
276 * over a period of time. This is similar to SIGHOLD or to sigblock, but
277 * much more efficient and portable. (But hacking the kernel is so much
278 * more fun than worrying about efficiency and portability. :-))
280 #define INT_OFF do { \
286 * Called to raise an exception. Since C doesn't include exceptions, we
287 * just do a longjmp to the exception handler. The type of exception is
288 * stored in the global variable "exception_type".
290 static void raise_exception(int) NORETURN;
292 raise_exception(int e)
295 if (exception_handler == NULL)
300 longjmp(exception_handler->loc, 1);
303 #define raise_exception(e) do { \
304 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
305 raise_exception(e); \
310 * Called from trap.c when a SIGINT is received. (If the user specifies
311 * that SIGINT is to be trapped or ignored using the trap builtin, then
312 * this routine is not called.) Suppressint is nonzero when interrupts
313 * are held using the INT_OFF macro. (The test for iflag is just
314 * defensive programming.)
316 static void raise_interrupt(void) NORETURN;
318 raise_interrupt(void)
323 /* Signal is not automatically unmasked after it is raised,
324 * do it ourself - unmask all signals */
325 sigprocmask_allsigs(SIG_UNBLOCK);
326 /* pending_sig = 0; - now done in onsig() */
329 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
330 if (!(rootshell && iflag)) {
331 /* Kill ourself with SIGINT */
332 signal(SIGINT, SIG_DFL);
337 raise_exception(ex_type);
341 #define raise_interrupt() do { \
342 TRACE(("raising interrupt on line %d\n", __LINE__)); \
347 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
351 if (--suppress_int == 0 && pending_int) {
355 #define INT_ON int_on()
356 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
364 #define FORCE_INT_ON force_int_on()
366 #define SAVE_INT(v) ((v) = suppress_int)
368 #define RESTORE_INT(v) do { \
370 suppress_int = (v); \
371 if (suppress_int == 0 && pending_int) \
376 /* ============ Stdout/stderr output */
379 outstr(const char *p, FILE *file)
387 flush_stdout_stderr(void)
404 outcslow(int c, FILE *dest)
412 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
414 out1fmt(const char *fmt, ...)
421 r = vprintf(fmt, ap);
427 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
429 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
436 ret = vsnprintf(outbuf, length, fmt, ap);
443 out1str(const char *p)
449 out2str(const char *p)
456 /* ============ Parser structures */
458 /* control characters in argument strings */
459 #define CTLESC ((unsigned char)'\201') /* escape next character */
460 #define CTLVAR ((unsigned char)'\202') /* variable defn */
461 #define CTLENDVAR ((unsigned char)'\203')
462 #define CTLBACKQ ((unsigned char)'\204')
463 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
464 /* CTLBACKQ | CTLQUOTE == '\205' */
465 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
466 #define CTLENDARI ((unsigned char)'\207')
467 #define CTLQUOTEMARK ((unsigned char)'\210')
469 /* variable substitution byte (follows CTLVAR) */
470 #define VSTYPE 0x0f /* type of variable substitution */
471 #define VSNUL 0x10 /* colon--treat the empty string as unset */
472 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
474 /* values of VSTYPE field */
475 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
476 #define VSMINUS 0x2 /* ${var-text} */
477 #define VSPLUS 0x3 /* ${var+text} */
478 #define VSQUESTION 0x4 /* ${var?message} */
479 #define VSASSIGN 0x5 /* ${var=text} */
480 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
481 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
482 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
483 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
484 #define VSLENGTH 0xa /* ${#var} */
485 #if ENABLE_ASH_BASH_COMPAT
486 #define VSSUBSTR 0xc /* ${var:position:length} */
487 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
488 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491 static const char dolatstr[] ALIGN1 = {
492 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
512 #if ENABLE_ASH_BASH_COMPAT
529 smallint type; /* Nxxxx */
532 union node *redirect;
537 smallint pipe_backgnd;
538 struct nodelist *cmdlist;
544 union node *redirect;
557 union node *elsepart;
584 struct nodelist *backquote;
587 /* nfile and ndup layout must match!
588 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
589 * that it is actually NTO2 (>&file), and change its type.
606 char *_unused_expfname;
625 struct nredir nredir;
626 struct nbinary nbinary;
630 struct nclist nclist;
639 * NODE_EOF is returned by parsecmd when it encounters an end of file.
640 * It must be distinct from NULL.
642 #define NODE_EOF ((union node *) -1L)
645 struct nodelist *next;
658 freefunc(struct funcnode *f)
660 if (f && --f->count < 0)
665 /* ============ Debugging output */
669 static FILE *tracefile;
672 trace_printf(const char *fmt, ...)
679 fprintf(tracefile, "%u ", (int) time(NULL));
681 fprintf(tracefile, "[%u] ", (int) getpid());
683 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
685 vfprintf(tracefile, fmt, va);
690 trace_vprintf(const char *fmt, va_list va)
695 fprintf(tracefile, "%u ", (int) time(NULL));
697 fprintf(tracefile, "[%u] ", (int) getpid());
699 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
700 vfprintf(tracefile, fmt, va);
704 trace_puts(const char *s)
712 trace_puts_quoted(char *s)
719 putc('"', tracefile);
720 for (p = s; *p; p++) {
722 case '\n': c = 'n'; goto backslash;
723 case '\t': c = 't'; goto backslash;
724 case '\r': c = 'r'; goto backslash;
725 case '"': c = '"'; goto backslash;
726 case '\\': c = '\\'; goto backslash;
727 case CTLESC: c = 'e'; goto backslash;
728 case CTLVAR: c = 'v'; goto backslash;
729 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
730 case CTLBACKQ: c = 'q'; goto backslash;
731 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
733 putc('\\', tracefile);
737 if (*p >= ' ' && *p <= '~')
740 putc('\\', tracefile);
741 putc(*p >> 6 & 03, tracefile);
742 putc(*p >> 3 & 07, tracefile);
743 putc(*p & 07, tracefile);
748 putc('"', tracefile);
752 trace_puts_args(char **ap)
759 trace_puts_quoted(*ap);
761 putc('\n', tracefile);
764 putc(' ', tracefile);
779 /* leave open because libedit might be using it */
782 strcpy(s, "./trace");
784 if (!freopen(s, "a", tracefile)) {
785 fprintf(stderr, "Can't re-open %s\n", s);
790 tracefile = fopen(s, "a");
791 if (tracefile == NULL) {
792 fprintf(stderr, "Can't open %s\n", s);
798 flags = fcntl(fileno(tracefile), F_GETFL);
800 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
802 setlinebuf(tracefile);
803 fputs("\nTracing started.\n", tracefile);
807 indent(int amount, char *pfx, FILE *fp)
811 for (i = 0; i < amount; i++) {
812 if (pfx && i == amount - 1)
818 /* little circular references here... */
819 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822 sharg(union node *arg, FILE *fp)
825 struct nodelist *bqlist;
828 if (arg->type != NARG) {
829 out1fmt("<node type %d>\n", arg->type);
832 bqlist = arg->narg.backquote;
833 for (p = arg->narg.text; *p; p++) {
842 if (subtype == VSLENGTH)
851 switch (subtype & VSTYPE) {
884 out1fmt("<subtype %d>", subtype);
891 case CTLBACKQ|CTLQUOTE:
894 shtree(bqlist->n, -1, NULL, fp);
905 shcmd(union node *cmd, FILE *fp)
913 for (np = cmd->ncmd.args; np; np = np->narg.next) {
919 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
923 switch (np->nfile.type) {
924 case NTO: s = ">>"+1; dftfd = 1; break;
925 case NCLOBBER: s = ">|"; dftfd = 1; break;
926 case NAPPEND: s = ">>"; dftfd = 1; break;
927 #if ENABLE_ASH_BASH_COMPAT
930 case NTOFD: s = ">&"; dftfd = 1; break;
931 case NFROM: s = "<"; break;
932 case NFROMFD: s = "<&"; break;
933 case NFROMTO: s = "<>"; break;
934 default: s = "*error*"; break;
936 if (np->nfile.fd != dftfd)
937 fprintf(fp, "%d", np->nfile.fd);
939 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
940 fprintf(fp, "%d", np->ndup.dupfd);
942 sharg(np->nfile.fname, fp);
949 shtree(union node *n, int ind, char *pfx, FILE *fp)
957 indent(ind, pfx, fp);
974 shtree(n->nbinary.ch1, ind, NULL, fp);
977 shtree(n->nbinary.ch2, ind, NULL, fp);
985 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
986 shtree(lp->n, 0, NULL, fp);
990 if (n->npipe.pipe_backgnd)
996 fprintf(fp, "<node type %d>", n->type);
1004 showtree(union node *n)
1006 trace_puts("showtree called\n");
1007 shtree(n, 1, NULL, stderr);
1013 /* ============ Parser data */
1016 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 struct strlist *next;
1026 struct strpush *prev; /* preceding string on stack */
1028 int prev_left_in_line;
1029 #if ENABLE_ASH_ALIAS
1030 struct alias *ap; /* if push was associated with an alias */
1032 char *string; /* remember the string since it may change */
1036 struct parsefile *prev; /* preceding file on stack */
1037 int linno; /* current line */
1038 int fd; /* file descriptor (or -1 if string) */
1039 int left_in_line; /* number of chars left in this line */
1040 int left_in_buffer; /* number of chars left in this buffer past the line */
1041 char *next_to_pgetc; /* next char in buffer */
1042 char *buf; /* input buffer */
1043 struct strpush *strpush; /* for pushing strings at this level */
1044 struct strpush basestrpush; /* so pushing one is fast */
1047 static struct parsefile basepf; /* top level input file */
1048 static struct parsefile *g_parsefile = &basepf; /* current input file */
1049 static int startlinno; /* line # where last token started */
1050 static char *commandname; /* currently executing command */
1051 static struct strlist *cmdenviron; /* environment for builtin command */
1052 static uint8_t exitstatus; /* exit status of last command */
1055 /* ============ Message printing */
1058 ash_vmsg(const char *msg, va_list ap)
1060 fprintf(stderr, "%s: ", arg0);
1062 if (strcmp(arg0, commandname))
1063 fprintf(stderr, "%s: ", commandname);
1064 if (!iflag || g_parsefile->fd)
1065 fprintf(stderr, "line %d: ", startlinno);
1067 vfprintf(stderr, msg, ap);
1068 outcslow('\n', stderr);
1072 * Exverror is called to raise the error exception. If the second argument
1073 * is not NULL then error prints an error message using printf style
1074 * formatting. It then raises the error exception.
1076 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1078 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1082 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1084 TRACE(("\") pid=%d\n", getpid()));
1086 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1091 flush_stdout_stderr();
1092 raise_exception(cond);
1096 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1098 ash_msg_and_raise_error(const char *msg, ...)
1103 ash_vmsg_and_raise(EXERROR, msg, ap);
1108 static void raise_error_syntax(const char *) NORETURN;
1110 raise_error_syntax(const char *msg)
1112 ash_msg_and_raise_error("syntax error: %s", msg);
1116 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1118 ash_msg_and_raise(int cond, const char *msg, ...)
1123 ash_vmsg_and_raise(cond, msg, ap);
1129 * error/warning routines for external builtins
1132 ash_msg(const char *fmt, ...)
1142 * Return a string describing an error. The returned string may be a
1143 * pointer to a static buffer that will be overwritten on the next call.
1144 * Action describes the operation that got the error.
1147 errmsg(int e, const char *em)
1149 if (e == ENOENT || e == ENOTDIR) {
1156 /* ============ Memory allocation */
1159 /* 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;
1594 len = strspn(s, "'");
1598 q = p = makestrspace(len + 3, p);
1601 q = (char *)memcpy(q, s, 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 */
2615 #if ENABLE_ASH_ALIAS
2619 #define PEOA_OR_PEOF PEOA
2623 #define PEOA_OR_PEOF PEOF
2626 /* number syntax index */
2627 #define BASESYNTAX 0 /* not in quotes */
2628 #define DQSYNTAX 1 /* in double quotes */
2629 #define SQSYNTAX 2 /* in single quotes */
2630 #define ARISYNTAX 3 /* in arithmetic */
2631 #define PSSYNTAX 4 /* prompt */
2633 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
2634 #define USE_SIT_FUNCTION
2637 #if ENABLE_SH_MATH_SUPPORT
2638 static const char S_I_T[][4] = {
2639 #if ENABLE_ASH_ALIAS
2640 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
2642 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2643 { CNL, CNL, CNL, CNL }, /* 2, \n */
2644 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2645 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2646 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2647 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2648 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2649 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2650 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2651 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2652 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
2653 #ifndef USE_SIT_FUNCTION
2654 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2655 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2656 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2660 static const char S_I_T[][3] = {
2661 #if ENABLE_ASH_ALIAS
2662 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
2664 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2665 { CNL, CNL, CNL }, /* 2, \n */
2666 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2667 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2668 { CVAR, CVAR, CWORD }, /* 5, $ */
2669 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2670 { CSPCL, CWORD, CWORD }, /* 7, ( */
2671 { CSPCL, CWORD, CWORD }, /* 8, ) */
2672 { CBACK, CBACK, CCTL }, /* 9, \ */
2673 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2674 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
2675 #ifndef USE_SIT_FUNCTION
2676 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2677 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2678 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
2681 #endif /* SH_MATH_SUPPORT */
2683 #ifdef USE_SIT_FUNCTION
2686 SIT(int c, int syntax)
2688 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2689 #if ENABLE_ASH_ALIAS
2690 static const char syntax_index_table[] ALIGN1 = {
2691 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2692 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2693 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2697 static const char syntax_index_table[] ALIGN1 = {
2698 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2699 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2700 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2707 if (c == PEOF) { /* 2^8+2 */
2710 #if ENABLE_ASH_ALIAS
2711 if (c == PEOA) { /* 2^8+1 */
2716 if ((unsigned char)c >= CTLESC
2717 && (unsigned char)c <= CTLQUOTEMARK
2721 s = strchrnul(spec_symbls, c);
2725 indx = syntax_index_table[s - spec_symbls];
2727 return S_I_T[indx][syntax];
2730 #else /* !USE_SIT_FUNCTION */
2732 #if ENABLE_ASH_ALIAS
2733 #define CSPCL_CIGN_CIGN_CIGN 0
2734 #define CSPCL_CWORD_CWORD_CWORD 1
2735 #define CNL_CNL_CNL_CNL 2
2736 #define CWORD_CCTL_CCTL_CWORD 3
2737 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2738 #define CVAR_CVAR_CWORD_CVAR 5
2739 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2740 #define CSPCL_CWORD_CWORD_CLP 7
2741 #define CSPCL_CWORD_CWORD_CRP 8
2742 #define CBACK_CBACK_CCTL_CBACK 9
2743 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2744 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2745 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2746 #define CWORD_CWORD_CWORD_CWORD 13
2747 #define CCTL_CCTL_CCTL_CCTL 14
2749 #define CSPCL_CWORD_CWORD_CWORD 0
2750 #define CNL_CNL_CNL_CNL 1
2751 #define CWORD_CCTL_CCTL_CWORD 2
2752 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2753 #define CVAR_CVAR_CWORD_CVAR 4
2754 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2755 #define CSPCL_CWORD_CWORD_CLP 6
2756 #define CSPCL_CWORD_CWORD_CRP 7
2757 #define CBACK_CBACK_CCTL_CBACK 8
2758 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2759 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2760 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2761 #define CWORD_CWORD_CWORD_CWORD 12
2762 #define CCTL_CCTL_CCTL_CCTL 13
2765 static const char syntax_index_table[258] = {
2766 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2767 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
2768 #if ENABLE_ASH_ALIAS
2769 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2771 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2773 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2774 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2775 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2776 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2777 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2778 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2779 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2780 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2910 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2932 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2933 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2934 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2936 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2938 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2939 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2940 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2941 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2944 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2946 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2959 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2960 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2961 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2962 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2991 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2992 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2993 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2996 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3024 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3025 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3026 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
3029 #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
3031 #endif /* USE_SIT_FUNCTION */
3034 /* ============ Alias handling */
3036 #if ENABLE_ASH_ALIAS
3038 #define ALIASINUSE 1
3049 static struct alias **atab; // [ATABSIZE];
3050 #define INIT_G_alias() do { \
3051 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3055 static struct alias **
3056 __lookupalias(const char *name) {
3057 unsigned int hashval;
3064 ch = (unsigned char)*p;
3068 ch = (unsigned char)*++p;
3070 app = &atab[hashval % ATABSIZE];
3072 for (; *app; app = &(*app)->next) {
3073 if (strcmp(name, (*app)->name) == 0) {
3081 static struct alias *
3082 lookupalias(const char *name, int check)
3084 struct alias *ap = *__lookupalias(name);
3086 if (check && ap && (ap->flag & ALIASINUSE))
3091 static struct alias *
3092 freealias(struct alias *ap)
3096 if (ap->flag & ALIASINUSE) {
3097 ap->flag |= ALIASDEAD;
3109 setalias(const char *name, const char *val)
3111 struct alias *ap, **app;
3113 app = __lookupalias(name);
3117 if (!(ap->flag & ALIASINUSE)) {
3120 ap->val = ckstrdup(val);
3121 ap->flag &= ~ALIASDEAD;
3124 ap = ckzalloc(sizeof(struct alias));
3125 ap->name = ckstrdup(name);
3126 ap->val = ckstrdup(val);
3127 /*ap->flag = 0; - ckzalloc did it */
3128 /*ap->next = NULL;*/
3135 unalias(const char *name)
3139 app = __lookupalias(name);
3143 *app = freealias(*app);
3154 struct alias *ap, **app;
3158 for (i = 0; i < ATABSIZE; i++) {
3160 for (ap = *app; ap; ap = *app) {
3161 *app = freealias(*app);
3171 printalias(const struct alias *ap)
3173 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3177 * TODO - sort output
3179 static int FAST_FUNC
3180 aliascmd(int argc UNUSED_PARAM, char **argv)
3189 for (i = 0; i < ATABSIZE; i++) {
3190 for (ap = atab[i]; ap; ap = ap->next) {
3196 while ((n = *++argv) != NULL) {
3197 v = strchr(n+1, '=');
3198 if (v == NULL) { /* n+1: funny ksh stuff */
3199 ap = *__lookupalias(n);
3201 fprintf(stderr, "%s: %s not found\n", "alias", n);
3214 static int FAST_FUNC
3215 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3219 while ((i = nextopt("a")) != '\0') {
3225 for (i = 0; *argptr; argptr++) {
3226 if (unalias(*argptr)) {
3227 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3235 #endif /* ASH_ALIAS */
3238 /* ============ jobs.c */
3240 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3243 #define FORK_NOJOB 2
3245 /* mode flags for showjob(s) */
3246 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3247 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3248 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3251 * A job structure contains information about a job. A job is either a
3252 * single process or a set of processes contained in a pipeline. In the
3253 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3257 pid_t pid; /* process id */
3258 int status; /* last process status from wait() */
3259 char *cmd; /* text of command being run */
3263 struct procstat ps0; /* status of process */
3264 struct procstat *ps; /* status or processes when more than one */
3266 int stopstatus; /* status of a stopped job */
3269 nprocs: 16, /* number of processes */
3271 #define JOBRUNNING 0 /* at least one proc running */
3272 #define JOBSTOPPED 1 /* all procs are stopped */
3273 #define JOBDONE 2 /* all procs are completed */
3275 sigint: 1, /* job was killed by SIGINT */
3276 jobctl: 1, /* job running under job control */
3278 waited: 1, /* true if this entry has been waited for */
3279 used: 1, /* true if this entry is in used */
3280 changed: 1; /* true if status has changed */
3281 struct job *prev_job; /* previous job */
3284 static struct job *makejob(/*union node *,*/ int);
3285 static int forkshell(struct job *, union node *, int);
3286 static int waitforjob(struct job *);
3289 enum { doing_jobctl = 0 };
3290 #define setjobctl(on) do {} while (0)
3292 static smallint doing_jobctl; //references:8
3293 static void setjobctl(int);
3300 ignoresig(int signo)
3302 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3303 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3304 /* No, need to do it */
3305 signal(signo, SIG_IGN);
3307 sigmode[signo - 1] = S_HARD_IGN;
3311 * Signal handler. Only one usage site - in setsignal()
3316 gotsig[signo - 1] = 1;
3318 if (signo == SIGINT && !trap[SIGINT]) {
3319 if (!suppress_int) {
3321 raise_interrupt(); /* does not return */
3325 pending_sig = signo;
3330 * Set the signal handler for the specified signal. The routine figures
3331 * out what it should be set to.
3334 setsignal(int signo)
3337 char cur_act, new_act;
3338 struct sigaction act;
3342 if (t != NULL) { /* trap for this sig is set */
3344 if (t[0] == '\0') /* trap is "": ignore this sig */
3348 if (rootshell && new_act == S_DFL) {
3351 if (iflag || minusc || sflag == 0)
3360 * "In all cases, bash ignores SIGQUIT. Non-builtin
3361 * commands run by bash have signal handlers
3362 * set to the values inherited by the shell
3363 * from its parent". */
3379 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3380 //whereas we have to restore it to what shell got on entry
3381 //from the parent. See comment above
3383 t = &sigmode[signo - 1];
3386 /* current setting is not yet known */
3387 if (sigaction(signo, NULL, &act)) {
3388 /* pretend it worked; maybe we should give a warning,
3389 * but other shells don't. We don't alter sigmode,
3390 * so we retry every time.
3391 * btw, in Linux it never fails. --vda */
3394 if (act.sa_handler == SIG_IGN) {
3395 cur_act = S_HARD_IGN;
3397 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3399 cur_act = S_IGN; /* don't hard ignore these */
3403 if (cur_act == S_HARD_IGN || cur_act == new_act)
3406 act.sa_handler = SIG_DFL;
3409 act.sa_handler = onsig;
3410 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3411 sigfillset(&act.sa_mask); /* ditto */
3414 act.sa_handler = SIG_IGN;
3417 sigaction_set(signo, &act);
3422 /* mode flags for set_curjob */
3423 #define CUR_DELETE 2
3424 #define CUR_RUNNING 1
3425 #define CUR_STOPPED 0
3427 /* mode flags for dowait */
3428 #define DOWAIT_NONBLOCK WNOHANG
3429 #define DOWAIT_BLOCK 0
3432 /* pgrp of shell on invocation */
3433 static int initialpgrp; //references:2
3434 static int ttyfd = -1; //5
3437 static struct job *jobtab; //5
3439 static unsigned njobs; //4
3441 static struct job *curjob; //lots
3442 /* number of presumed living untracked jobs */
3443 static int jobless; //4
3446 set_curjob(struct job *jp, unsigned mode)
3449 struct job **jpp, **curp;
3451 /* first remove from list */
3452 jpp = curp = &curjob;
3457 jpp = &jp1->prev_job;
3459 *jpp = jp1->prev_job;
3461 /* Then re-insert in correct position */
3469 /* job being deleted */
3472 /* newly created job or backgrounded job,
3473 put after all stopped jobs. */
3477 if (!jp1 || jp1->state != JOBSTOPPED)
3480 jpp = &jp1->prev_job;
3486 /* newly stopped job - becomes curjob */
3487 jp->prev_job = *jpp;
3495 jobno(const struct job *jp)
3497 return jp - jobtab + 1;
3502 * Convert a job name to a job structure.
3505 #define getjob(name, getctl) getjob(name)
3508 getjob(const char *name, int getctl)
3512 const char *err_msg = "%s: no such job";
3516 char *(*match)(const char *, const char *);
3531 if (c == '+' || c == '%') {
3533 err_msg = "No current job";
3539 err_msg = "No previous job";
3550 jp = jobtab + num - 1;
3565 if (match(jp->ps[0].cmd, p)) {
3569 err_msg = "%s: ambiguous";
3579 err_msg = "job %s not created under job control";
3580 if (getctl && jp->jobctl == 0)
3585 ash_msg_and_raise_error(err_msg, name);
3589 * Mark a job structure as unused.
3592 freejob(struct job *jp)
3594 struct procstat *ps;
3598 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3599 if (ps->cmd != nullstr)
3602 if (jp->ps != &jp->ps0)
3605 set_curjob(jp, CUR_DELETE);
3611 xtcsetpgrp(int fd, pid_t pgrp)
3613 if (tcsetpgrp(fd, pgrp))
3614 ash_msg_and_raise_error("can't set tty process group (%m)");
3618 * Turn job control on and off.
3620 * Note: This code assumes that the third arg to ioctl is a character
3621 * pointer, which is true on Berkeley systems but not System V. Since
3622 * System V doesn't have job control yet, this isn't a problem now.
3624 * Called with interrupts off.
3632 if (on == doing_jobctl || rootshell == 0)
3636 ofd = fd = open(_PATH_TTY, O_RDWR);
3638 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3639 * That sometimes helps to acquire controlling tty.
3640 * Obviously, a workaround for bugs when someone
3641 * failed to provide a controlling tty to bash! :) */
3647 fd = fcntl(fd, F_DUPFD, 10);
3652 /* fd is a tty at this point */
3653 close_on_exec_on(fd);
3654 do { /* while we are in the background */
3655 pgrp = tcgetpgrp(fd);
3658 ash_msg("can't access tty; job control turned off");
3662 if (pgrp == getpgrp())
3673 xtcsetpgrp(fd, pgrp);
3675 /* turning job control off */
3678 /* was xtcsetpgrp, but this can make exiting ash
3679 * loop forever if pty is already deleted */
3680 tcsetpgrp(fd, pgrp);
3694 static int FAST_FUNC
3695 killcmd(int argc, char **argv)
3698 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3700 if (argv[i][0] == '%') {
3701 struct job *jp = getjob(argv[i], 0);
3702 unsigned pid = jp->ps[0].pid;
3703 /* Enough space for ' -NNN<nul>' */
3704 argv[i] = alloca(sizeof(int)*3 + 3);
3705 /* kill_main has matching code to expect
3706 * leading space. Needed to not confuse
3707 * negative pids with "kill -SIGNAL_NO" syntax */
3708 sprintf(argv[i], " -%u", pid);
3710 } while (argv[++i]);
3712 return kill_main(argc, argv);
3716 showpipe(struct job *jp, FILE *out)
3718 struct procstat *sp;
3719 struct procstat *spend;
3721 spend = jp->ps + jp->nprocs;
3722 for (sp = jp->ps + 1; sp < spend; sp++)
3723 fprintf(out, " | %s", sp->cmd);
3724 outcslow('\n', out);
3725 flush_stdout_stderr();
3730 restartjob(struct job *jp, int mode)
3732 struct procstat *ps;
3738 if (jp->state == JOBDONE)
3740 jp->state = JOBRUNNING;
3742 if (mode == FORK_FG)
3743 xtcsetpgrp(ttyfd, pgid);
3744 killpg(pgid, SIGCONT);
3748 if (WIFSTOPPED(ps->status)) {
3754 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3759 static int FAST_FUNC
3760 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3767 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3772 jp = getjob(*argv, 1);
3773 if (mode == FORK_BG) {
3774 set_curjob(jp, CUR_RUNNING);
3775 fprintf(out, "[%d] ", jobno(jp));
3777 outstr(jp->ps->cmd, out);
3779 retval = restartjob(jp, mode);
3780 } while (*argv && *++argv);
3786 sprint_status(char *s, int status, int sigonly)
3792 if (!WIFEXITED(status)) {
3794 if (WIFSTOPPED(status))
3795 st = WSTOPSIG(status);
3798 st = WTERMSIG(status);
3800 if (st == SIGINT || st == SIGPIPE)
3803 if (WIFSTOPPED(status))
3808 col = fmtstr(s, 32, strsignal(st));
3809 if (WCOREDUMP(status)) {
3810 col += fmtstr(s + col, 16, " (core dumped)");
3812 } else if (!sigonly) {
3813 st = WEXITSTATUS(status);
3815 col = fmtstr(s, 16, "Done(%d)", st);
3817 col = fmtstr(s, 16, "Done");
3824 dowait(int wait_flags, struct job *job)
3829 struct job *thisjob;
3832 TRACE(("dowait(0x%x) called\n", wait_flags));
3834 /* Do a wait system call. If job control is compiled in, we accept
3835 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3836 * NB: _not_ safe_waitpid, we need to detect EINTR */
3837 pid = waitpid(-1, &status,
3838 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
3839 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3840 pid, status, errno, strerror(errno)));
3846 for (jp = curjob; jp; jp = jp->prev_job) {
3847 struct procstat *sp;
3848 struct procstat *spend;
3849 if (jp->state == JOBDONE)
3852 spend = jp->ps + jp->nprocs;
3855 if (sp->pid == pid) {
3856 TRACE(("Job %d: changing status of proc %d "
3857 "from 0x%x to 0x%x\n",
3858 jobno(jp), pid, sp->status, status));
3859 sp->status = status;
3862 if (sp->status == -1)
3865 if (state == JOBRUNNING)
3867 if (WIFSTOPPED(sp->status)) {
3868 jp->stopstatus = sp->status;
3872 } while (++sp < spend);
3877 if (!WIFSTOPPED(status))
3883 if (state != JOBRUNNING) {
3884 thisjob->changed = 1;
3886 if (thisjob->state != state) {
3887 TRACE(("Job %d: changing state from %d to %d\n",
3888 jobno(thisjob), thisjob->state, state));
3889 thisjob->state = state;
3891 if (state == JOBSTOPPED) {
3892 set_curjob(thisjob, CUR_STOPPED);
3901 if (thisjob && thisjob == job) {
3905 len = sprint_status(s, status, 1);
3916 blocking_wait_with_raise_on_sig(struct job *job)
3918 pid_t pid = dowait(DOWAIT_BLOCK, job);
3919 if (pid <= 0 && pending_sig)
3920 raise_exception(EXSIG);
3926 showjob(FILE *out, struct job *jp, int mode)
3928 struct procstat *ps;
3929 struct procstat *psend;
3936 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
3937 /* just output process (group) id of pipeline */
3938 fprintf(out, "%d\n", ps->pid);
3942 col = fmtstr(s, 16, "[%d] ", jobno(jp));
3947 else if (curjob && jp == curjob->prev_job)
3950 if (mode & SHOW_PIDS)
3951 col += fmtstr(s + col, 16, "%d ", ps->pid);
3953 psend = ps + jp->nprocs;
3955 if (jp->state == JOBRUNNING) {
3956 strcpy(s + col, "Running");
3957 col += sizeof("Running") - 1;
3959 int status = psend[-1].status;
3960 if (jp->state == JOBSTOPPED)
3961 status = jp->stopstatus;
3962 col += sprint_status(s + col, status, 0);
3964 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
3966 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3967 * or prints several "PID | <cmdN>" lines,
3968 * depending on SHOW_PIDS bit.
3969 * We do not print status of individual processes
3970 * between PID and <cmdN>. bash does it, but not very well:
3971 * first line shows overall job status, not process status,
3972 * making it impossible to know 1st process status.
3976 /* for each process */
3979 if (mode & SHOW_PIDS)
3980 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
3982 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3985 fprintf(out, "%s", ps->cmd);
3989 outcslow('\n', out);
3993 if (jp->state == JOBDONE) {
3994 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4000 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4001 * statuses have changed since the last call to showjobs.
4004 showjobs(FILE *out, int mode)
4008 TRACE(("showjobs(0x%x) called\n", mode));
4010 /* Handle all finished jobs */
4011 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4014 for (jp = curjob; jp; jp = jp->prev_job) {
4015 if (!(mode & SHOW_CHANGED) || jp->changed) {
4016 showjob(out, jp, mode);
4021 static int FAST_FUNC
4022 jobscmd(int argc UNUSED_PARAM, char **argv)
4027 while ((m = nextopt("lp")) != '\0') {
4031 mode |= SHOW_ONLY_PGID;
4037 showjob(stdout, getjob(*argv, 0), mode);
4040 showjobs(stdout, mode);
4047 getstatus(struct job *job)
4052 status = job->ps[job->nprocs - 1].status;
4053 retval = WEXITSTATUS(status);
4054 if (!WIFEXITED(status)) {
4056 retval = WSTOPSIG(status);
4057 if (!WIFSTOPPED(status))
4060 /* XXX: limits number of signals */
4061 retval = WTERMSIG(status);
4063 if (retval == SIGINT)
4069 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4070 jobno(job), job->nprocs, status, retval));
4074 static int FAST_FUNC
4075 waitcmd(int argc UNUSED_PARAM, char **argv)
4082 raise_exception(EXSIG);
4089 /* wait for all jobs */
4093 if (!jp) /* no running procs */
4095 if (jp->state == JOBRUNNING)
4101 * "When bash is waiting for an asynchronous command via
4102 * the wait builtin, the reception of a signal for which a trap
4103 * has been set will cause the wait builtin to return immediately
4104 * with an exit status greater than 128, immediately after which
4105 * the trap is executed."
4106 * Do we do it that way? */
4107 blocking_wait_with_raise_on_sig(NULL);
4113 if (**argv != '%') {
4114 pid_t pid = number(*argv);
4119 if (job->ps[job->nprocs - 1].pid == pid)
4121 job = job->prev_job;
4124 job = getjob(*argv, 0);
4125 /* loop until process terminated or stopped */
4126 while (job->state == JOBRUNNING)
4127 blocking_wait_with_raise_on_sig(NULL);
4129 retval = getstatus(job);
4142 struct job *jp, *jq;
4144 len = njobs * sizeof(*jp);
4146 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4148 offset = (char *)jp - (char *)jq;
4150 /* Relocate pointers */
4153 jq = (struct job *)((char *)jq + l);
4157 #define joff(p) ((struct job *)((char *)(p) + l))
4158 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4159 if (joff(jp)->ps == &jq->ps0)
4160 jmove(joff(jp)->ps);
4161 if (joff(jp)->prev_job)
4162 jmove(joff(jp)->prev_job);
4172 jp = (struct job *)((char *)jp + len);
4176 } while (--jq >= jp);
4181 * Return a new job structure.
4182 * Called with interrupts off.
4185 makejob(/*union node *node,*/ int nprocs)
4190 for (i = njobs, jp = jobtab; ; jp++) {
4197 if (jp->state != JOBDONE || !jp->waited)
4206 memset(jp, 0, sizeof(*jp));
4208 /* jp->jobctl is a bitfield.
4209 * "jp->jobctl |= jobctl" likely to give awful code */
4213 jp->prev_job = curjob;
4218 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4220 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4227 * Return a string identifying a command (to be printed by the
4230 static char *cmdnextc;
4233 cmdputs(const char *s)
4235 static const char vstype[VSTYPE + 1][3] = {
4236 "", "}", "-", "+", "?", "=",
4237 "%", "%%", "#", "##"
4238 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4241 const char *p, *str;
4242 char c, cc[2] = " ";
4247 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4249 while ((c = *p++) != 0) {
4257 if ((subtype & VSTYPE) == VSLENGTH)
4261 if (!(subtype & VSQUOTE) == !(quoted & 1))
4267 str = "\"}" + !(quoted & 1);
4274 case CTLBACKQ+CTLQUOTE:
4277 #if ENABLE_SH_MATH_SUPPORT
4292 if ((subtype & VSTYPE) != VSNORMAL)
4294 str = vstype[subtype & VSTYPE];
4295 if (subtype & VSNUL)
4304 /* These can only happen inside quotes */
4317 while ((c = *str++) != '\0') {
4322 USTPUTC('"', nextc);
4328 /* cmdtxt() and cmdlist() call each other */
4329 static void cmdtxt(union node *n);
4332 cmdlist(union node *np, int sep)
4334 for (; np; np = np->narg.next) {
4338 if (sep && np->narg.next)
4344 cmdtxt(union node *n)
4347 struct nodelist *lp;
4358 lp = n->npipe.cmdlist;
4376 cmdtxt(n->nbinary.ch1);
4392 cmdtxt(n->nif.test);
4394 if (n->nif.elsepart) {
4395 cmdtxt(n->nif.ifpart);
4397 n = n->nif.elsepart;
4415 cmdtxt(n->nbinary.ch1);
4425 cmdputs(n->nfor.var);
4427 cmdlist(n->nfor.args, 1);
4432 cmdputs(n->narg.text);
4436 cmdlist(n->ncmd.args, 1);
4437 cmdlist(n->ncmd.redirect, 0);
4450 cmdputs(n->ncase.expr->narg.text);
4452 for (np = n->ncase.cases; np; np = np->nclist.next) {
4453 cmdtxt(np->nclist.pattern);
4455 cmdtxt(np->nclist.body);
4469 #if ENABLE_ASH_BASH_COMPAT
4484 cmdputs(utoa(n->nfile.fd));
4486 if (n->type == NTOFD || n->type == NFROMFD) {
4487 cmdputs(utoa(n->ndup.dupfd));
4496 commandtext(union node *n)
4500 STARTSTACKSTR(cmdnextc);
4502 name = stackblock();
4503 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4504 name, cmdnextc, cmdnextc));
4505 return ckstrdup(name);
4510 * Fork off a subshell. If we are doing job control, give the subshell its
4511 * own process group. Jp is a job structure that the job is to be added to.
4512 * N is the command that will be evaluated by the child. Both jp and n may
4513 * be NULL. The mode parameter can be one of the following:
4514 * FORK_FG - Fork off a foreground process.
4515 * FORK_BG - Fork off a background process.
4516 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4517 * process group even if job control is on.
4519 * When job control is turned off, background processes have their standard
4520 * input redirected to /dev/null (except for the second and later processes
4523 * Called with interrupts off.
4526 * Clear traps on a fork.
4533 for (tp = trap; tp < &trap[NSIG]; tp++) {
4534 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4536 if (trap_ptr == trap)
4538 /* else: it "belongs" to trap_ptr vector, don't free */
4540 if ((tp - trap) != 0)
4541 setsignal(tp - trap);
4547 /* Lives far away from here, needed for forkchild */
4548 static void closescript(void);
4550 /* Called after fork(), in child */
4551 static NOINLINE void
4552 forkchild(struct job *jp, union node *n, int mode)
4556 TRACE(("Child shell %d\n", getpid()));
4560 /* man bash: "Non-builtin commands run by bash have signal handlers
4561 * set to the values inherited by the shell from its parent".
4562 * Do we do it correctly? */
4566 if (mode == FORK_NOJOB /* is it `xxx` ? */
4567 && n && n->type == NCMD /* is it single cmd? */
4568 /* && n->ncmd.args->type == NARG - always true? */
4569 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4570 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4571 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4573 TRACE(("Trap hack\n"));
4574 /* Awful hack for `trap` or $(trap).
4576 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4577 * contains an example where "trap" is executed in a subshell:
4579 * save_traps=$(trap)
4581 * eval "$save_traps"
4583 * Standard does not say that "trap" in subshell shall print
4584 * parent shell's traps. It only says that its output
4585 * must have suitable form, but then, in the above example
4586 * (which is not supposed to be normative), it implies that.
4588 * bash (and probably other shell) does implement it
4589 * (traps are reset to defaults, but "trap" still shows them),
4590 * but as a result, "trap" logic is hopelessly messed up:
4593 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4594 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4595 * # true | trap <--- trap is in subshell - no output (ditto)
4596 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4597 * trap -- 'echo Ho' SIGWINCH
4598 * # echo `(trap)` <--- in subshell in subshell - output
4599 * trap -- 'echo Ho' SIGWINCH
4600 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4601 * trap -- 'echo Ho' SIGWINCH
4603 * The rules when to forget and when to not forget traps
4604 * get really complex and nonsensical.
4606 * Our solution: ONLY bare $(trap) or `trap` is special.
4608 /* Save trap handler strings for trap builtin to print */
4609 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4610 /* Fall through into clearing traps */
4614 /* do job control only in root shell */
4616 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4619 if (jp->nprocs == 0)
4622 pgrp = jp->ps[0].pid;
4623 /* this can fail because we are doing it in the parent also */
4625 if (mode == FORK_FG)
4626 xtcsetpgrp(ttyfd, pgrp);
4631 if (mode == FORK_BG) {
4632 /* man bash: "When job control is not in effect,
4633 * asynchronous commands ignore SIGINT and SIGQUIT" */
4636 if (jp->nprocs == 0) {
4638 if (open(bb_dev_null, O_RDONLY) != 0)
4639 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4643 if (iflag) { /* why if iflag only? */
4648 * "In all cases, bash ignores SIGQUIT. Non-builtin
4649 * commands run by bash have signal handlers
4650 * set to the values inherited by the shell
4652 * Take care of the second rule: */
4656 if (n && n->type == NCMD
4657 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4659 TRACE(("Job hack\n"));
4660 /* "jobs": we do not want to clear job list for it,
4661 * instead we remove only _its_ own_ job from job list.
4662 * This makes "jobs .... | cat" more useful.
4668 for (jp = curjob; jp; jp = jp->prev_job)
4673 /* Called after fork(), in parent */
4675 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4678 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4680 TRACE(("In parent shell: child = %d\n", pid));
4682 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4688 if (mode != FORK_NOJOB && jp->jobctl) {
4691 if (jp->nprocs == 0)
4694 pgrp = jp->ps[0].pid;
4695 /* This can fail because we are doing it in the child also */
4699 if (mode == FORK_BG) {
4700 backgndpid = pid; /* set $! */
4701 set_curjob(jp, CUR_RUNNING);
4704 struct procstat *ps = &jp->ps[jp->nprocs++];
4709 if (doing_jobctl && n)
4710 ps->cmd = commandtext(n);
4716 forkshell(struct job *jp, union node *n, int mode)
4720 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4723 TRACE(("Fork failed, errno=%d", errno));
4726 ash_msg_and_raise_error("can't fork");
4729 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4730 forkchild(jp, n, mode);
4732 forkparent(jp, n, mode, pid);
4738 * Wait for job to finish.
4740 * Under job control we have the problem that while a child process
4741 * is running interrupts generated by the user are sent to the child
4742 * but not to the shell. This means that an infinite loop started by
4743 * an interactive user may be hard to kill. With job control turned off,
4744 * an interactive user may place an interactive program inside a loop.
4745 * If the interactive program catches interrupts, the user doesn't want
4746 * these interrupts to also abort the loop. The approach we take here
4747 * is to have the shell ignore interrupt signals while waiting for a
4748 * foreground process to terminate, and then send itself an interrupt
4749 * signal if the child process was terminated by an interrupt signal.
4750 * Unfortunately, some programs want to do a bit of cleanup and then
4751 * exit on interrupt; unless these processes terminate themselves by
4752 * sending a signal to themselves (instead of calling exit) they will
4753 * confuse this approach.
4755 * Called with interrupts off.
4758 waitforjob(struct job *jp)
4762 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4765 while (jp->state == JOBRUNNING) {
4766 /* In non-interactive shells, we _can_ get
4767 * a keyboard signal here and be EINTRed,
4768 * but we just loop back, waiting for command to complete.
4771 * "If bash is waiting for a command to complete and receives
4772 * a signal for which a trap has been set, the trap
4773 * will not be executed until the command completes."
4775 * Reality is that even if trap is not set, bash
4776 * will not act on the signal until command completes.
4777 * Try this. sleep5intoff.c:
4778 * #include <signal.h>
4779 * #include <unistd.h>
4782 * sigemptyset(&set);
4783 * sigaddset(&set, SIGINT);
4784 * sigaddset(&set, SIGQUIT);
4785 * sigprocmask(SIG_BLOCK, &set, NULL);
4789 * $ bash -c './sleep5intoff; echo hi'
4790 * ^C^C^C^C <--- pressing ^C once a second
4792 * $ bash -c './sleep5intoff; echo hi'
4793 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4796 dowait(DOWAIT_BLOCK, jp);
4803 xtcsetpgrp(ttyfd, rootpid);
4805 * This is truly gross.
4806 * If we're doing job control, then we did a TIOCSPGRP which
4807 * caused us (the shell) to no longer be in the controlling
4808 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4809 * intuit from the subprocess exit status whether a SIGINT
4810 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4812 if (jp->sigint) /* TODO: do the same with all signals */
4813 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4815 if (jp->state == JOBDONE)
4822 * return 1 if there are stopped jobs, otherwise 0
4834 if (jp && jp->state == JOBSTOPPED) {
4835 out2str("You have stopped jobs.\n");
4844 /* ============ redir.c
4846 * Code for dealing with input/output redirection.
4849 #define EMPTY -2 /* marks an unused slot in redirtab */
4850 #define CLOSED -3 /* marks a slot of previously-closed fd */
4853 * Open a file in noclobber mode.
4854 * The code was copied from bash.
4857 noclobberopen(const char *fname)
4860 struct stat finfo, finfo2;
4863 * If the file exists and is a regular file, return an error
4866 r = stat(fname, &finfo);
4867 if (r == 0 && S_ISREG(finfo.st_mode)) {
4873 * If the file was not present (r != 0), make sure we open it
4874 * exclusively so that if it is created before we open it, our open
4875 * will fail. Make sure that we do not truncate an existing file.
4876 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4877 * file was not a regular file, we leave O_EXCL off.
4880 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4881 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4883 /* If the open failed, return the file descriptor right away. */
4888 * OK, the open succeeded, but the file may have been changed from a
4889 * non-regular file to a regular file between the stat and the open.
4890 * We are assuming that the O_EXCL open handles the case where FILENAME
4891 * did not exist and is symlinked to an existing file between the stat
4896 * If we can open it and fstat the file descriptor, and neither check
4897 * revealed that it was a regular file, and the file has not been
4898 * replaced, return the file descriptor.
4900 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4901 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4904 /* The file has been replaced. badness. */
4911 * Handle here documents. Normally we fork off a process to write the
4912 * data to a pipe. If the document is short, we can stuff the data in
4913 * the pipe without forking.
4915 /* openhere needs this forward reference */
4916 static void expandhere(union node *arg, int fd);
4918 openhere(union node *redir)
4924 ash_msg_and_raise_error("pipe call failed");
4925 if (redir->type == NHERE) {
4926 len = strlen(redir->nhere.doc->narg.text);
4927 if (len <= PIPE_BUF) {
4928 full_write(pip[1], redir->nhere.doc->narg.text, len);
4932 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4935 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4936 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4937 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4938 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
4939 signal(SIGPIPE, SIG_DFL);
4940 if (redir->type == NHERE)
4941 full_write(pip[1], redir->nhere.doc->narg.text, len);
4943 expandhere(redir->nhere.doc, pip[1]);
4944 _exit(EXIT_SUCCESS);
4952 openredirect(union node *redir)
4957 switch (redir->nfile.type) {
4959 fname = redir->nfile.expfname;
4960 f = open(fname, O_RDONLY);
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4971 #if ENABLE_ASH_BASH_COMPAT
4974 /* Take care of noclobber mode. */
4976 fname = redir->nfile.expfname;
4977 f = noclobberopen(fname);
4984 fname = redir->nfile.expfname;
4985 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4990 fname = redir->nfile.expfname;
4991 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4999 /* Fall through to eliminate warning. */
5000 /* Our single caller does this itself */
5007 f = openhere(redir);
5013 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5015 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5019 * Copy a file descriptor to be >= to. Returns -1
5020 * if the source file descriptor is closed, EMPTY if there are no unused
5021 * file descriptors left.
5023 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5024 * old code was doing close(to) prior to copyfd() to achieve the same */
5026 COPYFD_EXACT = (int)~(INT_MAX),
5027 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5030 copyfd(int from, int to)
5034 if (to & COPYFD_EXACT) {
5035 to &= ~COPYFD_EXACT;
5037 newfd = dup2(from, to);
5039 newfd = fcntl(from, F_DUPFD, to);
5042 if (errno == EMFILE)
5044 /* Happens when source fd is not open: try "echo >&99" */
5045 ash_msg_and_raise_error("%d: %m", from);
5050 /* Struct def and variable are moved down to the first usage site */
5055 struct redirtab *next;
5058 struct two_fd_t two_fd[];
5060 #define redirlist (G_var.redirlist)
5062 static int need_to_remember(struct redirtab *rp, int fd)
5066 if (!rp) /* remembering was not requested */
5069 for (i = 0; i < rp->pair_count; i++) {
5070 if (rp->two_fd[i].orig == fd) {
5071 /* already remembered */
5078 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5079 static int is_hidden_fd(struct redirtab *rp, int fd)
5082 struct parsefile *pf;
5095 fd |= COPYFD_RESTORE;
5096 for (i = 0; i < rp->pair_count; i++) {
5097 if (rp->two_fd[i].copy == fd) {
5105 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5106 * old file descriptors are stashed away so that the redirection can be
5107 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5108 * standard output, and the standard error if it becomes a duplicate of
5109 * stdout, is saved in memory.
5111 /* flags passed to redirect */
5112 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5113 #define REDIR_SAVEFD2 03 /* set preverrout */
5115 redirect(union node *redir, int flags)
5117 struct redirtab *sv;
5122 int copied_fd2 = -1;
5132 if (flags & REDIR_PUSH) {
5133 union node *tmp = redir;
5136 #if ENABLE_ASH_BASH_COMPAT
5137 if (redir->nfile.type == NTO2)
5140 tmp = tmp->nfile.next;
5142 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5143 sv->next = redirlist;
5144 sv->pair_count = sv_pos;
5146 sv->nullredirs = g_nullredirs - 1;
5148 while (sv_pos > 0) {
5150 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5155 fd = redir->nfile.fd;
5156 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5157 int right_fd = redir->ndup.dupfd;
5158 /* redirect from/to same file descriptor? */
5161 /* echo >&10 and 10 is a fd opened to the sh script? */
5162 if (is_hidden_fd(sv, right_fd)) {
5163 errno = EBADF; /* as if it is closed */
5164 ash_msg_and_raise_error("%d: %m", right_fd);
5168 newfd = openredirect(redir); /* always >= 0 */
5170 /* Descriptor wasn't open before redirect.
5171 * Mark it for close in the future */
5172 if (need_to_remember(sv, fd)) {
5173 goto remember_to_close;
5178 #if ENABLE_ASH_BASH_COMPAT
5181 if (need_to_remember(sv, fd)) {
5182 /* Copy old descriptor */
5183 i = fcntl(fd, F_DUPFD, 10);
5184 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5185 * are closed in popredir() in the child, preventing them from leaking
5186 * into child. (popredir() also cleans up the mess in case of failures)
5191 /* Strange error (e.g. "too many files" EMFILE?) */
5195 ash_msg_and_raise_error("%d: %m", fd);
5198 /* EBADF: it is not open - good, remember to close it */
5201 } else { /* fd is open, save its copy */
5202 /* "exec fd>&-" should not close fds
5203 * which point to script file(s).
5204 * Force them to be restored afterwards */
5205 if (is_hidden_fd(sv, fd))
5206 i |= COPYFD_RESTORE;
5210 sv->two_fd[sv_pos].orig = fd;
5211 sv->two_fd[sv_pos].copy = i;
5215 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5216 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5217 /* Don't want to trigger debugging */
5221 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5223 } else if (fd != newfd) { /* move newfd to fd */
5224 copyfd(newfd, fd | COPYFD_EXACT);
5225 #if ENABLE_ASH_BASH_COMPAT
5226 if (!(redir->nfile.type == NTO2 && fd == 2))
5230 #if ENABLE_ASH_BASH_COMPAT
5231 if (redir->nfile.type == NTO2 && fd == 1) {
5232 /* We already redirected it to fd 1, now copy it to 2 */
5238 } while ((redir = redir->nfile.next) != NULL);
5241 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5242 preverrout_fd = copied_fd2;
5246 * Undo the effects of the last redirection.
5249 popredir(int drop, int restore)
5251 struct redirtab *rp;
5254 if (--g_nullredirs >= 0)
5258 for (i = 0; i < rp->pair_count; i++) {
5259 int fd = rp->two_fd[i].orig;
5260 int copy = rp->two_fd[i].copy;
5261 if (copy == CLOSED) {
5266 if (copy != EMPTY) {
5267 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5268 copy &= ~COPYFD_RESTORE;
5270 copyfd(copy, fd | COPYFD_EXACT);
5272 close(copy & ~COPYFD_RESTORE);
5275 redirlist = rp->next;
5276 g_nullredirs = rp->nullredirs;
5282 * Undo all redirections. Called on error or interrupt.
5286 * Discard all saved file descriptors.
5289 clearredir(int drop)
5295 popredir(drop, /*restore:*/ 0);
5300 redirectsafe(union node *redir, int flags)
5303 volatile int saveint;
5304 struct jmploc *volatile savehandler = exception_handler;
5305 struct jmploc jmploc;
5308 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5309 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5311 exception_handler = &jmploc;
5312 redirect(redir, flags);
5314 exception_handler = savehandler;
5315 if (err && exception_type != EXERROR)
5316 longjmp(exception_handler->loc, 1);
5317 RESTORE_INT(saveint);
5322 /* ============ Routines to expand arguments to commands
5324 * We have to deal with backquotes, shell variables, and file metacharacters.
5327 #if ENABLE_SH_MATH_SUPPORT
5329 ash_arith(const char *s)
5331 arith_eval_hooks_t math_hooks;
5335 math_hooks.lookupvar = lookupvar;
5336 math_hooks.setvar = setvar;
5337 math_hooks.endofname = endofname;
5340 result = arith(s, &errcode, &math_hooks);
5343 ash_msg_and_raise_error("exponent less than 0");
5345 ash_msg_and_raise_error("divide by zero");
5347 ash_msg_and_raise_error("expression recursion loop detected");
5348 raise_error_syntax(s);
5359 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5360 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5361 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5362 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5363 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5364 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5365 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5366 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5367 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5371 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5372 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5373 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5374 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5375 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5378 * Structure specifying which parts of the string should be searched
5379 * for IFS characters.
5382 struct ifsregion *next; /* next region in list */
5383 int begoff; /* offset of start of region */
5384 int endoff; /* offset of end of region */
5385 int nulonly; /* search for nul bytes only */
5389 struct strlist *list;
5390 struct strlist **lastp;
5393 /* output of current string */
5394 static char *expdest;
5395 /* list of back quote expressions */
5396 static struct nodelist *argbackq;
5397 /* first struct in list of ifs regions */
5398 static struct ifsregion ifsfirst;
5399 /* last struct in list */
5400 static struct ifsregion *ifslastp;
5401 /* holds expanded arg list */
5402 static struct arglist exparg;
5412 expdest = makestrspace(32, expdest);
5413 len = fmtstr(expdest, 32, arith_t_fmt, num);
5414 STADJUST(len, expdest);
5419 esclen(const char *start, const char *p)
5423 while (p > start && (unsigned char)*--p == CTLESC) {
5430 * Remove any CTLESC characters from a string.
5433 rmescapes(char *str, int flag)
5435 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5439 unsigned protect_against_glob;
5442 p = strpbrk(str, qchars);
5448 if (flag & RMESCAPE_ALLOC) {
5449 size_t len = p - str;
5450 size_t fulllen = len + strlen(p) + 1;
5452 if (flag & RMESCAPE_GROW) {
5453 r = makestrspace(fulllen, expdest);
5454 } else if (flag & RMESCAPE_HEAP) {
5455 r = ckmalloc(fulllen);
5457 r = stalloc(fulllen);
5461 q = (char *)memcpy(q, str, len) + len;
5465 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5466 globbing = flag & RMESCAPE_GLOB;
5467 protect_against_glob = globbing;
5469 if (*p == CTLQUOTEMARK) {
5470 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5471 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5472 // Note: both inquotes and protect_against_glob only affect whether
5473 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5474 inquotes = ~inquotes;
5476 protect_against_glob = globbing;
5480 /* naked back slash */
5481 protect_against_glob = 0;
5486 if (protect_against_glob && inquotes && *p != '/') {
5490 protect_against_glob = globbing;
5495 if (flag & RMESCAPE_GROW) {
5497 STADJUST(q - r + 1, expdest);
5501 #define pmatch(a, b) !fnmatch((a), (b), 0)
5504 * Prepare a pattern for a expmeta (internal glob(3)) call.
5506 * Returns an stalloced string.
5509 preglob(const char *pattern, int quoted, int flag)
5511 flag |= RMESCAPE_GLOB;
5513 flag |= RMESCAPE_QUOTED;
5515 return rmescapes((char *)pattern, flag);
5519 * Put a string on the stack.
5522 memtodest(const char *p, size_t len, int syntax, int quotes)
5526 q = makestrspace(quotes ? len * 2 : len, q);
5529 int c = signed_char2int(*p++);
5533 int n = SIT(c, syntax);
5534 if (n == CCTL || n == CBACK)
5544 strtodest(const char *p, int syntax, int quotes)
5546 memtodest(p, strlen(p), syntax, quotes);
5550 * Record the fact that we have to scan this region of the
5551 * string for IFS characters.
5554 recordregion(int start, int end, int nulonly)
5556 struct ifsregion *ifsp;
5558 if (ifslastp == NULL) {
5562 ifsp = ckzalloc(sizeof(*ifsp));
5563 /*ifsp->next = NULL; - ckzalloc did it */
5564 ifslastp->next = ifsp;
5568 ifslastp->begoff = start;
5569 ifslastp->endoff = end;
5570 ifslastp->nulonly = nulonly;
5574 removerecordregions(int endoff)
5576 if (ifslastp == NULL)
5579 if (ifsfirst.endoff > endoff) {
5580 while (ifsfirst.next != NULL) {
5581 struct ifsregion *ifsp;
5583 ifsp = ifsfirst.next->next;
5584 free(ifsfirst.next);
5585 ifsfirst.next = ifsp;
5588 if (ifsfirst.begoff > endoff)
5591 ifslastp = &ifsfirst;
5592 ifsfirst.endoff = endoff;
5597 ifslastp = &ifsfirst;
5598 while (ifslastp->next && ifslastp->next->begoff < endoff)
5599 ifslastp=ifslastp->next;
5600 while (ifslastp->next != NULL) {
5601 struct ifsregion *ifsp;
5603 ifsp = ifslastp->next->next;
5604 free(ifslastp->next);
5605 ifslastp->next = ifsp;
5608 if (ifslastp->endoff > endoff)
5609 ifslastp->endoff = endoff;
5613 exptilde(char *startp, char *p, int flags)
5619 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5624 while ((c = *++p) != '\0') {
5631 if (flags & EXP_VARTILDE)
5641 if (*name == '\0') {
5642 home = lookupvar(homestr);
5644 pw = getpwnam(name);
5649 if (!home || !*home)
5652 startloc = expdest - (char *)stackblock();
5653 strtodest(home, SQSYNTAX, quotes);
5654 recordregion(startloc, expdest - (char *)stackblock(), 0);
5662 * Execute a command inside back quotes. If it's a builtin command, we
5663 * want to save its output in a block obtained from malloc. Otherwise
5664 * we fork off a subprocess and get the output of the command via a pipe.
5665 * Should be called with interrupts off.
5667 struct backcmd { /* result of evalbackcmd */
5668 int fd; /* file descriptor to read from */
5669 int nleft; /* number of chars in buffer */
5670 char *buf; /* buffer */
5671 struct job *jp; /* job structure for command */
5674 /* These forward decls are needed to use "eval" code for backticks handling: */
5675 static uint8_t back_exitstatus; /* exit status of backquoted command */
5676 #define EV_EXIT 01 /* exit after evaluating tree */
5677 static void evaltree(union node *, int);
5679 static void FAST_FUNC
5680 evalbackcmd(union node *n, struct backcmd *result)
5691 saveherefd = herefd;
5699 ash_msg_and_raise_error("pipe call failed");
5700 jp = makejob(/*n,*/ 1);
5701 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5706 copyfd(pip[1], 1 | COPYFD_EXACT);
5710 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5714 result->fd = pip[0];
5717 herefd = saveherefd;
5719 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5720 result->fd, result->buf, result->nleft, result->jp));
5724 * Expand stuff in backwards quotes.
5727 expbackq(union node *cmd, int quoted, int quotes)
5735 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5736 struct stackmark smark;
5739 setstackmark(&smark);
5741 startloc = dest - (char *)stackblock();
5743 evalbackcmd(cmd, &in);
5744 popstackmark(&smark);
5751 memtodest(p, i, syntax, quotes);
5755 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5756 TRACE(("expbackq: read returns %d\n", i));
5765 back_exitstatus = waitforjob(in.jp);
5769 /* Eat all trailing newlines */
5771 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5776 recordregion(startloc, dest - (char *)stackblock(), 0);
5777 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5778 (dest - (char *)stackblock()) - startloc,
5779 (dest - (char *)stackblock()) - startloc,
5780 stackblock() + startloc));
5783 #if ENABLE_SH_MATH_SUPPORT
5785 * Expand arithmetic expression. Backup to start of expression,
5786 * evaluate, place result in (backed up) result, adjust string position.
5799 * This routine is slightly over-complicated for
5800 * efficiency. Next we scan backwards looking for the
5801 * start of arithmetic.
5803 start = stackblock();
5810 while (*p != CTLARI) {
5814 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5819 esc = esclen(start, p);
5829 removerecordregions(begoff);
5836 rmescapes(p + 2, 0);
5838 len = cvtnum(ash_arith(p + 2));
5841 recordregion(begoff, begoff + len, 0);
5845 /* argstr needs it */
5846 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5849 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5850 * characters to allow for further processing. Otherwise treat
5851 * $@ like $* since no splitting will be performed.
5853 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5854 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5855 * for correct expansion of "B=$A" word.
5858 argstr(char *p, int flags, struct strlist *var_str_list)
5860 static const char spclchars[] ALIGN1 = {
5868 CTLBACKQ | CTLQUOTE,
5869 #if ENABLE_SH_MATH_SUPPORT
5874 const char *reject = spclchars;
5876 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5877 int breakall = flags & EXP_WORD;
5882 if (!(flags & EXP_VARTILDE)) {
5884 } else if (flags & EXP_VARTILDE2) {
5889 if (flags & EXP_TILDE) {
5892 flags &= ~EXP_TILDE;
5895 if (*q == CTLESC && (flags & EXP_QWORD))
5898 p = exptilde(p, q, flags);
5901 startloc = expdest - (char *)stackblock();
5903 length += strcspn(p + length, reject);
5904 c = (unsigned char) p[length];
5907 #if ENABLE_SH_MATH_SUPPORT
5911 /* c == '=' || c == ':' || c == CTLENDARI */
5917 expdest = stack_nputstr(p, length, expdest);
5918 newloc = expdest - (char *)stackblock();
5919 if (breakall && !inquotes && newloc > startloc) {
5920 recordregion(startloc, newloc, 0);
5931 if (flags & EXP_VARTILDE2) {
5935 flags |= EXP_VARTILDE2;
5940 * sort of a hack - expand tildes in variable
5941 * assignments (after the first '=' and after ':'s).
5950 case CTLENDVAR: /* ??? */
5953 /* "$@" syntax adherence hack */
5955 && memcmp(p, dolatstr, 4) == 0
5956 && ( p[4] == CTLQUOTEMARK
5957 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5960 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
5963 inquotes = !inquotes;
5976 p = evalvar(p, flags, var_str_list);
5980 case CTLBACKQ|CTLQUOTE:
5981 expbackq(argbackq->n, c, quotes);
5982 argbackq = argbackq->next;
5984 #if ENABLE_SH_MATH_SUPPORT
5997 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
6000 // This commented out code was added by James Simmons <jsimmons@infradead.org>
6001 // as part of a larger change when he added support for ${var/a/b}.
6002 // However, it broke # and % operators:
6006 //echo ${var#ab} abcdcd abcdcd
6007 //echo ${var##ab} abcdcd abcdcd
6008 //echo ${var#a*b} abcdcd ababcdcd (!)
6009 //echo ${var##a*b} cdcd cdcd
6010 //echo ${var#?} babcdcd ababcdcd (!)
6011 //echo ${var##?} babcdcd babcdcd
6012 //echo ${var#*} ababcdcd babcdcd (!)
6014 //echo ${var%cd} ababcd ababcd
6015 //echo ${var%%cd} ababcd abab (!)
6016 //echo ${var%c*d} ababcd ababcd
6017 //echo ${var%%c*d} abab ababcdcd (!)
6018 //echo ${var%?} ababcdc ababcdc
6019 //echo ${var%%?} ababcdc ababcdcd (!)
6020 //echo ${var%*} ababcdcd ababcdcd
6023 // Commenting it back out helped. Remove it completely if it really
6026 char *loc, *loc2; //, *full;
6032 int match; // = strlen(str);
6033 const char *s = loc2;
6040 match = pmatch(str, s); // this line was deleted
6042 // // chop off end if its '*'
6043 // full = strrchr(str, '*');
6044 // if (full && full != str)
6047 // // If str starts with '*' replace with s.
6048 // if ((*str == '*') && strlen(s) >= match) {
6049 // full = xstrdup(s);
6050 // strncpy(full+strlen(s)-match+1, str+1, match-1);
6052 // full = xstrndup(str, match);
6053 // match = strncmp(s, full, strlen(full));
6057 if (match) // if (!match)
6059 if (quotes && *loc == CTLESC)
6068 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6075 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6078 const char *s = loc2;
6083 match = pmatch(str, s);
6090 esc = esclen(startp, loc);
6101 static void varunset(const char *, const char *, const char *, int) NORETURN;
6103 varunset(const char *end, const char *var, const char *umsg, int varflags)
6109 msg = "parameter not set";
6111 if (*end == CTLENDVAR) {
6112 if (varflags & VSNUL)
6118 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6121 #if ENABLE_ASH_BASH_COMPAT
6123 parse_sub_pattern(char *arg, int inquotes)
6125 char *idx, *repl = NULL;
6134 /* Only the first '/' seen is our separator */
6141 if (!inquotes && c == '\\' && arg[1] == '\\')
6142 arg++; /* skip both \\, not just first one */
6149 #endif /* ENABLE_ASH_BASH_COMPAT */
6152 subevalvar(char *p, char *str, int strloc, int subtype,
6153 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6155 struct nodelist *saveargbackq = argbackq;
6158 char *rmesc, *rmescend;
6159 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6160 IF_ASH_BASH_COMPAT(char null = '\0';)
6161 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6162 int saveherefd = herefd;
6163 int amount, workloc, resetloc;
6165 char *(*scan)(char*, char*, char*, char*, int, int);
6168 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6170 STPUTC('\0', expdest);
6171 herefd = saveherefd;
6172 argbackq = saveargbackq;
6173 startp = (char *)stackblock() + startloc;
6177 setvar(str, startp, 0);
6178 amount = startp - expdest;
6179 STADJUST(amount, expdest);
6182 #if ENABLE_ASH_BASH_COMPAT
6184 loc = str = stackblock() + strloc;
6185 /* Read POS in ${var:POS:LEN} */
6186 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6187 len = str - startp - 1;
6189 /* *loc != '\0', guaranteed by parser */
6193 /* Adjust the length by the number of escapes */
6194 for (ptr = startp; ptr < (str - 1); ptr++) {
6195 if (*ptr == CTLESC) {
6203 if (*loc++ == ':') {
6207 /* Skip POS in ${var:POS:LEN} */
6209 while (*loc && *loc != ':') {
6211 * bash complains on: var=qwe; echo ${var:1a:123}
6213 ash_msg_and_raise_error(msg_illnum, str);
6217 if (*loc++ == ':') {
6221 if (pos >= orig_len) {
6225 if (len > (orig_len - pos))
6226 len = orig_len - pos;
6228 for (str = startp; pos; str++, pos--) {
6229 if (quotes && *str == CTLESC)
6232 for (loc = startp; len; len--) {
6233 if (quotes && *str == CTLESC)
6238 amount = loc - expdest;
6239 STADJUST(amount, expdest);
6244 varunset(p, str, startp, varflags);
6247 resetloc = expdest - (char *)stackblock();
6249 /* We'll comeback here if we grow the stack while handling
6250 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6251 * stack will need rebasing, and we'll need to remove our work
6254 IF_ASH_BASH_COMPAT(restart:)
6256 amount = expdest - ((char *)stackblock() + resetloc);
6257 STADJUST(-amount, expdest);
6258 startp = (char *)stackblock() + startloc;
6261 rmescend = (char *)stackblock() + strloc;
6263 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6264 if (rmesc != startp) {
6266 startp = (char *)stackblock() + startloc;
6270 str = (char *)stackblock() + strloc;
6271 preglob(str, varflags & VSQUOTE, 0);
6272 workloc = expdest - (char *)stackblock();
6274 #if ENABLE_ASH_BASH_COMPAT
6275 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6276 char *idx, *end, *restart_detect;
6279 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6284 /* If there's no pattern to match, return the expansion unmolested */
6292 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6294 /* No match, advance */
6295 restart_detect = stackblock();
6296 STPUTC(*idx, expdest);
6297 if (quotes && *idx == CTLESC) {
6300 STPUTC(*idx, expdest);
6302 if (stackblock() != restart_detect)
6310 if (subtype == VSREPLACEALL) {
6312 if (quotes && *idx == CTLESC)
6321 for (loc = repl; *loc; loc++) {
6322 restart_detect = stackblock();
6323 STPUTC(*loc, expdest);
6324 if (stackblock() != restart_detect)
6329 if (subtype == VSREPLACE) {
6331 restart_detect = stackblock();
6332 STPUTC(*idx, expdest);
6333 if (stackblock() != restart_detect)
6342 /* We've put the replaced text into a buffer at workloc, now
6343 * move it to the right place and adjust the stack.
6345 startp = stackblock() + startloc;
6346 STPUTC('\0', expdest);
6347 memmove(startp, stackblock() + workloc, len);
6348 startp[len++] = '\0';
6349 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6350 STADJUST(-amount, expdest);
6353 #endif /* ENABLE_ASH_BASH_COMPAT */
6355 subtype -= VSTRIMRIGHT;
6357 if (subtype < 0 || subtype > 7)
6360 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6361 zero = subtype >> 1;
6362 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6363 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6365 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6368 memmove(startp, loc, str - loc);
6369 loc = startp + (str - loc) - 1;
6372 amount = loc - expdest;
6373 STADJUST(amount, expdest);
6379 * Add the value of a specialized variable to the stack string.
6380 * name parameter (examples):
6381 * ash -c 'echo $1' name:'1='
6382 * ash -c 'echo $qwe' name:'qwe='
6383 * ash -c 'echo $$' name:'$='
6384 * ash -c 'echo ${$}' name:'$='
6385 * ash -c 'echo ${$##q}' name:'$=q'
6386 * ash -c 'echo ${#$}' name:'$='
6387 * note: examples with bad shell syntax:
6388 * ash -c 'echo ${#$1}' name:'$=1'
6389 * ash -c 'echo ${#1#}' name:'1=#'
6391 static NOINLINE ssize_t
6392 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6402 int quoted = varflags & VSQUOTE;
6403 int subtype = varflags & VSTYPE;
6404 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6406 if (quoted && (flags & EXP_FULL))
6407 sep = 1 << CHAR_BIT;
6409 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6418 num = shellparam.nparam;
6426 goto check_1char_name;
6428 expdest = makestrspace(NOPTS, expdest);
6429 for (i = NOPTS - 1; i >= 0; i--) {
6431 USTPUTC(optletters(i), expdest);
6437 /* handles cases similar to ${#$1} */
6438 if (name[2] != '\0')
6439 raise_error_syntax("bad substitution");
6447 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
6448 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6454 while ((p = *ap++) != NULL) {
6457 partlen = strlen(p);
6460 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6461 memtodest(p, partlen, syntax, quotes);
6467 if (subtype == VSPLUS || subtype == VSLENGTH) {
6488 num = atoi(name); /* number(name) fails on ${N#str} etc */
6489 if (num < 0 || num > shellparam.nparam)
6491 p = num ? shellparam.p[num - 1] : arg0;
6494 /* NB: name has form "VAR=..." */
6496 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6497 * which should be considered before we check variables. */
6499 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6503 str = var_str_list->text;
6504 eq = strchr(str, '=');
6505 if (!eq) /* stop at first non-assignment */
6508 if (name_len == (unsigned)(eq - str)
6509 && strncmp(str, name, name_len) == 0) {
6511 /* goto value; - WRONG! */
6512 /* think "A=1 A=2 B=$A" */
6514 var_str_list = var_str_list->next;
6515 } while (var_str_list);
6519 p = lookupvar(name);
6525 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6526 memtodest(p, len, syntax, quotes);
6530 if (subtype == VSPLUS || subtype == VSLENGTH)
6531 STADJUST(-len, expdest);
6536 * Expand a variable, and return a pointer to the next character in the
6540 evalvar(char *p, int flags, struct strlist *var_str_list)
6551 varflags = (unsigned char) *p++;
6552 subtype = varflags & VSTYPE;
6553 quoted = varflags & VSQUOTE;
6555 easy = (!quoted || (*var == '@' && shellparam.nparam));
6556 startloc = expdest - (char *)stackblock();
6557 p = strchr(p, '=') + 1;
6560 varlen = varvalue(var, varflags, flags, var_str_list);
6561 if (varflags & VSNUL)
6564 if (subtype == VSPLUS) {
6565 varlen = -1 - varlen;
6569 if (subtype == VSMINUS) {
6573 p, flags | EXP_TILDE |
6574 (quoted ? EXP_QWORD : EXP_WORD),
6584 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6586 if (subevalvar(p, var, /* strloc: */ 0,
6587 subtype, startloc, varflags,
6593 * Remove any recorded regions beyond
6596 removerecordregions(startloc);
6606 if (varlen < 0 && uflag)
6607 varunset(p, var, 0, 0);
6609 if (subtype == VSLENGTH) {
6610 cvtnum(varlen > 0 ? varlen : 0);
6614 if (subtype == VSNORMAL) {
6625 case VSTRIMRIGHTMAX:
6626 #if ENABLE_ASH_BASH_COMPAT
6639 * Terminate the string and start recording the pattern
6642 STPUTC('\0', expdest);
6643 patloc = expdest - (char *)stackblock();
6644 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6646 //TODO: | EXP_REDIR too? All other such places do it too
6647 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6650 int amount = expdest - (
6651 (char *)stackblock() + patloc - 1
6653 STADJUST(-amount, expdest);
6655 /* Remove any recorded regions beyond start of variable */
6656 removerecordregions(startloc);
6658 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6662 if (subtype != VSNORMAL) { /* skip to end of alternative */
6668 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6670 argbackq = argbackq->next;
6671 } else if (c == CTLVAR) {
6672 if ((*p++ & VSTYPE) != VSNORMAL)
6674 } else if (c == CTLENDVAR) {
6684 * Break the argument string into pieces based upon IFS and add the
6685 * strings to the argument list. The regions of the string to be
6686 * searched for IFS characters have been stored by recordregion.
6689 ifsbreakup(char *string, struct arglist *arglist)
6691 struct ifsregion *ifsp;
6696 const char *ifs, *realifs;
6701 if (ifslastp != NULL) {
6704 realifs = ifsset() ? ifsval() : defifs;
6707 p = string + ifsp->begoff;
6708 nulonly = ifsp->nulonly;
6709 ifs = nulonly ? nullstr : realifs;
6711 while (p < string + ifsp->endoff) {
6715 if (!strchr(ifs, *p)) {
6720 ifsspc = (strchr(defifs, *p) != NULL);
6721 /* Ignore IFS whitespace at start */
6722 if (q == start && ifsspc) {
6728 sp = stzalloc(sizeof(*sp));
6730 *arglist->lastp = sp;
6731 arglist->lastp = &sp->next;
6735 if (p >= string + ifsp->endoff) {
6741 if (strchr(ifs, *p) == NULL) {
6745 if (strchr(defifs, *p) == NULL) {
6760 } while (ifsp != NULL);
6769 sp = stzalloc(sizeof(*sp));
6771 *arglist->lastp = sp;
6772 arglist->lastp = &sp->next;
6778 struct ifsregion *p;
6783 struct ifsregion *ifsp;
6789 ifsfirst.next = NULL;
6794 * Add a file name to the list.
6797 addfname(const char *name)
6801 sp = stzalloc(sizeof(*sp));
6802 sp->text = ststrdup(name);
6804 exparg.lastp = &sp->next;
6807 static char *expdir;
6810 * Do metacharacter (i.e. *, ?, [...]) expansion.
6813 expmeta(char *enddir, char *name)
6828 for (p = name; *p; p++) {
6829 if (*p == '*' || *p == '?')
6831 else if (*p == '[') {
6838 if (*q == '/' || *q == '\0')
6845 } else if (*p == '\\')
6847 else if (*p == '/') {
6854 if (metaflag == 0) { /* we've reached the end of the file name */
6855 if (enddir != expdir)
6863 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6874 } while (p < start);
6876 if (enddir == expdir) {
6878 } else if (enddir == expdir + 1 && *expdir == '/') {
6887 if (enddir != expdir)
6889 if (*endname == 0) {
6901 while (!pending_int && (dp = readdir(dirp)) != NULL) {
6902 if (dp->d_name[0] == '.' && !matchdot)
6904 if (pmatch(start, dp->d_name)) {
6906 strcpy(enddir, dp->d_name);
6909 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6912 expmeta(p, endname);
6921 static struct strlist *
6922 msort(struct strlist *list, int len)
6924 struct strlist *p, *q = NULL;
6925 struct strlist **lpp;
6933 for (n = half; --n >= 0;) {
6937 q->next = NULL; /* terminate first half of list */
6938 q = msort(list, half); /* sort first half of list */
6939 p = msort(p, len - half); /* sort second half */
6942 #if ENABLE_LOCALE_SUPPORT
6943 if (strcoll(p->text, q->text) < 0)
6945 if (strcmp(p->text, q->text) < 0)
6969 * Sort the results of file name expansion. It calculates the number of
6970 * strings to sort and then calls msort (short for merge sort) to do the
6973 static struct strlist *
6974 expsort(struct strlist *str)
6980 for (sp = str; sp; sp = sp->next)
6982 return msort(str, len);
6986 expandmeta(struct strlist *str /*, int flag*/)
6988 static const char metachars[] ALIGN1 = {
6991 /* TODO - EXP_REDIR */
6994 struct strlist **savelastp;
7000 if (!strpbrk(str->text, metachars))
7002 savelastp = exparg.lastp;
7005 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7007 int i = strlen(str->text);
7008 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7016 if (exparg.lastp == savelastp) {
7021 *exparg.lastp = str;
7022 rmescapes(str->text, 0);
7023 exparg.lastp = &str->next;
7025 *exparg.lastp = NULL;
7026 *savelastp = sp = expsort(*savelastp);
7027 while (sp->next != NULL)
7029 exparg.lastp = &sp->next;
7036 * Perform variable substitution and command substitution on an argument,
7037 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7038 * perform splitting and file name expansion. When arglist is NULL, perform
7039 * here document expansion.
7042 expandarg(union node *arg, struct arglist *arglist, int flag)
7047 argbackq = arg->narg.backquote;
7048 STARTSTACKSTR(expdest);
7049 ifsfirst.next = NULL;
7051 argstr(arg->narg.text, flag,
7052 /* var_str_list: */ arglist ? arglist->list : NULL);
7053 p = _STPUTC('\0', expdest);
7055 if (arglist == NULL) {
7056 return; /* here document expanded */
7058 p = grabstackstr(p);
7059 exparg.lastp = &exparg.list;
7063 if (flag & EXP_FULL) {
7064 ifsbreakup(p, &exparg);
7065 *exparg.lastp = NULL;
7066 exparg.lastp = &exparg.list;
7067 expandmeta(exparg.list /*, flag*/);
7069 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7071 sp = stzalloc(sizeof(*sp));
7074 exparg.lastp = &sp->next;
7078 *exparg.lastp = NULL;
7080 *arglist->lastp = exparg.list;
7081 arglist->lastp = exparg.lastp;
7086 * Expand shell variables and backquotes inside a here document.
7089 expandhere(union node *arg, int fd)
7092 expandarg(arg, (struct arglist *)NULL, 0);
7093 full_write(fd, stackblock(), expdest - (char *)stackblock());
7097 * Returns true if the pattern matches the string.
7100 patmatch(char *pattern, const char *string)
7102 return pmatch(preglob(pattern, 0, 0), string);
7106 * See if a pattern matches in a case statement.
7109 casematch(union node *pattern, char *val)
7111 struct stackmark smark;
7114 setstackmark(&smark);
7115 argbackq = pattern->narg.backquote;
7116 STARTSTACKSTR(expdest);
7118 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7119 /* var_str_list: */ NULL);
7120 STACKSTRNUL(expdest);
7121 result = patmatch(stackblock(), val);
7122 popstackmark(&smark);
7127 /* ============ find_command */
7131 int (*builtin)(int, char **) FAST_FUNC;
7132 /* unsigned flags; */
7134 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7135 /* "regular" builtins always take precedence over commands,
7136 * regardless of PATH=....%builtin... position */
7137 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7138 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7141 smallint cmdtype; /* CMDxxx */
7144 /* index >= 0 for commands without path (slashes) */
7145 /* (TODO: what exactly does the value mean? PATH position?) */
7146 /* index == -1 for commands with slashes */
7147 /* index == (-2 - applet_no) for NOFORK applets */
7148 const struct builtincmd *cmd;
7149 struct funcnode *func;
7152 /* values of cmdtype */
7153 #define CMDUNKNOWN -1 /* no entry in table for command */
7154 #define CMDNORMAL 0 /* command is an executable program */
7155 #define CMDFUNCTION 1 /* command is a shell function */
7156 #define CMDBUILTIN 2 /* command is a shell builtin */
7158 /* action to find_command() */
7159 #define DO_ERR 0x01 /* prints errors */
7160 #define DO_ABS 0x02 /* checks absolute paths */
7161 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7162 #define DO_ALTPATH 0x08 /* using alternate path */
7163 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7165 static void find_command(char *, struct cmdentry *, int, const char *);
7168 /* ============ Hashing commands */
7171 * When commands are first encountered, they are entered in a hash table.
7172 * This ensures that a full path search will not have to be done for them
7173 * on each invocation.
7175 * We should investigate converting to a linear search, even though that
7176 * would make the command name "hash" a misnomer.
7180 struct tblentry *next; /* next entry in hash chain */
7181 union param param; /* definition of builtin function */
7182 smallint cmdtype; /* CMDxxx */
7183 char rehash; /* if set, cd done since entry created */
7184 char cmdname[1]; /* name of command */
7187 static struct tblentry **cmdtable;
7188 #define INIT_G_cmdtable() do { \
7189 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7192 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7196 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7200 #if ENABLE_FEATURE_SH_STANDALONE
7201 if (applet_no >= 0) {
7202 if (APPLET_IS_NOEXEC(applet_no)) {
7205 run_applet_no_and_exit(applet_no, argv);
7207 /* re-exec ourselves with the new arguments */
7208 execve(bb_busybox_exec_path, argv, envp);
7209 /* If they called chroot or otherwise made the binary no longer
7210 * executable, fall through */
7217 execve(cmd, argv, envp);
7218 } while (errno == EINTR);
7220 execve(cmd, argv, envp);
7226 if (errno == ENOEXEC) {
7230 for (ap = argv; *ap; ap++)
7232 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7234 ap[0] = cmd = (char *)DEFAULT_SHELL;
7237 while ((*ap++ = *argv++) != NULL)
7246 * Exec a program. Never returns. If you change this routine, you may
7247 * have to change the find_command routine as well.
7249 static void shellexec(char **, const char *, int) NORETURN;
7251 shellexec(char **argv, const char *path, int idx)
7257 #if ENABLE_FEATURE_SH_STANDALONE
7261 clearredir(/*drop:*/ 1);
7262 envp = listvars(VEXPORT, VUNSET, 0);
7263 if (strchr(argv[0], '/') != NULL
7264 #if ENABLE_FEATURE_SH_STANDALONE
7265 || (applet_no = find_applet_by_name(argv[0])) >= 0
7268 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7272 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7273 if (--idx < 0 && pathopt == NULL) {
7274 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7275 if (errno != ENOENT && errno != ENOTDIR)
7282 /* Map to POSIX errors */
7294 exitstatus = exerrno;
7295 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7296 argv[0], e, suppress_int));
7297 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7302 printentry(struct tblentry *cmdp)
7308 idx = cmdp->param.index;
7311 name = path_advance(&path, cmdp->cmdname);
7313 } while (--idx >= 0);
7314 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7318 * Clear out command entries. The argument specifies the first entry in
7319 * PATH which has changed.
7322 clearcmdentry(int firstchange)
7324 struct tblentry **tblp;
7325 struct tblentry **pp;
7326 struct tblentry *cmdp;
7329 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7331 while ((cmdp = *pp) != NULL) {
7332 if ((cmdp->cmdtype == CMDNORMAL &&
7333 cmdp->param.index >= firstchange)
7334 || (cmdp->cmdtype == CMDBUILTIN &&
7335 builtinloc >= firstchange)
7348 * Locate a command in the command hash table. If "add" is nonzero,
7349 * add the command to the table if it is not already present. The
7350 * variable "lastcmdentry" is set to point to the address of the link
7351 * pointing to the entry, so that delete_cmd_entry can delete the
7354 * Interrupts must be off if called with add != 0.
7356 static struct tblentry **lastcmdentry;
7358 static struct tblentry *
7359 cmdlookup(const char *name, int add)
7361 unsigned int hashval;
7363 struct tblentry *cmdp;
7364 struct tblentry **pp;
7367 hashval = (unsigned char)*p << 4;
7369 hashval += (unsigned char)*p++;
7371 pp = &cmdtable[hashval % CMDTABLESIZE];
7372 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7373 if (strcmp(cmdp->cmdname, name) == 0)
7377 if (add && cmdp == NULL) {
7378 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7380 /* + 1 - already done because
7381 * tblentry::cmdname is char[1] */);
7382 /*cmdp->next = NULL; - ckzalloc did it */
7383 cmdp->cmdtype = CMDUNKNOWN;
7384 strcpy(cmdp->cmdname, name);
7391 * Delete the command entry returned on the last lookup.
7394 delete_cmd_entry(void)
7396 struct tblentry *cmdp;
7399 cmdp = *lastcmdentry;
7400 *lastcmdentry = cmdp->next;
7401 if (cmdp->cmdtype == CMDFUNCTION)
7402 freefunc(cmdp->param.func);
7408 * Add a new command entry, replacing any existing command entry for
7409 * the same name - except special builtins.
7412 addcmdentry(char *name, struct cmdentry *entry)
7414 struct tblentry *cmdp;
7416 cmdp = cmdlookup(name, 1);
7417 if (cmdp->cmdtype == CMDFUNCTION) {
7418 freefunc(cmdp->param.func);
7420 cmdp->cmdtype = entry->cmdtype;
7421 cmdp->param = entry->u;
7425 static int FAST_FUNC
7426 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7428 struct tblentry **pp;
7429 struct tblentry *cmdp;
7431 struct cmdentry entry;
7434 if (nextopt("r") != '\0') {
7439 if (*argptr == NULL) {
7440 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7441 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7442 if (cmdp->cmdtype == CMDNORMAL)
7450 while ((name = *argptr) != NULL) {
7451 cmdp = cmdlookup(name, 0);
7453 && (cmdp->cmdtype == CMDNORMAL
7454 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7458 find_command(name, &entry, DO_ERR, pathval());
7459 if (entry.cmdtype == CMDUNKNOWN)
7467 * Called when a cd is done. Marks all commands so the next time they
7468 * are executed they will be rehashed.
7473 struct tblentry **pp;
7474 struct tblentry *cmdp;
7476 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7477 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7478 if (cmdp->cmdtype == CMDNORMAL
7479 || (cmdp->cmdtype == CMDBUILTIN
7480 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7490 * Fix command hash table when PATH changed.
7491 * Called before PATH is changed. The argument is the new value of PATH;
7492 * pathval() still returns the old value at this point.
7493 * Called with interrupts off.
7495 static void FAST_FUNC
7496 changepath(const char *new)
7504 firstchange = 9999; /* assume no change */
7510 if ((*old == '\0' && *new == ':')
7511 || (*old == ':' && *new == '\0'))
7513 old = new; /* ignore subsequent differences */
7517 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7523 if (builtinloc < 0 && idx_bltin >= 0)
7524 builtinloc = idx_bltin; /* zap builtins */
7525 if (builtinloc >= 0 && idx_bltin < 0)
7527 clearcmdentry(firstchange);
7528 builtinloc = idx_bltin;
7543 #define TENDBQUOTE 12
7560 typedef smallint token_id_t;
7562 /* first char is indicating which tokens mark the end of a list */
7563 static const char *const tokname_array[] = {
7577 #define KWDOFFSET 13
7578 /* the following are keywords */
7600 static char buf[16];
7603 //if (tok < TSEMI) return tokname_array[tok] + 1;
7604 //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7609 sprintf(buf + (tok >= TSEMI), "%s%c",
7610 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7614 /* Wrapper around strcmp for qsort/bsearch/... */
7616 pstrcmp(const void *a, const void *b)
7618 return strcmp((char*) a, (*(char**) b) + 1);
7621 static const char *const *
7622 findkwd(const char *s)
7624 return bsearch(s, tokname_array + KWDOFFSET,
7625 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7626 sizeof(tokname_array[0]), pstrcmp);
7630 * Locate and print what a word is...
7633 describe_command(char *command, int describe_command_verbose)
7635 struct cmdentry entry;
7636 struct tblentry *cmdp;
7637 #if ENABLE_ASH_ALIAS
7638 const struct alias *ap;
7640 const char *path = pathval();
7642 if (describe_command_verbose) {
7646 /* First look at the keywords */
7647 if (findkwd(command)) {
7648 out1str(describe_command_verbose ? " is a shell keyword" : command);
7652 #if ENABLE_ASH_ALIAS
7653 /* Then look at the aliases */
7654 ap = lookupalias(command, 0);
7656 if (!describe_command_verbose) {
7661 out1fmt(" is an alias for %s", ap->val);
7665 /* Then check if it is a tracked alias */
7666 cmdp = cmdlookup(command, 0);
7668 entry.cmdtype = cmdp->cmdtype;
7669 entry.u = cmdp->param;
7671 /* Finally use brute force */
7672 find_command(command, &entry, DO_ABS, path);
7675 switch (entry.cmdtype) {
7677 int j = entry.u.index;
7683 p = path_advance(&path, command);
7687 if (describe_command_verbose) {
7689 (cmdp ? " a tracked alias for" : nullstr), p
7698 if (describe_command_verbose) {
7699 out1str(" is a shell function");
7706 if (describe_command_verbose) {
7707 out1fmt(" is a %sshell builtin",
7708 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7709 "special " : nullstr
7717 if (describe_command_verbose) {
7718 out1str(": not found\n");
7723 outstr("\n", stdout);
7727 static int FAST_FUNC
7728 typecmd(int argc UNUSED_PARAM, char **argv)
7734 /* type -p ... ? (we don't bother checking for 'p') */
7735 if (argv[1] && argv[1][0] == '-') {
7740 err |= describe_command(argv[i++], verbose);
7745 #if ENABLE_ASH_CMDCMD
7746 static int FAST_FUNC
7747 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7755 while ((c = nextopt("pvV")) != '\0')
7757 verify |= VERIFY_VERBOSE;
7759 verify |= VERIFY_BRIEF;
7764 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7765 if (verify && (*argptr != NULL)) {
7766 return describe_command(*argptr, verify - VERIFY_BRIEF);
7774 /* ============ eval.c */
7776 static int funcblocksize; /* size of structures in function */
7777 static int funcstringsize; /* size of strings in node */
7778 static void *funcblock; /* block to allocate function from */
7779 static char *funcstring; /* block to allocate strings from */
7781 /* flags in argument to evaltree */
7782 #define EV_EXIT 01 /* exit after evaluating tree */
7783 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7784 #define EV_BACKCMD 04 /* command executing within back quotes */
7786 static const uint8_t nodesize[N_NUMBER] = {
7787 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7788 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7789 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7790 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7791 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7792 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7793 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7794 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7795 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7796 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7797 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7798 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7799 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7800 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7801 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7802 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7803 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7804 #if ENABLE_ASH_BASH_COMPAT
7805 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7807 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7808 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7809 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7810 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7811 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7812 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7813 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7814 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7815 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7818 static void calcsize(union node *n);
7821 sizenodelist(struct nodelist *lp)
7824 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7831 calcsize(union node *n)
7835 funcblocksize += nodesize[n->type];
7838 calcsize(n->ncmd.redirect);
7839 calcsize(n->ncmd.args);
7840 calcsize(n->ncmd.assign);
7843 sizenodelist(n->npipe.cmdlist);
7848 calcsize(n->nredir.redirect);
7849 calcsize(n->nredir.n);
7856 calcsize(n->nbinary.ch2);
7857 calcsize(n->nbinary.ch1);
7860 calcsize(n->nif.elsepart);
7861 calcsize(n->nif.ifpart);
7862 calcsize(n->nif.test);
7865 funcstringsize += strlen(n->nfor.var) + 1;
7866 calcsize(n->nfor.body);
7867 calcsize(n->nfor.args);
7870 calcsize(n->ncase.cases);
7871 calcsize(n->ncase.expr);
7874 calcsize(n->nclist.body);
7875 calcsize(n->nclist.pattern);
7876 calcsize(n->nclist.next);
7880 sizenodelist(n->narg.backquote);
7881 funcstringsize += strlen(n->narg.text) + 1;
7882 calcsize(n->narg.next);
7885 #if ENABLE_ASH_BASH_COMPAT
7892 calcsize(n->nfile.fname);
7893 calcsize(n->nfile.next);
7897 calcsize(n->ndup.vname);
7898 calcsize(n->ndup.next);
7902 calcsize(n->nhere.doc);
7903 calcsize(n->nhere.next);
7906 calcsize(n->nnot.com);
7912 nodeckstrdup(char *s)
7914 char *rtn = funcstring;
7916 strcpy(funcstring, s);
7917 funcstring += strlen(s) + 1;
7921 static union node *copynode(union node *);
7923 static struct nodelist *
7924 copynodelist(struct nodelist *lp)
7926 struct nodelist *start;
7927 struct nodelist **lpp;
7932 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7933 (*lpp)->n = copynode(lp->n);
7935 lpp = &(*lpp)->next;
7942 copynode(union node *n)
7949 funcblock = (char *) funcblock + nodesize[n->type];
7953 new->ncmd.redirect = copynode(n->ncmd.redirect);
7954 new->ncmd.args = copynode(n->ncmd.args);
7955 new->ncmd.assign = copynode(n->ncmd.assign);
7958 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7959 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
7964 new->nredir.redirect = copynode(n->nredir.redirect);
7965 new->nredir.n = copynode(n->nredir.n);
7972 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7973 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7976 new->nif.elsepart = copynode(n->nif.elsepart);
7977 new->nif.ifpart = copynode(n->nif.ifpart);
7978 new->nif.test = copynode(n->nif.test);
7981 new->nfor.var = nodeckstrdup(n->nfor.var);
7982 new->nfor.body = copynode(n->nfor.body);
7983 new->nfor.args = copynode(n->nfor.args);
7986 new->ncase.cases = copynode(n->ncase.cases);
7987 new->ncase.expr = copynode(n->ncase.expr);
7990 new->nclist.body = copynode(n->nclist.body);
7991 new->nclist.pattern = copynode(n->nclist.pattern);
7992 new->nclist.next = copynode(n->nclist.next);
7996 new->narg.backquote = copynodelist(n->narg.backquote);
7997 new->narg.text = nodeckstrdup(n->narg.text);
7998 new->narg.next = copynode(n->narg.next);
8001 #if ENABLE_ASH_BASH_COMPAT
8008 new->nfile.fname = copynode(n->nfile.fname);
8009 new->nfile.fd = n->nfile.fd;
8010 new->nfile.next = copynode(n->nfile.next);
8014 new->ndup.vname = copynode(n->ndup.vname);
8015 new->ndup.dupfd = n->ndup.dupfd;
8016 new->ndup.fd = n->ndup.fd;
8017 new->ndup.next = copynode(n->ndup.next);
8021 new->nhere.doc = copynode(n->nhere.doc);
8022 new->nhere.fd = n->nhere.fd;
8023 new->nhere.next = copynode(n->nhere.next);
8026 new->nnot.com = copynode(n->nnot.com);
8029 new->type = n->type;
8034 * Make a copy of a parse tree.
8036 static struct funcnode *
8037 copyfunc(union node *n)
8042 funcblocksize = offsetof(struct funcnode, n);
8045 blocksize = funcblocksize;
8046 f = ckmalloc(blocksize + funcstringsize);
8047 funcblock = (char *) f + offsetof(struct funcnode, n);
8048 funcstring = (char *) f + blocksize;
8055 * Define a shell function.
8058 defun(char *name, union node *func)
8060 struct cmdentry entry;
8063 entry.cmdtype = CMDFUNCTION;
8064 entry.u.func = copyfunc(func);
8065 addcmdentry(name, &entry);
8069 /* Reasons for skipping commands (see comment on breakcmd routine) */
8070 #define SKIPBREAK (1 << 0)
8071 #define SKIPCONT (1 << 1)
8072 #define SKIPFUNC (1 << 2)
8073 #define SKIPFILE (1 << 3)
8074 #define SKIPEVAL (1 << 4)
8075 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8076 static int skipcount; /* number of levels to skip */
8077 static int funcnest; /* depth of function calls */
8078 static int loopnest; /* current loop nesting level */
8080 /* Forward decl way out to parsing code - dotrap needs it */
8081 static int evalstring(char *s, int mask);
8083 /* Called to execute a trap.
8084 * Single callsite - at the end of evaltree().
8085 * If we return non-zero, exaltree raises EXEXIT exception.
8087 * Perhaps we should avoid entering new trap handlers
8088 * while we are executing a trap handler. [is it a TODO?]
8097 savestatus = exitstatus;
8101 TRACE(("dotrap entered\n"));
8102 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8109 /* non-trapped SIGINT is handled separately by raise_interrupt,
8110 * don't upset it by resetting gotsig[SIGINT-1] */
8111 if (sig == SIGINT && !t)
8114 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8118 want_exexit = evalstring(t, SKIPEVAL);
8119 exitstatus = savestatus;
8121 TRACE(("dotrap returns %d\n", want_exexit));
8126 TRACE(("dotrap returns 0\n"));
8130 /* forward declarations - evaluation is fairly recursive business... */
8131 static void evalloop(union node *, int);
8132 static void evalfor(union node *, int);
8133 static void evalcase(union node *, int);
8134 static void evalsubshell(union node *, int);
8135 static void expredir(union node *);
8136 static void evalpipe(union node *, int);
8137 static void evalcommand(union node *, int);
8138 static int evalbltin(const struct builtincmd *, int, char **);
8139 static void prehash(union node *);
8142 * Evaluate a parse tree. The value is left in the global variable
8146 evaltree(union node *n, int flags)
8148 struct jmploc *volatile savehandler = exception_handler;
8149 struct jmploc jmploc;
8151 void (*evalfn)(union node *, int);
8155 SAVE_INT(int_level);
8158 TRACE(("evaltree(NULL) called\n"));
8161 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8163 exception_handler = &jmploc;
8165 int err = setjmp(jmploc.loc);
8167 /* if it was a signal, check for trap handlers */
8168 if (exception_type == EXSIG) {
8169 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8170 exception_type, err));
8173 /* continue on the way out */
8174 TRACE(("exception %d in evaltree, propagating err=%d\n",
8175 exception_type, err));
8176 exception_handler = savehandler;
8177 longjmp(exception_handler->loc, err);
8184 out1fmt("Node type = %d\n", n->type);
8189 evaltree(n->nnot.com, EV_TESTED);
8190 status = !exitstatus;
8193 expredir(n->nredir.redirect);
8194 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8196 evaltree(n->nredir.n, flags & EV_TESTED);
8197 status = exitstatus;
8199 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8202 evalfn = evalcommand;
8204 if (eflag && !(flags & EV_TESTED))
8216 evalfn = evalsubshell;
8229 #error NAND + 1 != NOR
8231 #if NOR + 1 != NSEMI
8232 #error NOR + 1 != NSEMI
8234 unsigned is_or = n->type - NAND;
8237 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8239 if (!exitstatus == is_or)
8252 evaltree(n->nif.test, EV_TESTED);
8255 if (exitstatus == 0) {
8259 if (n->nif.elsepart) {
8260 n = n->nif.elsepart;
8265 defun(n->narg.text, n->narg.next);
8269 exitstatus = status;
8274 exception_handler = savehandler;
8276 if (checkexit & exitstatus)
8277 evalskip |= SKIPEVAL;
8278 else if (pending_sig && dotrap())
8281 if (flags & EV_EXIT) {
8283 raise_exception(EXEXIT);
8286 RESTORE_INT(int_level);
8287 TRACE(("leaving evaltree (no interrupts)\n"));
8290 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8293 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8296 evalloop(union node *n, int flags)
8306 evaltree(n->nbinary.ch1, EV_TESTED);
8309 if (evalskip == SKIPCONT && --skipcount <= 0) {
8313 if (evalskip == SKIPBREAK && --skipcount <= 0)
8318 if (n->type != NWHILE)
8322 evaltree(n->nbinary.ch2, flags);
8323 status = exitstatus;
8328 exitstatus = status;
8332 evalfor(union node *n, int flags)
8334 struct arglist arglist;
8337 struct stackmark smark;
8339 setstackmark(&smark);
8340 arglist.list = NULL;
8341 arglist.lastp = &arglist.list;
8342 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8343 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8348 *arglist.lastp = NULL;
8353 for (sp = arglist.list; sp; sp = sp->next) {
8354 setvar(n->nfor.var, sp->text, 0);
8355 evaltree(n->nfor.body, flags);
8357 if (evalskip == SKIPCONT && --skipcount <= 0) {
8361 if (evalskip == SKIPBREAK && --skipcount <= 0)
8368 popstackmark(&smark);
8372 evalcase(union node *n, int flags)
8376 struct arglist arglist;
8377 struct stackmark smark;
8379 setstackmark(&smark);
8380 arglist.list = NULL;
8381 arglist.lastp = &arglist.list;
8382 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8384 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8385 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8386 if (casematch(patp, arglist.list->text)) {
8387 if (evalskip == 0) {
8388 evaltree(cp->nclist.body, flags);
8395 popstackmark(&smark);
8399 * Kick off a subshell to evaluate a tree.
8402 evalsubshell(union node *n, int flags)
8405 int backgnd = (n->type == NBACKGND);
8408 expredir(n->nredir.redirect);
8409 if (!backgnd && flags & EV_EXIT && !trap[0])
8412 jp = makejob(/*n,*/ 1);
8413 if (forkshell(jp, n, backgnd) == 0) {
8417 flags &=~ EV_TESTED;
8419 redirect(n->nredir.redirect, 0);
8420 evaltreenr(n->nredir.n, flags);
8425 status = waitforjob(jp);
8426 exitstatus = status;
8431 * Compute the names of the files in a redirection list.
8433 static void fixredir(union node *, const char *, int);
8435 expredir(union node *n)
8439 for (redir = n; redir; redir = redir->nfile.next) {
8443 fn.lastp = &fn.list;
8444 switch (redir->type) {
8448 #if ENABLE_ASH_BASH_COMPAT
8453 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8454 #if ENABLE_ASH_BASH_COMPAT
8457 redir->nfile.expfname = fn.list->text;
8460 case NTOFD: /* >& */
8461 if (redir->ndup.vname) {
8462 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8463 if (fn.list == NULL)
8464 ash_msg_and_raise_error("redir error");
8465 #if ENABLE_ASH_BASH_COMPAT
8466 //FIXME: we used expandarg with different args!
8467 if (!isdigit_str9(fn.list->text)) {
8468 /* >&file, not >&fd */
8469 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8470 ash_msg_and_raise_error("redir error");
8472 goto store_expfname;
8475 fixredir(redir, fn.list->text, 1);
8483 * Evaluate a pipeline. All the processes in the pipeline are children
8484 * of the process creating the pipeline. (This differs from some versions
8485 * of the shell, which make the last process in a pipeline the parent
8489 evalpipe(union node *n, int flags)
8492 struct nodelist *lp;
8497 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8499 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8503 jp = makejob(/*n,*/ pipelen);
8505 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8509 if (pipe(pip) < 0) {
8511 ash_msg_and_raise_error("pipe call failed");
8514 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8527 evaltreenr(lp->n, flags);
8533 /* Don't want to trigger debugging */
8537 if (n->npipe.pipe_backgnd == 0) {
8538 exitstatus = waitforjob(jp);
8539 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8545 * Controls whether the shell is interactive or not.
8548 setinteractive(int on)
8550 static smallint is_interactive;
8552 if (++on == is_interactive)
8554 is_interactive = on;
8558 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8559 if (is_interactive > 1) {
8560 /* Looks like they want an interactive shell */
8561 static smallint did_banner;
8564 /* note: ash and hush share this string */
8565 out1fmt("\n\n%s %s\n"
8566 "Enter 'help' for a list of built-in commands."
8569 "built-in shell (ash)"
8583 setinteractive(iflag);
8585 #if ENABLE_FEATURE_EDITING_VI
8587 line_input_state->flags |= VI_MODE;
8589 line_input_state->flags &= ~VI_MODE;
8591 viflag = 0; /* forcibly keep the option off */
8595 static struct localvar *localvars;
8598 * Called after a function returns.
8599 * Interrupts must be off.
8604 struct localvar *lvp;
8607 while ((lvp = localvars) != NULL) {
8608 localvars = lvp->next;
8610 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8611 if (vp == NULL) { /* $- saved */
8612 memcpy(optlist, lvp->text, sizeof(optlist));
8613 free((char*)lvp->text);
8615 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8619 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8620 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8621 free((char*)vp->text);
8622 vp->flags = lvp->flags;
8623 vp->text = lvp->text;
8630 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8632 volatile struct shparam saveparam;
8633 struct localvar *volatile savelocalvars;
8634 struct jmploc *volatile savehandler;
8635 struct jmploc jmploc;
8638 saveparam = shellparam;
8639 savelocalvars = localvars;
8640 e = setjmp(jmploc.loc);
8645 savehandler = exception_handler;
8646 exception_handler = &jmploc;
8648 shellparam.malloced = 0;
8652 shellparam.nparam = argc - 1;
8653 shellparam.p = argv + 1;
8654 #if ENABLE_ASH_GETOPTS
8655 shellparam.optind = 1;
8656 shellparam.optoff = -1;
8658 evaltree(&func->n, flags & EV_TESTED);
8664 localvars = savelocalvars;
8665 freeparam(&shellparam);
8666 shellparam = saveparam;
8667 exception_handler = savehandler;
8669 evalskip &= ~SKIPFUNC;
8673 #if ENABLE_ASH_CMDCMD
8675 parse_command_args(char **argv, const char **path)
8688 if (c == '-' && !*cp) {
8695 *path = bb_default_path;
8698 /* run 'typecmd' for other options */
8709 * Make a variable a local variable. When a variable is made local, it's
8710 * value and flags are saved in a localvar structure. The saved values
8711 * will be restored when the shell function returns. We handle the name
8712 * "-" as a special case.
8717 struct localvar *lvp;
8722 lvp = ckzalloc(sizeof(struct localvar));
8723 if (LONE_DASH(name)) {
8725 p = ckmalloc(sizeof(optlist));
8726 lvp->text = memcpy(p, optlist, sizeof(optlist));
8731 vpp = hashvar(name);
8732 vp = *findvar(vpp, name);
8733 eq = strchr(name, '=');
8736 setvareq(name, VSTRFIXED);
8738 setvar(name, NULL, VSTRFIXED);
8739 vp = *vpp; /* the new variable */
8740 lvp->flags = VUNSET;
8742 lvp->text = vp->text;
8743 lvp->flags = vp->flags;
8744 vp->flags |= VSTRFIXED|VTEXTFIXED;
8750 lvp->next = localvars;
8756 * The "local" command.
8758 static int FAST_FUNC
8759 localcmd(int argc UNUSED_PARAM, char **argv)
8764 while ((name = *argv++) != NULL) {
8770 static int FAST_FUNC
8771 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8776 static int FAST_FUNC
8777 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8782 static int FAST_FUNC
8783 execcmd(int argc UNUSED_PARAM, char **argv)
8786 iflag = 0; /* exit on error */
8789 shellexec(argv + 1, pathval(), 0);
8795 * The return command.
8797 static int FAST_FUNC
8798 returncmd(int argc UNUSED_PARAM, char **argv)
8801 * If called outside a function, do what ksh does;
8802 * skip the rest of the file.
8804 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8805 return argv[1] ? number(argv[1]) : exitstatus;
8808 /* Forward declarations for builtintab[] */
8809 static int breakcmd(int, char **) FAST_FUNC;
8810 static int dotcmd(int, char **) FAST_FUNC;
8811 static int evalcmd(int, char **) FAST_FUNC;
8812 static int exitcmd(int, char **) FAST_FUNC;
8813 static int exportcmd(int, char **) FAST_FUNC;
8814 #if ENABLE_ASH_GETOPTS
8815 static int getoptscmd(int, char **) FAST_FUNC;
8817 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8818 static int helpcmd(int, char **) FAST_FUNC;
8820 #if ENABLE_SH_MATH_SUPPORT
8821 static int letcmd(int, char **) FAST_FUNC;
8823 static int readcmd(int, char **) FAST_FUNC;
8824 static int setcmd(int, char **) FAST_FUNC;
8825 static int shiftcmd(int, char **) FAST_FUNC;
8826 static int timescmd(int, char **) FAST_FUNC;
8827 static int trapcmd(int, char **) FAST_FUNC;
8828 static int umaskcmd(int, char **) FAST_FUNC;
8829 static int unsetcmd(int, char **) FAST_FUNC;
8830 static int ulimitcmd(int, char **) FAST_FUNC;
8832 #define BUILTIN_NOSPEC "0"
8833 #define BUILTIN_SPECIAL "1"
8834 #define BUILTIN_REGULAR "2"
8835 #define BUILTIN_SPEC_REG "3"
8836 #define BUILTIN_ASSIGN "4"
8837 #define BUILTIN_SPEC_ASSG "5"
8838 #define BUILTIN_REG_ASSG "6"
8839 #define BUILTIN_SPEC_REG_ASSG "7"
8841 /* Stubs for calling non-FAST_FUNC's */
8842 #if ENABLE_ASH_BUILTIN_ECHO
8843 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8845 #if ENABLE_ASH_BUILTIN_PRINTF
8846 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8848 #if ENABLE_ASH_BUILTIN_TEST
8849 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8852 /* Keep these in proper order since it is searched via bsearch() */
8853 static const struct builtincmd builtintab[] = {
8854 { BUILTIN_SPEC_REG ".", dotcmd },
8855 { BUILTIN_SPEC_REG ":", truecmd },
8856 #if ENABLE_ASH_BUILTIN_TEST
8857 { BUILTIN_REGULAR "[", testcmd },
8858 #if ENABLE_ASH_BASH_COMPAT
8859 { BUILTIN_REGULAR "[[", testcmd },
8862 #if ENABLE_ASH_ALIAS
8863 { BUILTIN_REG_ASSG "alias", aliascmd },
8866 { BUILTIN_REGULAR "bg", fg_bgcmd },
8868 { BUILTIN_SPEC_REG "break", breakcmd },
8869 { BUILTIN_REGULAR "cd", cdcmd },
8870 { BUILTIN_NOSPEC "chdir", cdcmd },
8871 #if ENABLE_ASH_CMDCMD
8872 { BUILTIN_REGULAR "command", commandcmd },
8874 { BUILTIN_SPEC_REG "continue", breakcmd },
8875 #if ENABLE_ASH_BUILTIN_ECHO
8876 { BUILTIN_REGULAR "echo", echocmd },
8878 { BUILTIN_SPEC_REG "eval", evalcmd },
8879 { BUILTIN_SPEC_REG "exec", execcmd },
8880 { BUILTIN_SPEC_REG "exit", exitcmd },
8881 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8882 { BUILTIN_REGULAR "false", falsecmd },
8884 { BUILTIN_REGULAR "fg", fg_bgcmd },
8886 #if ENABLE_ASH_GETOPTS
8887 { BUILTIN_REGULAR "getopts", getoptscmd },
8889 { BUILTIN_NOSPEC "hash", hashcmd },
8890 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8891 { BUILTIN_NOSPEC "help", helpcmd },
8894 { BUILTIN_REGULAR "jobs", jobscmd },
8895 { BUILTIN_REGULAR "kill", killcmd },
8897 #if ENABLE_SH_MATH_SUPPORT
8898 { BUILTIN_NOSPEC "let", letcmd },
8900 { BUILTIN_ASSIGN "local", localcmd },
8901 #if ENABLE_ASH_BUILTIN_PRINTF
8902 { BUILTIN_REGULAR "printf", printfcmd },
8904 { BUILTIN_NOSPEC "pwd", pwdcmd },
8905 { BUILTIN_REGULAR "read", readcmd },
8906 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8907 { BUILTIN_SPEC_REG "return", returncmd },
8908 { BUILTIN_SPEC_REG "set", setcmd },
8909 { BUILTIN_SPEC_REG "shift", shiftcmd },
8910 { BUILTIN_SPEC_REG "source", dotcmd },
8911 #if ENABLE_ASH_BUILTIN_TEST
8912 { BUILTIN_REGULAR "test", testcmd },
8914 { BUILTIN_SPEC_REG "times", timescmd },
8915 { BUILTIN_SPEC_REG "trap", trapcmd },
8916 { BUILTIN_REGULAR "true", truecmd },
8917 { BUILTIN_NOSPEC "type", typecmd },
8918 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8919 { BUILTIN_REGULAR "umask", umaskcmd },
8920 #if ENABLE_ASH_ALIAS
8921 { BUILTIN_REGULAR "unalias", unaliascmd },
8923 { BUILTIN_SPEC_REG "unset", unsetcmd },
8924 { BUILTIN_REGULAR "wait", waitcmd },
8927 /* Should match the above table! */
8928 #define COMMANDCMD (builtintab + \
8930 1 * ENABLE_ASH_BUILTIN_TEST + \
8931 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8932 1 * ENABLE_ASH_ALIAS + \
8933 1 * ENABLE_ASH_JOB_CONTROL + \
8935 #define EXECCMD (builtintab + \
8937 1 * ENABLE_ASH_BUILTIN_TEST + \
8938 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8939 1 * ENABLE_ASH_ALIAS + \
8940 1 * ENABLE_ASH_JOB_CONTROL + \
8942 1 * ENABLE_ASH_CMDCMD + \
8944 ENABLE_ASH_BUILTIN_ECHO + \
8948 * Search the table of builtin commands.
8950 static struct builtincmd *
8951 find_builtin(const char *name)
8953 struct builtincmd *bp;
8956 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
8963 * Execute a simple command.
8966 isassignment(const char *p)
8968 const char *q = endofname(p);
8973 static int FAST_FUNC
8974 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8976 /* Preserve exitstatus of a previous possible redirection
8977 * as POSIX mandates */
8978 return back_exitstatus;
8981 evalcommand(union node *cmd, int flags)
8983 static const struct builtincmd null_bltin = {
8984 "\0\0", bltincmd /* why three NULs? */
8986 struct stackmark smark;
8988 struct arglist arglist;
8989 struct arglist varlist;
8992 const struct strlist *sp;
8993 struct cmdentry cmdentry;
9000 struct builtincmd *bcmd;
9001 smallint cmd_is_exec;
9002 smallint pseudovarflag = 0;
9004 /* First expand the arguments. */
9005 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9006 setstackmark(&smark);
9007 back_exitstatus = 0;
9009 cmdentry.cmdtype = CMDBUILTIN;
9010 cmdentry.u.cmd = &null_bltin;
9011 varlist.lastp = &varlist.list;
9012 *varlist.lastp = NULL;
9013 arglist.lastp = &arglist.list;
9014 *arglist.lastp = NULL;
9017 if (cmd->ncmd.args) {
9018 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9019 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9022 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9023 struct strlist **spp;
9025 spp = arglist.lastp;
9026 if (pseudovarflag && isassignment(argp->narg.text))
9027 expandarg(argp, &arglist, EXP_VARTILDE);
9029 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9031 for (sp = *spp; sp; sp = sp->next)
9035 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9036 for (sp = arglist.list; sp; sp = sp->next) {
9037 TRACE(("evalcommand arg: %s\n", sp->text));
9038 *nargv++ = sp->text;
9043 if (iflag && funcnest == 0 && argc > 0)
9044 lastarg = nargv[-1];
9047 expredir(cmd->ncmd.redirect);
9048 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9051 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9052 struct strlist **spp;
9055 spp = varlist.lastp;
9056 expandarg(argp, &varlist, EXP_VARTILDE);
9059 * Modify the command lookup path, if a PATH= assignment
9063 if (varequal(p, path))
9067 /* Print the command if xflag is set. */
9070 const char *p = " %s";
9073 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9076 for (n = 0; n < 2; n++) {
9078 fdprintf(preverrout_fd, p, sp->text);
9086 safe_write(preverrout_fd, "\n", 1);
9092 /* Now locate the command. */
9094 const char *oldpath;
9095 int cmd_flag = DO_ERR;
9100 find_command(argv[0], &cmdentry, cmd_flag, path);
9101 if (cmdentry.cmdtype == CMDUNKNOWN) {
9107 /* implement bltin and command here */
9108 if (cmdentry.cmdtype != CMDBUILTIN)
9111 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9112 if (cmdentry.u.cmd == EXECCMD)
9114 #if ENABLE_ASH_CMDCMD
9115 if (cmdentry.u.cmd == COMMANDCMD) {
9117 nargv = parse_command_args(argv, &path);
9120 argc -= nargv - argv;
9122 cmd_flag |= DO_NOFUNC;
9130 /* We have a redirection error. */
9132 raise_exception(EXERROR);
9134 exitstatus = status;
9138 /* Execute the command. */
9139 switch (cmdentry.cmdtype) {
9142 #if ENABLE_FEATURE_SH_NOFORK
9143 /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9144 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
9146 /* find_command() encodes applet_no as (-2 - applet_no) */
9147 int applet_no = (- cmdentry.u.index - 2);
9148 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9149 listsetvar(varlist.list, VEXPORT|VSTACK);
9150 /* run <applet>_main() */
9151 exitstatus = run_nofork_applet(applet_no, argv);
9156 /* Fork off a child process if necessary. */
9157 if (!(flags & EV_EXIT) || trap[0]) {
9159 jp = makejob(/*cmd,*/ 1);
9160 if (forkshell(jp, cmd, FORK_FG) != 0) {
9161 exitstatus = waitforjob(jp);
9163 TRACE(("forked child exited with %d\n", exitstatus));
9168 listsetvar(varlist.list, VEXPORT|VSTACK);
9169 shellexec(argv, path, cmdentry.u.index);
9173 cmdenviron = varlist.list;
9175 struct strlist *list = cmdenviron;
9177 if (spclbltin > 0 || argc == 0) {
9179 if (cmd_is_exec && argc > 1)
9182 listsetvar(list, i);
9184 /* Tight loop with builtins only:
9185 * "while kill -0 $child; do true; done"
9186 * will never exit even if $child died, unless we do this
9187 * to reap the zombie and make kill detect that it's gone: */
9188 dowait(DOWAIT_NONBLOCK, NULL);
9190 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9192 int i = exception_type;
9197 exit_status = 128 + SIGINT;
9199 exit_status = 128 + pending_sig;
9200 exitstatus = exit_status;
9201 if (i == EXINT || spclbltin > 0) {
9203 longjmp(exception_handler->loc, 1);
9210 listsetvar(varlist.list, 0);
9211 /* See above for the rationale */
9212 dowait(DOWAIT_NONBLOCK, NULL);
9213 if (evalfun(cmdentry.u.func, argc, argv, flags))
9219 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9221 /* dsl: I think this is intended to be used to support
9222 * '_' in 'vi' command mode during line editing...
9223 * However I implemented that within libedit itself.
9225 setvar("_", lastarg, 0);
9227 popstackmark(&smark);
9231 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9233 char *volatile savecmdname;
9234 struct jmploc *volatile savehandler;
9235 struct jmploc jmploc;
9238 savecmdname = commandname;
9239 i = setjmp(jmploc.loc);
9242 savehandler = exception_handler;
9243 exception_handler = &jmploc;
9244 commandname = argv[0];
9246 optptr = NULL; /* initialize nextopt */
9247 exitstatus = (*cmd->builtin)(argc, argv);
9248 flush_stdout_stderr();
9250 exitstatus |= ferror(stdout);
9252 commandname = savecmdname;
9253 exception_handler = savehandler;
9259 goodname(const char *p)
9261 return !*endofname(p);
9266 * Search for a command. This is called before we fork so that the
9267 * location of the command will be available in the parent as well as
9268 * the child. The check for "goodname" is an overly conservative
9269 * check that the name will not be subject to expansion.
9272 prehash(union node *n)
9274 struct cmdentry entry;
9276 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9277 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9281 /* ============ Builtin commands
9283 * Builtin commands whose functions are closely tied to evaluation
9284 * are implemented here.
9288 * Handle break and continue commands. Break, continue, and return are
9289 * all handled by setting the evalskip flag. The evaluation routines
9290 * above all check this flag, and if it is set they start skipping
9291 * commands rather than executing them. The variable skipcount is
9292 * the number of loops to break/continue, or the number of function
9293 * levels to return. (The latter is always 1.) It should probably
9294 * be an error to break out of more loops than exist, but it isn't
9295 * in the standard shell so we don't make it one here.
9297 static int FAST_FUNC
9298 breakcmd(int argc UNUSED_PARAM, char **argv)
9300 int n = argv[1] ? number(argv[1]) : 1;
9303 ash_msg_and_raise_error(msg_illnum, argv[1]);
9307 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9314 /* ============ input.c
9316 * This implements the input routines used by the parser.
9320 INPUT_PUSH_FILE = 1,
9321 INPUT_NOFILE_OK = 2,
9324 static smallint checkkwd;
9325 /* values of checkkwd variable */
9326 #define CHKALIAS 0x1
9331 * Push a string back onto the input at this current parsefile level.
9332 * We handle aliases this way.
9334 #if !ENABLE_ASH_ALIAS
9335 #define pushstring(s, ap) pushstring(s)
9338 pushstring(char *s, struct alias *ap)
9345 if (g_parsefile->strpush) {
9346 sp = ckzalloc(sizeof(*sp));
9347 sp->prev = g_parsefile->strpush;
9349 sp = &(g_parsefile->basestrpush);
9351 g_parsefile->strpush = sp;
9352 sp->prev_string = g_parsefile->next_to_pgetc;
9353 sp->prev_left_in_line = g_parsefile->left_in_line;
9354 #if ENABLE_ASH_ALIAS
9357 ap->flag |= ALIASINUSE;
9361 g_parsefile->next_to_pgetc = s;
9362 g_parsefile->left_in_line = len;
9369 struct strpush *sp = g_parsefile->strpush;
9372 #if ENABLE_ASH_ALIAS
9374 if (g_parsefile->next_to_pgetc[-1] == ' '
9375 || g_parsefile->next_to_pgetc[-1] == '\t'
9377 checkkwd |= CHKALIAS;
9379 if (sp->string != sp->ap->val) {
9382 sp->ap->flag &= ~ALIASINUSE;
9383 if (sp->ap->flag & ALIASDEAD) {
9384 unalias(sp->ap->name);
9388 g_parsefile->next_to_pgetc = sp->prev_string;
9389 g_parsefile->left_in_line = sp->prev_left_in_line;
9390 g_parsefile->strpush = sp->prev;
9391 if (sp != &(g_parsefile->basestrpush))
9396 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9397 //it peeks whether it is &>, and then pushes back both chars.
9398 //This function needs to save last *next_to_pgetc to buf[0]
9399 //to make two pungetc() reliable. Currently,
9400 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9405 char *buf = g_parsefile->buf;
9407 g_parsefile->next_to_pgetc = buf;
9408 #if ENABLE_FEATURE_EDITING
9410 if (!iflag || g_parsefile->fd != STDIN_FILENO)
9411 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9413 #if ENABLE_FEATURE_TAB_COMPLETION
9414 line_input_state->path_lookup = pathval();
9416 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9418 /* Ctrl+C pressed */
9427 if (nr < 0 && errno == 0) {
9428 /* Ctrl+D pressed */
9433 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
9437 /* nonblock_safe_read() handles this problem */
9439 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9440 int flags = fcntl(0, F_GETFL);
9441 if (flags >= 0 && (flags & O_NONBLOCK)) {
9442 flags &= ~O_NONBLOCK;
9443 if (fcntl(0, F_SETFL, flags) >= 0) {
9444 out2str("sh: turning off NDELAY mode\n");
9455 * Refill the input buffer and return the next input character:
9457 * 1) If a string was pushed back on the input, pop it;
9458 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9459 * or we are reading from a string so we can't refill the buffer,
9461 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9462 * 4) Process input up to the next newline, deleting nul characters.
9464 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9465 #define pgetc_debug(...) ((void)0)
9467 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9468 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9469 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9470 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9478 while (g_parsefile->strpush) {
9479 #if ENABLE_ASH_ALIAS
9480 if (g_parsefile->left_in_line == -1
9481 && g_parsefile->strpush->ap
9482 && g_parsefile->next_to_pgetc[-1] != ' '
9483 && g_parsefile->next_to_pgetc[-1] != '\t'
9485 pgetc_debug("preadbuffer PEOA");
9490 /* try "pgetc" now: */
9491 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9492 g_parsefile->left_in_line,
9493 g_parsefile->next_to_pgetc,
9494 g_parsefile->next_to_pgetc);
9495 if (--g_parsefile->left_in_line >= 0)
9496 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9498 /* on both branches above g_parsefile->left_in_line < 0.
9499 * "pgetc" needs refilling.
9502 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9503 * pungetc() may increment it a few times.
9504 * Assuming it won't increment it to less than -90.
9506 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9507 pgetc_debug("preadbuffer PEOF1");
9508 /* even in failure keep left_in_line and next_to_pgetc
9509 * in lock step, for correct multi-layer pungetc.
9510 * left_in_line was decremented before preadbuffer(),
9511 * must inc next_to_pgetc: */
9512 g_parsefile->next_to_pgetc++;
9516 more = g_parsefile->left_in_buffer;
9518 flush_stdout_stderr();
9522 /* don't try reading again */
9523 g_parsefile->left_in_line = -99;
9524 pgetc_debug("preadbuffer PEOF2");
9525 g_parsefile->next_to_pgetc++;
9530 /* Find out where's the end of line.
9531 * Set g_parsefile->left_in_line
9532 * and g_parsefile->left_in_buffer acordingly.
9533 * NUL chars are deleted.
9535 q = g_parsefile->next_to_pgetc;
9543 memmove(q, q + 1, more);
9547 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9553 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9554 if (g_parsefile->left_in_line < 0)
9559 g_parsefile->left_in_buffer = more;
9564 out2str(g_parsefile->next_to_pgetc);
9568 pgetc_debug("preadbuffer at %d:%p'%s'",
9569 g_parsefile->left_in_line,
9570 g_parsefile->next_to_pgetc,
9571 g_parsefile->next_to_pgetc);
9572 return signed_char2int(*g_parsefile->next_to_pgetc++);
9575 #define pgetc_as_macro() \
9576 (--g_parsefile->left_in_line >= 0 \
9577 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
9584 pgetc_debug("pgetc_fast at %d:%p'%s'",
9585 g_parsefile->left_in_line,
9586 g_parsefile->next_to_pgetc,
9587 g_parsefile->next_to_pgetc);
9588 return pgetc_as_macro();
9591 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9592 #define pgetc_fast() pgetc()
9594 #define pgetc_fast() pgetc_as_macro()
9598 * Same as pgetc(), but ignores PEOA.
9600 #if ENABLE_ASH_ALIAS
9606 pgetc_debug("pgetc_fast at %d:%p'%s'",
9607 g_parsefile->left_in_line,
9608 g_parsefile->next_to_pgetc,
9609 g_parsefile->next_to_pgetc);
9611 } while (c == PEOA);
9615 #define pgetc2() pgetc()
9619 * Read a line from the script.
9622 pfgets(char *line, int len)
9628 while (--nleft > 0) {
9644 * Undo the last call to pgetc. Only one character may be pushed back.
9645 * PEOF may be pushed back.
9650 g_parsefile->left_in_line++;
9651 g_parsefile->next_to_pgetc--;
9652 pgetc_debug("pushed back to %d:%p'%s'",
9653 g_parsefile->left_in_line,
9654 g_parsefile->next_to_pgetc,
9655 g_parsefile->next_to_pgetc);
9659 * To handle the "." command, a stack of input files is used. Pushfile
9660 * adds a new entry to the stack and popfile restores the previous level.
9665 struct parsefile *pf;
9667 pf = ckzalloc(sizeof(*pf));
9668 pf->prev = g_parsefile;
9670 /*pf->strpush = NULL; - ckzalloc did it */
9671 /*pf->basestrpush.prev = NULL;*/
9678 struct parsefile *pf = g_parsefile;
9686 g_parsefile = pf->prev;
9692 * Return to top level.
9697 while (g_parsefile != &basepf)
9702 * Close the file(s) that the shell is reading commands from. Called
9703 * after a fork is done.
9709 if (g_parsefile->fd > 0) {
9710 close(g_parsefile->fd);
9711 g_parsefile->fd = 0;
9716 * Like setinputfile, but takes an open file descriptor. Call this with
9720 setinputfd(int fd, int push)
9722 close_on_exec_on(fd);
9725 g_parsefile->buf = NULL;
9727 g_parsefile->fd = fd;
9728 if (g_parsefile->buf == NULL)
9729 g_parsefile->buf = ckmalloc(IBUFSIZ);
9730 g_parsefile->left_in_buffer = 0;
9731 g_parsefile->left_in_line = 0;
9732 g_parsefile->linno = 1;
9736 * Set the input to take input from a file. If push is set, push the
9737 * old input onto the stack first.
9740 setinputfile(const char *fname, int flags)
9746 fd = open(fname, O_RDONLY);
9748 if (flags & INPUT_NOFILE_OK)
9750 ash_msg_and_raise_error("can't open '%s'", fname);
9753 fd2 = copyfd(fd, 10);
9756 ash_msg_and_raise_error("out of file descriptors");
9759 setinputfd(fd, flags & INPUT_PUSH_FILE);
9766 * Like setinputfile, but takes input from a string.
9769 setinputstring(char *string)
9773 g_parsefile->next_to_pgetc = string;
9774 g_parsefile->left_in_line = strlen(string);
9775 g_parsefile->buf = NULL;
9776 g_parsefile->linno = 1;
9781 /* ============ mail.c
9783 * Routines to check for mail.
9788 #define MAXMBOXES 10
9790 /* times of mailboxes */
9791 static time_t mailtime[MAXMBOXES];
9792 /* Set if MAIL or MAILPATH is changed. */
9793 static smallint mail_var_path_changed;
9796 * Print appropriate message(s) if mail has arrived.
9797 * If mail_var_path_changed is set,
9798 * then the value of MAIL has mail_var_path_changed,
9799 * so we just update the values.
9808 struct stackmark smark;
9811 setstackmark(&smark);
9812 mpath = mpathset() ? mpathval() : mailval();
9813 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9814 p = path_advance(&mpath, nullstr);
9819 for (q = p; *q; q++)
9825 q[-1] = '\0'; /* delete trailing '/' */
9826 if (stat(p, &statb) < 0) {
9830 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9833 pathopt ? pathopt : "you have mail"
9836 *mtp = statb.st_mtime;
9838 mail_var_path_changed = 0;
9839 popstackmark(&smark);
9842 static void FAST_FUNC
9843 changemail(const char *val UNUSED_PARAM)
9845 mail_var_path_changed = 1;
9848 #endif /* ASH_MAIL */
9851 /* ============ ??? */
9854 * Set the shell parameters.
9857 setparam(char **argv)
9863 for (nparam = 0; argv[nparam]; nparam++)
9865 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9867 *ap++ = ckstrdup(*argv++);
9870 freeparam(&shellparam);
9871 shellparam.malloced = 1;
9872 shellparam.nparam = nparam;
9873 shellparam.p = newparam;
9874 #if ENABLE_ASH_GETOPTS
9875 shellparam.optind = 1;
9876 shellparam.optoff = -1;
9881 * Process shell options. The global variable argptr contains a pointer
9882 * to the argument list; we advance it past the options.
9884 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9885 * For a non-interactive shell, an error condition encountered
9886 * by a special built-in ... shall cause the shell to write a diagnostic message
9887 * to standard error and exit as shown in the following table:
9888 * Error Special Built-In
9890 * Utility syntax error (option or operand error) Shall exit
9892 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9893 * we see that bash does not do that (set "finishes" with error code 1 instead,
9894 * and shell continues), and people rely on this behavior!
9896 * set -o barfoo 2>/dev/null
9899 * Oh well. Let's mimic that.
9902 plus_minus_o(char *name, int val)
9907 for (i = 0; i < NOPTS; i++) {
9908 if (strcmp(name, optnames(i)) == 0) {
9913 ash_msg("illegal option %co %s", val ? '-' : '+', name);
9916 for (i = 0; i < NOPTS; i++) {
9918 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9920 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9926 setoption(int flag, int val)
9930 for (i = 0; i < NOPTS; i++) {
9931 if (optletters(i) == flag) {
9936 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
9940 options(int cmdline)
9948 while ((p = *argptr) != NULL) {
9950 if (c != '-' && c != '+')
9953 val = 0; /* val = 0 if c == '+' */
9956 if (p[0] == '\0' || LONE_DASH(p)) {
9958 /* "-" means turn off -x and -v */
9961 /* "--" means reset params */
9962 else if (*argptr == NULL)
9965 break; /* "-" or "--" terminates options */
9968 /* first char was + or - */
9969 while ((c = *p++) != '\0') {
9970 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
9971 if (c == 'c' && cmdline) {
9972 minusc = p; /* command is after shell args */
9973 } else if (c == 'o') {
9974 if (plus_minus_o(*argptr, val)) {
9975 /* it already printed err message */
9976 return 1; /* error */
9980 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9982 /* bash does not accept +-login, we also won't */
9983 } else if (cmdline && val && (c == '-')) { /* long options */
9984 if (strcmp(p, "login") == 0)
9996 * The shift builtin command.
9998 static int FAST_FUNC
9999 shiftcmd(int argc UNUSED_PARAM, char **argv)
10006 n = number(argv[1]);
10007 if (n > shellparam.nparam)
10008 n = 0; /* bash compat, was = shellparam.nparam; */
10010 shellparam.nparam -= n;
10011 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10012 if (shellparam.malloced)
10015 ap2 = shellparam.p;
10016 while ((*ap2++ = *ap1++) != NULL)
10018 #if ENABLE_ASH_GETOPTS
10019 shellparam.optind = 1;
10020 shellparam.optoff = -1;
10027 * POSIX requires that 'set' (but not export or readonly) output the
10028 * variables in lexicographic order - by the locale's collating order (sigh).
10029 * Maybe we could keep them in an ordered balanced binary tree
10030 * instead of hashed lists.
10031 * For now just roll 'em through qsort for printing...
10034 showvars(const char *sep_prefix, int on, int off)
10037 char **ep, **epend;
10039 ep = listvars(on, off, &epend);
10040 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10042 sep = *sep_prefix ? " " : sep_prefix;
10044 for (; ep < epend; ep++) {
10048 p = strchrnul(*ep, '=');
10051 q = single_quote(++p);
10052 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10058 * The set command builtin.
10060 static int FAST_FUNC
10061 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10066 return showvars(nullstr, 0, VUNSET);
10069 if (!options(0)) { /* if no parse error... */
10072 if (*argptr != NULL) {
10080 #if ENABLE_ASH_RANDOM_SUPPORT
10081 static void FAST_FUNC
10082 change_random(const char *value)
10086 if (value == NULL) {
10087 /* "get", generate */
10088 t = next_random(&random_gen);
10089 /* set without recursion */
10090 setvar(vrandom.text, utoa(t), VNOFUNC);
10091 vrandom.flags &= ~VNOFUNC;
10094 t = strtoul(value, NULL, 10);
10095 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10100 #if ENABLE_ASH_GETOPTS
10102 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10111 if (*param_optind < 1)
10113 optnext = optfirst + *param_optind - 1;
10115 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10118 p = optnext[-1] + *optoff;
10119 if (p == NULL || *p == '\0') {
10120 /* Current word is done, advance */
10122 if (p == NULL || *p != '-' || *++p == '\0') {
10129 if (LONE_DASH(p)) /* check for "--" */
10134 for (q = optstr; *q != c;) {
10136 if (optstr[0] == ':') {
10139 err |= setvarsafe("OPTARG", s, 0);
10141 fprintf(stderr, "Illegal option -%c\n", c);
10142 unsetvar("OPTARG");
10152 if (*p == '\0' && (p = *optnext) == NULL) {
10153 if (optstr[0] == ':') {
10156 err |= setvarsafe("OPTARG", s, 0);
10159 fprintf(stderr, "No arg for -%c option\n", c);
10160 unsetvar("OPTARG");
10168 err |= setvarsafe("OPTARG", p, 0);
10171 err |= setvarsafe("OPTARG", nullstr, 0);
10173 *optoff = p ? p - *(optnext - 1) : -1;
10174 *param_optind = optnext - optfirst + 1;
10175 fmtstr(s, sizeof(s), "%d", *param_optind);
10176 err |= setvarsafe("OPTIND", s, VNOFUNC);
10179 err |= setvarsafe(optvar, s, 0);
10183 flush_stdout_stderr();
10184 raise_exception(EXERROR);
10190 * The getopts builtin. Shellparam.optnext points to the next argument
10191 * to be processed. Shellparam.optptr points to the next character to
10192 * be processed in the current argument. If shellparam.optnext is NULL,
10193 * then it's the first time getopts has been called.
10195 static int FAST_FUNC
10196 getoptscmd(int argc, char **argv)
10201 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10203 optbase = shellparam.p;
10204 if (shellparam.optind > shellparam.nparam + 1) {
10205 shellparam.optind = 1;
10206 shellparam.optoff = -1;
10209 optbase = &argv[3];
10210 if (shellparam.optind > argc - 2) {
10211 shellparam.optind = 1;
10212 shellparam.optoff = -1;
10216 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10217 &shellparam.optoff);
10219 #endif /* ASH_GETOPTS */
10222 /* ============ Shell parser */
10225 struct heredoc *next; /* next here document in list */
10226 union node *here; /* redirection node */
10227 char *eofmark; /* string indicating end of input */
10228 smallint striptabs; /* if set, strip leading tabs */
10231 static smallint tokpushback; /* last token pushed back */
10232 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10233 static smallint quoteflag; /* set if (part of) last token was quoted */
10234 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10235 static struct heredoc *heredoclist; /* list of here documents to read */
10236 static char *wordtext; /* text of last word returned by readtoken */
10237 static struct nodelist *backquotelist;
10238 static union node *redirnode;
10239 static struct heredoc *heredoc;
10242 * Called when an unexpected token is read during the parse. The argument
10243 * is the token that is expected, or -1 if more than one type of token can
10244 * occur at this point.
10246 static void raise_error_unexpected_syntax(int) NORETURN;
10248 raise_error_unexpected_syntax(int token)
10253 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
10255 sprintf(msg + l, " (expecting %s)", tokname(token));
10256 raise_error_syntax(msg);
10260 #define EOFMARKLEN 79
10262 /* parsing is heavily cross-recursive, need these forward decls */
10263 static union node *andor(void);
10264 static union node *pipeline(void);
10265 static union node *parse_command(void);
10266 static void parseheredoc(void);
10267 static char peektoken(void);
10268 static int readtoken(void);
10270 static union node *
10273 union node *n1, *n2, *n3;
10276 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10277 if (nlflag == 2 && peektoken())
10283 if (tok == TBACKGND) {
10284 if (n2->type == NPIPE) {
10285 n2->npipe.pipe_backgnd = 1;
10287 if (n2->type != NREDIR) {
10288 n3 = stzalloc(sizeof(struct nredir));
10290 /*n3->nredir.redirect = NULL; - stzalloc did it */
10293 n2->type = NBACKGND;
10299 n3 = stzalloc(sizeof(struct nbinary));
10301 n3->nbinary.ch1 = n1;
10302 n3->nbinary.ch2 = n2;
10318 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10326 pungetc(); /* push back EOF on input */
10330 raise_error_unexpected_syntax(-1);
10337 static union node *
10340 union node *n1, *n2, *n3;
10348 } else if (t == TOR) {
10354 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10356 n3 = stzalloc(sizeof(struct nbinary));
10358 n3->nbinary.ch1 = n1;
10359 n3->nbinary.ch2 = n2;
10364 static union node *
10367 union node *n1, *n2, *pipenode;
10368 struct nodelist *lp, *prev;
10372 TRACE(("pipeline: entered\n"));
10373 if (readtoken() == TNOT) {
10375 checkkwd = CHKKWD | CHKALIAS;
10378 n1 = parse_command();
10379 if (readtoken() == TPIPE) {
10380 pipenode = stzalloc(sizeof(struct npipe));
10381 pipenode->type = NPIPE;
10382 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10383 lp = stzalloc(sizeof(struct nodelist));
10384 pipenode->npipe.cmdlist = lp;
10388 lp = stzalloc(sizeof(struct nodelist));
10389 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10390 lp->n = parse_command();
10392 } while (readtoken() == TPIPE);
10398 n2 = stzalloc(sizeof(struct nnot));
10406 static union node *
10411 n = stzalloc(sizeof(struct narg));
10413 /*n->narg.next = NULL; - stzalloc did it */
10414 n->narg.text = wordtext;
10415 n->narg.backquote = backquotelist;
10420 fixredir(union node *n, const char *text, int err)
10424 TRACE(("Fix redir %s %d\n", text, err));
10426 n->ndup.vname = NULL;
10428 fd = bb_strtou(text, NULL, 10);
10429 if (!errno && fd >= 0)
10430 n->ndup.dupfd = fd;
10431 else if (LONE_DASH(text))
10432 n->ndup.dupfd = -1;
10435 raise_error_syntax("bad fd number");
10436 n->ndup.vname = makename();
10441 * Returns true if the text contains nothing to expand (no dollar signs
10445 noexpand(const char *text)
10451 while ((c = *p++) != '\0') {
10452 if (c == CTLQUOTEMARK)
10456 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
10465 union node *n = redirnode;
10467 if (readtoken() != TWORD)
10468 raise_error_unexpected_syntax(-1);
10469 if (n->type == NHERE) {
10470 struct heredoc *here = heredoc;
10474 if (quoteflag == 0)
10476 TRACE(("Here document %d\n", n->type));
10477 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10478 raise_error_syntax("illegal eof marker for << redirection");
10479 rmescapes(wordtext, 0);
10480 here->eofmark = wordtext;
10482 if (heredoclist == NULL)
10483 heredoclist = here;
10485 for (p = heredoclist; p->next; p = p->next)
10489 } else if (n->type == NTOFD || n->type == NFROMFD) {
10490 fixredir(n, wordtext, 0);
10492 n->nfile.fname = makename();
10496 static union node *
10499 union node *args, **app;
10500 union node *n = NULL;
10501 union node *vars, **vpp;
10502 union node **rpp, *redir;
10504 #if ENABLE_ASH_BASH_COMPAT
10505 smallint double_brackets_flag = 0;
10515 savecheckkwd = CHKALIAS;
10518 checkkwd = savecheckkwd;
10521 #if ENABLE_ASH_BASH_COMPAT
10522 case TAND: /* "&&" */
10523 case TOR: /* "||" */
10524 if (!double_brackets_flag) {
10528 wordtext = (char *) (t == TAND ? "-a" : "-o");
10531 n = stzalloc(sizeof(struct narg));
10533 /*n->narg.next = NULL; - stzalloc did it */
10534 n->narg.text = wordtext;
10535 #if ENABLE_ASH_BASH_COMPAT
10536 if (strcmp("[[", wordtext) == 0)
10537 double_brackets_flag = 1;
10538 else if (strcmp("]]", wordtext) == 0)
10539 double_brackets_flag = 0;
10541 n->narg.backquote = backquotelist;
10542 if (savecheckkwd && isassignment(wordtext)) {
10544 vpp = &n->narg.next;
10547 app = &n->narg.next;
10552 *rpp = n = redirnode;
10553 rpp = &n->nfile.next;
10554 parsefname(); /* read name of redirection file */
10557 if (args && app == &args->narg.next
10560 struct builtincmd *bcmd;
10563 /* We have a function */
10564 if (readtoken() != TRP)
10565 raise_error_unexpected_syntax(TRP);
10566 name = n->narg.text;
10567 if (!goodname(name)
10568 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10570 raise_error_syntax("bad function name");
10573 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10574 n->narg.next = parse_command();
10587 n = stzalloc(sizeof(struct ncmd));
10589 n->ncmd.args = args;
10590 n->ncmd.assign = vars;
10591 n->ncmd.redirect = redir;
10595 static union node *
10596 parse_command(void)
10598 union node *n1, *n2;
10599 union node *ap, **app;
10600 union node *cp, **cpp;
10601 union node *redir, **rpp;
10608 switch (readtoken()) {
10610 raise_error_unexpected_syntax(-1);
10613 n1 = stzalloc(sizeof(struct nif));
10615 n1->nif.test = list(0);
10616 if (readtoken() != TTHEN)
10617 raise_error_unexpected_syntax(TTHEN);
10618 n1->nif.ifpart = list(0);
10620 while (readtoken() == TELIF) {
10621 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10622 n2 = n2->nif.elsepart;
10624 n2->nif.test = list(0);
10625 if (readtoken() != TTHEN)
10626 raise_error_unexpected_syntax(TTHEN);
10627 n2->nif.ifpart = list(0);
10629 if (lasttoken == TELSE)
10630 n2->nif.elsepart = list(0);
10632 n2->nif.elsepart = NULL;
10640 n1 = stzalloc(sizeof(struct nbinary));
10641 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10642 n1->nbinary.ch1 = list(0);
10645 TRACE(("expecting DO got %s %s\n", tokname(got),
10646 got == TWORD ? wordtext : ""));
10647 raise_error_unexpected_syntax(TDO);
10649 n1->nbinary.ch2 = list(0);
10654 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10655 raise_error_syntax("bad for loop variable");
10656 n1 = stzalloc(sizeof(struct nfor));
10658 n1->nfor.var = wordtext;
10659 checkkwd = CHKKWD | CHKALIAS;
10660 if (readtoken() == TIN) {
10662 while (readtoken() == TWORD) {
10663 n2 = stzalloc(sizeof(struct narg));
10665 /*n2->narg.next = NULL; - stzalloc did it */
10666 n2->narg.text = wordtext;
10667 n2->narg.backquote = backquotelist;
10669 app = &n2->narg.next;
10672 n1->nfor.args = ap;
10673 if (lasttoken != TNL && lasttoken != TSEMI)
10674 raise_error_unexpected_syntax(-1);
10676 n2 = stzalloc(sizeof(struct narg));
10678 /*n2->narg.next = NULL; - stzalloc did it */
10679 n2->narg.text = (char *)dolatstr;
10680 /*n2->narg.backquote = NULL;*/
10681 n1->nfor.args = n2;
10683 * Newline or semicolon here is optional (but note
10684 * that the original Bourne shell only allowed NL).
10686 if (lasttoken != TNL && lasttoken != TSEMI)
10689 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10690 if (readtoken() != TDO)
10691 raise_error_unexpected_syntax(TDO);
10692 n1->nfor.body = list(0);
10696 n1 = stzalloc(sizeof(struct ncase));
10698 if (readtoken() != TWORD)
10699 raise_error_unexpected_syntax(TWORD);
10700 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10702 /*n2->narg.next = NULL; - stzalloc did it */
10703 n2->narg.text = wordtext;
10704 n2->narg.backquote = backquotelist;
10706 checkkwd = CHKKWD | CHKALIAS;
10707 } while (readtoken() == TNL);
10708 if (lasttoken != TIN)
10709 raise_error_unexpected_syntax(TIN);
10710 cpp = &n1->ncase.cases;
10712 checkkwd = CHKNL | CHKKWD;
10714 while (t != TESAC) {
10715 if (lasttoken == TLP)
10717 *cpp = cp = stzalloc(sizeof(struct nclist));
10719 app = &cp->nclist.pattern;
10721 *app = ap = stzalloc(sizeof(struct narg));
10723 /*ap->narg.next = NULL; - stzalloc did it */
10724 ap->narg.text = wordtext;
10725 ap->narg.backquote = backquotelist;
10726 if (readtoken() != TPIPE)
10728 app = &ap->narg.next;
10731 //ap->narg.next = NULL;
10732 if (lasttoken != TRP)
10733 raise_error_unexpected_syntax(TRP);
10734 cp->nclist.body = list(2);
10736 cpp = &cp->nclist.next;
10738 checkkwd = CHKNL | CHKKWD;
10742 raise_error_unexpected_syntax(TENDCASE);
10749 n1 = stzalloc(sizeof(struct nredir));
10750 n1->type = NSUBSHELL;
10751 n1->nredir.n = list(0);
10752 /*n1->nredir.redirect = NULL; - stzalloc did it */
10762 return simplecmd();
10765 if (readtoken() != t)
10766 raise_error_unexpected_syntax(t);
10769 /* Now check for redirection which may follow command */
10770 checkkwd = CHKKWD | CHKALIAS;
10772 while (readtoken() == TREDIR) {
10773 *rpp = n2 = redirnode;
10774 rpp = &n2->nfile.next;
10780 if (n1->type != NSUBSHELL) {
10781 n2 = stzalloc(sizeof(struct nredir));
10786 n1->nredir.redirect = redir;
10791 #if ENABLE_ASH_BASH_COMPAT
10792 static int decode_dollar_squote(void)
10794 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10800 p = strchr(C_escapes, c);
10805 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10809 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10811 } else if (c == 'x') { /* \xHH */
10815 } while (isxdigit(c) && --cnt);
10817 if (cnt == 3) { /* \x but next char is "bad" */
10821 } else { /* simple seq like \\ or \t */
10826 c = bb_process_escape_sequence((void*)&p);
10827 } else { /* unrecognized "\z": print both chars unless ' or " */
10828 if (c != '\'' && c != '"') {
10830 c |= 0x100; /* "please encode \, then me" */
10838 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10839 * is not NULL, read a here document. In the latter case, eofmark is the
10840 * word which marks the end of the document and striptabs is true if
10841 * leading tabs should be stripped from the document. The argument firstc
10842 * is the first character of the input token or document.
10844 * Because C does not have internal subroutines, I have simulated them
10845 * using goto's to implement the subroutine linkage. The following macros
10846 * will run code that appears at the end of readtoken1.
10848 #define CHECKEND() {goto checkend; checkend_return:;}
10849 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10850 #define PARSESUB() {goto parsesub; parsesub_return:;}
10851 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10852 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10853 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10855 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10857 /* NB: syntax parameter fits into smallint */
10861 char line[EOFMARKLEN + 1];
10862 struct nodelist *bqlist;
10866 smallint prevsyntax; /* syntax before arithmetic */
10867 #if ENABLE_ASH_EXPAND_PRMT
10868 smallint pssyntax; /* we are expanding a prompt string */
10870 int varnest; /* levels of variables expansion */
10871 int arinest; /* levels of arithmetic expansion */
10872 int parenlevel; /* levels of parens in arithmetic */
10873 int dqvarnest; /* levels of variables expansion within double quotes */
10875 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
10878 /* Avoid longjmp clobbering */
10884 (void) &parenlevel;
10887 (void) &prevsyntax;
10890 startlinno = g_parsefile->linno;
10895 #if ENABLE_ASH_EXPAND_PRMT
10896 pssyntax = (syntax == PSSYNTAX);
10900 dblquote = (syntax == DQSYNTAX);
10906 STARTSTACKSTR(out);
10908 /* For each line, until end of word */
10910 CHECKEND(); /* set c to PEOF if at end of here document */
10911 for (;;) { /* until end of line or end of word */
10912 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10913 switch (SIT(c, syntax)) {
10914 case CNL: /* '\n' */
10915 if (syntax == BASESYNTAX)
10916 goto endword; /* exit outer loop */
10918 g_parsefile->linno++;
10922 goto loop; /* continue outer loop */
10927 if (eofmark == NULL || dblquote)
10928 USTPUTC(CTLESC, out);
10929 #if ENABLE_ASH_BASH_COMPAT
10930 if (c == '\\' && bash_dollar_squote) {
10931 c = decode_dollar_squote();
10933 USTPUTC('\\', out);
10934 c = (unsigned char)c;
10940 case CBACK: /* backslash */
10943 USTPUTC(CTLESC, out);
10944 USTPUTC('\\', out);
10946 } else if (c == '\n') {
10950 #if ENABLE_ASH_EXPAND_PRMT
10951 if (c == '$' && pssyntax) {
10952 USTPUTC(CTLESC, out);
10953 USTPUTC('\\', out);
10956 if (dblquote && c != '\\'
10957 && c != '`' && c != '$'
10958 && (c != '"' || eofmark != NULL)
10960 USTPUTC(CTLESC, out);
10961 USTPUTC('\\', out);
10963 if (SIT(c, SQSYNTAX) == CCTL)
10964 USTPUTC(CTLESC, out);
10972 if (eofmark == NULL) {
10973 USTPUTC(CTLQUOTEMARK, out);
10981 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
10982 if (eofmark != NULL && arinest == 0
10987 if (dqvarnest == 0) {
10988 syntax = BASESYNTAX;
10995 case CVAR: /* '$' */
10996 PARSESUB(); /* parse substitution */
10998 case CENDVAR: /* '}' */
11001 if (dqvarnest > 0) {
11004 USTPUTC(CTLENDVAR, out);
11009 #if ENABLE_SH_MATH_SUPPORT
11010 case CLP: /* '(' in arithmetic */
11014 case CRP: /* ')' in arithmetic */
11015 if (parenlevel > 0) {
11019 if (pgetc() == ')') {
11020 if (--arinest == 0) {
11021 USTPUTC(CTLENDARI, out);
11022 syntax = prevsyntax;
11023 dblquote = (syntax == DQSYNTAX);
11028 * unbalanced parens
11029 * (don't 2nd guess - no error)
11037 case CBQUOTE: /* '`' */
11041 goto endword; /* exit outer loop */
11045 if (varnest == 0) {
11046 #if ENABLE_ASH_BASH_COMPAT
11048 if (pgetc() == '>')
11049 c = 0x100 + '>'; /* flag &> */
11053 goto endword; /* exit outer loop */
11055 #if ENABLE_ASH_ALIAS
11065 #if ENABLE_SH_MATH_SUPPORT
11066 if (syntax == ARISYNTAX)
11067 raise_error_syntax("missing '))'");
11069 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11070 raise_error_syntax("unterminated quoted string");
11071 if (varnest != 0) {
11072 startlinno = g_parsefile->linno;
11074 raise_error_syntax("missing '}'");
11076 USTPUTC('\0', out);
11077 len = out - (char *)stackblock();
11078 out = stackblock();
11079 if (eofmark == NULL) {
11080 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11083 if (isdigit_str9(out)) {
11084 PARSEREDIR(); /* passed as params: out, c */
11085 lasttoken = TREDIR;
11088 /* else: non-number X seen, interpret it
11089 * as "NNNX>file" = "NNNX >file" */
11093 quoteflag = quotef;
11094 backquotelist = bqlist;
11095 grabstackblock(len);
11099 /* end of readtoken routine */
11102 * Check to see whether we are at the end of the here document. When this
11103 * is called, c is set to the first character of the next input line. If
11104 * we are at the end of the here document, this routine sets the c to PEOF.
11108 #if ENABLE_ASH_ALIAS
11114 while (c == '\t') {
11118 if (c == *eofmark) {
11119 if (pfgets(line, sizeof(line)) != NULL) {
11123 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11125 if (*p == '\n' && *q == '\0') {
11127 g_parsefile->linno++;
11128 needprompt = doprompt;
11130 pushstring(line, NULL);
11135 goto checkend_return;
11139 * Parse a redirection operator. The variable "out" points to a string
11140 * specifying the fd to be redirected. The variable "c" contains the
11141 * first character of the redirection operator.
11144 /* out is already checked to be a valid number or "" */
11145 int fd = (*out == '\0' ? -1 : atoi(out));
11148 np = stzalloc(sizeof(struct nfile));
11153 np->type = NAPPEND;
11155 np->type = NCLOBBER;
11158 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11164 #if ENABLE_ASH_BASH_COMPAT
11165 else if (c == 0x100 + '>') { /* this flags &> redirection */
11167 pgetc(); /* this is '>', no need to check */
11171 else { /* c == '<' */
11172 /*np->nfile.fd = 0; - stzalloc did it */
11176 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11177 np = stzalloc(sizeof(struct nhere));
11178 /*np->nfile.fd = 0; - stzalloc did it */
11181 heredoc = stzalloc(sizeof(struct heredoc));
11182 heredoc->here = np;
11185 heredoc->striptabs = 1;
11187 /*heredoc->striptabs = 0; - stzalloc did it */
11193 np->type = NFROMFD;
11197 np->type = NFROMTO;
11209 goto parseredir_return;
11213 * Parse a substitution. At this point, we have read the dollar sign
11214 * and nothing else.
11217 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11218 * (assuming ascii char codes, as the original implementation did) */
11219 #define is_special(c) \
11220 (((unsigned)(c) - 33 < 32) \
11221 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11227 static const char types[] ALIGN1 = "}-+?=";
11230 if (c <= PEOA_OR_PEOF
11231 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11233 #if ENABLE_ASH_BASH_COMPAT
11235 bash_dollar_squote = 1;
11240 } else if (c == '(') { /* $(command) or $((arith)) */
11241 if (pgetc() == '(') {
11242 #if ENABLE_SH_MATH_SUPPORT
11245 raise_error_syntax("you disabled math support for $((arith)) syntax");
11252 USTPUTC(CTLVAR, out);
11253 typeloc = out - (char *)stackblock();
11254 USTPUTC(VSNORMAL, out);
11255 subtype = VSNORMAL;
11263 subtype = VSLENGTH;
11267 if (c > PEOA_OR_PEOF && is_name(c)) {
11271 } while (c > PEOA_OR_PEOF && is_in_name(c));
11272 } else if (isdigit(c)) {
11276 } while (isdigit(c));
11277 } else if (is_special(c)) {
11282 raise_error_syntax("bad substitution");
11284 if (c != '}' && subtype == VSLENGTH)
11289 if (subtype == 0) {
11293 #if ENABLE_ASH_BASH_COMPAT
11294 if (c == ':' || c == '$' || isdigit(c)) {
11296 subtype = VSSUBSTR;
11303 p = strchr(types, c);
11306 subtype = p - types + VSNORMAL;
11311 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11319 #if ENABLE_ASH_BASH_COMPAT
11321 subtype = VSREPLACE;
11324 subtype++; /* VSREPLACEALL */
11333 if (dblquote || arinest)
11335 *((char *)stackblock() + typeloc) = subtype | flags;
11336 if (subtype != VSNORMAL) {
11338 if (dblquote || arinest) {
11343 goto parsesub_return;
11347 * Called to parse command substitutions. Newstyle is set if the command
11348 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11349 * list of commands (passed by reference), and savelen is the number of
11350 * characters on the top of the stack which must be preserved.
11353 struct nodelist **nlpp;
11356 char *volatile str;
11357 struct jmploc jmploc;
11358 struct jmploc *volatile savehandler;
11360 smallint saveprompt = 0;
11363 (void) &saveprompt;
11365 savepbq = parsebackquote;
11366 if (setjmp(jmploc.loc)) {
11368 parsebackquote = 0;
11369 exception_handler = savehandler;
11370 longjmp(exception_handler->loc, 1);
11374 savelen = out - (char *)stackblock();
11376 str = ckmalloc(savelen);
11377 memcpy(str, stackblock(), savelen);
11379 savehandler = exception_handler;
11380 exception_handler = &jmploc;
11383 /* We must read until the closing backquote, giving special
11384 treatment to some slashes, and then push the string and
11385 reread it as input, interpreting it normally. */
11392 STARTSTACKSTR(pout);
11405 g_parsefile->linno++;
11409 * If eating a newline, avoid putting
11410 * the newline into the new character
11411 * stream (via the STPUTC after the
11416 if (pc != '\\' && pc != '`' && pc != '$'
11417 && (!dblquote || pc != '"'))
11418 STPUTC('\\', pout);
11419 if (pc > PEOA_OR_PEOF) {
11425 #if ENABLE_ASH_ALIAS
11428 startlinno = g_parsefile->linno;
11429 raise_error_syntax("EOF in backquote substitution");
11432 g_parsefile->linno++;
11433 needprompt = doprompt;
11442 STPUTC('\0', pout);
11443 psavelen = pout - (char *)stackblock();
11444 if (psavelen > 0) {
11445 pstr = grabstackstr(pout);
11446 setinputstring(pstr);
11451 nlpp = &(*nlpp)->next;
11452 *nlpp = stzalloc(sizeof(**nlpp));
11453 /* (*nlpp)->next = NULL; - stzalloc did it */
11454 parsebackquote = oldstyle;
11457 saveprompt = doprompt;
11464 doprompt = saveprompt;
11465 else if (readtoken() != TRP)
11466 raise_error_unexpected_syntax(TRP);
11471 * Start reading from old file again, ignoring any pushed back
11472 * tokens left from the backquote parsing
11477 while (stackblocksize() <= savelen)
11479 STARTSTACKSTR(out);
11481 memcpy(out, str, savelen);
11482 STADJUST(savelen, out);
11488 parsebackquote = savepbq;
11489 exception_handler = savehandler;
11490 if (arinest || dblquote)
11491 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11493 USTPUTC(CTLBACKQ, out);
11495 goto parsebackq_oldreturn;
11496 goto parsebackq_newreturn;
11499 #if ENABLE_SH_MATH_SUPPORT
11501 * Parse an arithmetic expansion (indicate start of one and set state)
11504 if (++arinest == 1) {
11505 prevsyntax = syntax;
11506 syntax = ARISYNTAX;
11507 USTPUTC(CTLARI, out);
11514 * we collapse embedded arithmetic expansion to
11515 * parenthesis, which should be equivalent
11519 goto parsearith_return;
11523 } /* end of readtoken */
11526 * Read the next input token.
11527 * If the token is a word, we set backquotelist to the list of cmds in
11528 * backquotes. We set quoteflag to true if any part of the word was
11530 * If the token is TREDIR, then we set redirnode to a structure containing
11532 * In all cases, the variable startlinno is set to the number of the line
11533 * on which the token starts.
11535 * [Change comment: here documents and internal procedures]
11536 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11537 * word parsing code into a separate routine. In this case, readtoken
11538 * doesn't need to have any internal procedures, but parseword does.
11539 * We could also make parseoperator in essence the main routine, and
11540 * have parseword (readtoken1?) handle both words and redirection.]
11542 #define NEW_xxreadtoken
11543 #ifdef NEW_xxreadtoken
11544 /* singles must be first! */
11545 static const char xxreadtoken_chars[7] ALIGN1 = {
11546 '\n', '(', ')', /* singles */
11547 '&', '|', ';', /* doubles */
11551 #define xxreadtoken_singles 3
11552 #define xxreadtoken_doubles 3
11554 static const char xxreadtoken_tokens[] ALIGN1 = {
11555 TNL, TLP, TRP, /* only single occurrence allowed */
11556 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11557 TEOF, /* corresponds to trailing nul */
11558 TAND, TOR, TENDCASE /* if double occurrence */
11573 startlinno = g_parsefile->linno;
11574 for (;;) { /* until token or start of word found */
11576 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11580 while ((c = pgetc()) != '\n' && c != PEOF)
11583 } else if (c == '\\') {
11584 if (pgetc() != '\n') {
11586 break; /* return readtoken1(...) */
11588 startlinno = ++g_parsefile->linno;
11594 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11597 g_parsefile->linno++;
11598 needprompt = doprompt;
11601 p = strchr(xxreadtoken_chars, c);
11603 break; /* return readtoken1(...) */
11605 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11607 if (cc == c) { /* double occurrence? */
11608 p += xxreadtoken_doubles + 1;
11611 #if ENABLE_ASH_BASH_COMPAT
11612 if (c == '&' && cc == '>') /* &> */
11613 break; /* return readtoken1(...) */
11618 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11623 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11625 #else /* old xxreadtoken */
11626 #define RETURN(token) return lasttoken = token
11639 startlinno = g_parsefile->linno;
11640 for (;;) { /* until token or start of word found */
11643 case ' ': case '\t':
11644 #if ENABLE_ASH_ALIAS
11649 while ((c = pgetc()) != '\n' && c != PEOF)
11654 if (pgetc() == '\n') {
11655 startlinno = ++g_parsefile->linno;
11663 g_parsefile->linno++;
11664 needprompt = doprompt;
11669 if (pgetc() == '&')
11674 if (pgetc() == '|')
11679 if (pgetc() == ';')
11692 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11695 #endif /* old xxreadtoken */
11702 smallint alreadyseen = tokpushback;
11705 #if ENABLE_ASH_ALIAS
11714 if (checkkwd & CHKNL) {
11721 if (t != TWORD || quoteflag) {
11726 * check for keywords
11728 if (checkkwd & CHKKWD) {
11729 const char *const *pp;
11731 pp = findkwd(wordtext);
11733 lasttoken = t = pp - tokname_array;
11734 TRACE(("keyword %s recognized\n", tokname(t)));
11739 if (checkkwd & CHKALIAS) {
11740 #if ENABLE_ASH_ALIAS
11742 ap = lookupalias(wordtext, 1);
11745 pushstring(ap->val, ap);
11755 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11757 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11769 return tokname_array[t][0];
11773 * Read and parse a command. Returns NODE_EOF on end of file.
11774 * (NULL is a valid parse tree indicating a blank line.)
11776 static union node *
11777 parsecmd(int interact)
11782 doprompt = interact;
11784 setprompt(doprompt);
11796 * Input any here documents.
11801 struct heredoc *here;
11804 here = heredoclist;
11805 heredoclist = NULL;
11811 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11812 here->eofmark, here->striptabs);
11813 n = stzalloc(sizeof(struct narg));
11814 n->narg.type = NARG;
11815 /*n->narg.next = NULL; - stzalloc did it */
11816 n->narg.text = wordtext;
11817 n->narg.backquote = backquotelist;
11818 here->here->nhere.doc = n;
11825 * called by editline -- any expansions to the prompt should be added here.
11827 #if ENABLE_ASH_EXPAND_PRMT
11828 static const char *
11829 expandstr(const char *ps)
11833 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11834 * and token processing _can_ alter it (delete NULs etc). */
11835 setinputstring((char *)ps);
11836 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11839 n.narg.type = NARG;
11840 n.narg.next = NULL;
11841 n.narg.text = wordtext;
11842 n.narg.backquote = backquotelist;
11844 expandarg(&n, NULL, 0);
11845 return stackblock();
11850 * Execute a command or commands contained in a string.
11853 evalstring(char *s, int mask)
11856 struct stackmark smark;
11860 setstackmark(&smark);
11863 while ((n = parsecmd(0)) != NODE_EOF) {
11865 popstackmark(&smark);
11878 * The eval command.
11880 static int FAST_FUNC
11881 evalcmd(int argc UNUSED_PARAM, char **argv)
11890 STARTSTACKSTR(concat);
11892 concat = stack_putstr(p, concat);
11896 STPUTC(' ', concat);
11898 STPUTC('\0', concat);
11899 p = grabstackstr(concat);
11901 evalstring(p, ~SKIPEVAL);
11908 * Read and execute commands. "Top" is nonzero for the top level command
11909 * loop; it turns on prompting if the shell is interactive.
11915 struct stackmark smark;
11919 TRACE(("cmdloop(%d) called\n", top));
11923 setstackmark(&smark);
11926 showjobs(stderr, SHOW_CHANGED);
11929 if (iflag && top) {
11931 #if ENABLE_ASH_MAIL
11935 n = parsecmd(inter);
11937 if (DEBUG > 2 && debug && (n != NODE_EOF))
11940 if (n == NODE_EOF) {
11941 if (!top || numeof >= 50)
11943 if (!stoppedjobs()) {
11946 out2str("\nUse \"exit\" to leave shell.\n");
11949 } else if (nflag == 0) {
11950 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11955 popstackmark(&smark);
11960 return skip & SKIPEVAL;
11967 * Take commands from a file. To be compatible we should do a path
11968 * search for the file, which is necessary to find sub-commands.
11971 find_dot_file(char *name)
11974 const char *path = pathval();
11977 /* don't try this for absolute or relative paths */
11978 if (strchr(name, '/'))
11981 /* IIRC standards do not say whether . is to be searched.
11982 * And it is even smaller this way, making it unconditional for now:
11984 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11989 while ((fullname = path_advance(&path, name)) != NULL) {
11991 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11993 * Don't bother freeing here, since it will
11994 * be freed by the caller.
11998 if (fullname != name)
11999 stunalloc(fullname);
12002 /* not found in the PATH */
12003 ash_msg_and_raise_error("%s: not found", name);
12007 static int FAST_FUNC
12008 dotcmd(int argc, char **argv)
12010 struct strlist *sp;
12011 volatile struct shparam saveparam;
12014 for (sp = cmdenviron; sp; sp = sp->next)
12015 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12017 if (argv[1]) { /* That's what SVR2 does */
12018 char *fullname = find_dot_file(argv[1]);
12021 if (argc) { /* argc > 0, argv[0] != NULL */
12022 saveparam = shellparam;
12023 shellparam.malloced = 0;
12024 shellparam.nparam = argc;
12025 shellparam.p = argv;
12028 setinputfile(fullname, INPUT_PUSH_FILE);
12029 commandname = fullname;
12034 freeparam(&shellparam);
12035 shellparam = saveparam;
12037 status = exitstatus;
12042 static int FAST_FUNC
12043 exitcmd(int argc UNUSED_PARAM, char **argv)
12048 exitstatus = number(argv[1]);
12049 raise_exception(EXEXIT);
12054 * Read a file containing shell functions.
12057 readcmdfile(char *name)
12059 setinputfile(name, INPUT_PUSH_FILE);
12065 /* ============ find_command inplementation */
12068 * Resolve a command name. If you change this routine, you may have to
12069 * change the shellexec routine as well.
12072 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12074 struct tblentry *cmdp;
12081 struct builtincmd *bcmd;
12083 /* If name contains a slash, don't use PATH or hash table */
12084 if (strchr(name, '/') != NULL) {
12085 entry->u.index = -1;
12086 if (act & DO_ABS) {
12087 while (stat(name, &statb) < 0) {
12089 if (errno == EINTR)
12092 entry->cmdtype = CMDUNKNOWN;
12096 entry->cmdtype = CMDNORMAL;
12100 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12102 updatetbl = (path == pathval());
12105 if (strstr(path, "%builtin") != NULL)
12106 act |= DO_ALTBLTIN;
12109 /* If name is in the table, check answer will be ok */
12110 cmdp = cmdlookup(name, 0);
12111 if (cmdp != NULL) {
12114 switch (cmdp->cmdtype) {
12132 } else if (cmdp->rehash == 0)
12133 /* if not invalidated by cd, we're done */
12137 /* If %builtin not in path, check for builtin next */
12138 bcmd = find_builtin(name);
12140 if (IS_BUILTIN_REGULAR(bcmd))
12141 goto builtin_success;
12142 if (act & DO_ALTPATH) {
12143 if (!(act & DO_ALTBLTIN))
12144 goto builtin_success;
12145 } else if (builtinloc <= 0) {
12146 goto builtin_success;
12150 #if ENABLE_FEATURE_SH_STANDALONE
12152 int applet_no = find_applet_by_name(name);
12153 if (applet_no >= 0) {
12154 entry->cmdtype = CMDNORMAL;
12155 entry->u.index = -2 - applet_no;
12161 /* We have to search path. */
12162 prev = -1; /* where to start */
12163 if (cmdp && cmdp->rehash) { /* doing a rehash */
12164 if (cmdp->cmdtype == CMDBUILTIN)
12167 prev = cmdp->param.index;
12173 while ((fullname = path_advance(&path, name)) != NULL) {
12174 stunalloc(fullname);
12175 /* NB: code below will still use fullname
12176 * despite it being "unallocated" */
12179 if (prefix(pathopt, "builtin")) {
12181 goto builtin_success;
12184 if ((act & DO_NOFUNC)
12185 || !prefix(pathopt, "func")
12186 ) { /* ignore unimplemented options */
12190 /* if rehash, don't redo absolute path names */
12191 if (fullname[0] == '/' && idx <= prev) {
12194 TRACE(("searchexec \"%s\": no change\n", name));
12197 while (stat(fullname, &statb) < 0) {
12199 if (errno == EINTR)
12202 if (errno != ENOENT && errno != ENOTDIR)
12206 e = EACCES; /* if we fail, this will be the error */
12207 if (!S_ISREG(statb.st_mode))
12209 if (pathopt) { /* this is a %func directory */
12210 stalloc(strlen(fullname) + 1);
12211 /* NB: stalloc will return space pointed by fullname
12212 * (because we don't have any intervening allocations
12213 * between stunalloc above and this stalloc) */
12214 readcmdfile(fullname);
12215 cmdp = cmdlookup(name, 0);
12216 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12217 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12218 stunalloc(fullname);
12221 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12223 entry->cmdtype = CMDNORMAL;
12224 entry->u.index = idx;
12228 cmdp = cmdlookup(name, 1);
12229 cmdp->cmdtype = CMDNORMAL;
12230 cmdp->param.index = idx;
12235 /* We failed. If there was an entry for this command, delete it */
12236 if (cmdp && updatetbl)
12237 delete_cmd_entry();
12239 ash_msg("%s: %s", name, errmsg(e, "not found"));
12240 entry->cmdtype = CMDUNKNOWN;
12245 entry->cmdtype = CMDBUILTIN;
12246 entry->u.cmd = bcmd;
12250 cmdp = cmdlookup(name, 1);
12251 cmdp->cmdtype = CMDBUILTIN;
12252 cmdp->param.cmd = bcmd;
12256 entry->cmdtype = cmdp->cmdtype;
12257 entry->u = cmdp->param;
12261 /* ============ trap.c */
12264 * The trap builtin.
12266 static int FAST_FUNC
12267 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12276 for (signo = 0; signo < NSIG; signo++) {
12277 char *tr = trap_ptr[signo];
12279 /* note: bash adds "SIG", but only if invoked
12280 * as "bash". If called as "sh", or if set -o posix,
12281 * then it prints short signal names.
12282 * We are printing short names: */
12283 out1fmt("trap -- %s %s\n",
12285 get_signame(signo));
12286 /* trap_ptr != trap only if we are in special-cased `trap` code.
12287 * In this case, we will exit very soon, no need to free(). */
12288 /* if (trap_ptr != trap && tp[0]) */
12293 if (trap_ptr != trap) {
12305 signo = get_signum(*ap);
12307 ash_msg_and_raise_error("%s: bad trap", *ap);
12310 if (LONE_DASH(action))
12313 action = ckstrdup(action);
12316 trap[signo] = action;
12326 /* ============ Builtins */
12328 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12330 * Lists available builtins
12332 static int FAST_FUNC
12333 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12339 "Built-in commands:\n"
12340 "------------------\n");
12341 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12342 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12343 builtintab[i].name + 1);
12349 #if ENABLE_FEATURE_SH_STANDALONE
12351 const char *a = applet_names;
12353 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12358 a += strlen(a) + 1;
12363 return EXIT_SUCCESS;
12365 #endif /* FEATURE_SH_EXTRA_QUIET */
12368 * The export and readonly commands.
12370 static int FAST_FUNC
12371 exportcmd(int argc UNUSED_PARAM, char **argv)
12377 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12379 if (nextopt("p") != 'p') {
12384 p = strchr(name, '=');
12388 vp = *findvar(hashvar(name), name);
12394 setvar(name, p, flag);
12395 } while ((name = *++aptr) != NULL);
12399 showvars(argv[0], flag, 0);
12404 * Delete a function if it exists.
12407 unsetfunc(const char *name)
12409 struct tblentry *cmdp;
12411 cmdp = cmdlookup(name, 0);
12412 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12413 delete_cmd_entry();
12417 * The unset builtin command. We unset the function before we unset the
12418 * variable to allow a function to be unset when there is a readonly variable
12419 * with the same name.
12421 static int FAST_FUNC
12422 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12429 while ((i = nextopt("vf")) != '\0') {
12433 for (ap = argptr; *ap; ap++) {
12449 #include <sys/times.h>
12451 static const unsigned char timescmd_str[] ALIGN1 = {
12452 ' ', offsetof(struct tms, tms_utime),
12453 '\n', offsetof(struct tms, tms_stime),
12454 ' ', offsetof(struct tms, tms_cutime),
12455 '\n', offsetof(struct tms, tms_cstime),
12459 static int FAST_FUNC
12460 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12462 long clk_tck, s, t;
12463 const unsigned char *p;
12466 clk_tck = sysconf(_SC_CLK_TCK);
12471 t = *(clock_t *)(((char *) &buf) + p[1]);
12473 out1fmt("%ldm%ld.%.3lds%c",
12475 ((t - s * clk_tck) * 1000) / clk_tck,
12477 } while (*(p += 2));
12482 #if ENABLE_SH_MATH_SUPPORT
12484 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12485 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12487 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12489 static int FAST_FUNC
12490 letcmd(int argc UNUSED_PARAM, char **argv)
12496 ash_msg_and_raise_error("expression expected");
12498 i = ash_arith(*argv);
12503 #endif /* SH_MATH_SUPPORT */
12506 /* ============ miscbltin.c
12508 * Miscellaneous builtins.
12513 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12514 typedef enum __rlimit_resource rlim_t;
12518 * The read builtin. Options:
12519 * -r Do not interpret '\' specially
12520 * -s Turn off echo (tty only)
12521 * -n NCHARS Read NCHARS max
12522 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12523 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12524 * -u FD Read from given FD instead of fd 0
12525 * This uses unbuffered input, which may be avoidable in some cases.
12526 * TODO: bash also has:
12527 * -a ARRAY Read into array[0],[1],etc
12528 * -d DELIM End on DELIM char, not newline
12529 * -e Use line editing (tty only)
12531 static int FAST_FUNC
12532 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12534 static const char *const arg_REPLY[] = { "REPLY", NULL };
12547 #if ENABLE_ASH_READ_NCHARS
12548 int nchars = 0; /* if != 0, -n is in effect */
12550 struct termios tty, old_tty;
12552 #if ENABLE_ASH_READ_TIMEOUT
12553 unsigned end_ms = 0;
12554 unsigned timeout = 0;
12559 while ((i = nextopt("p:u:r"
12560 IF_ASH_READ_TIMEOUT("t:")
12561 IF_ASH_READ_NCHARS("n:s")
12565 prompt = optionarg;
12567 #if ENABLE_ASH_READ_NCHARS
12569 nchars = bb_strtou(optionarg, NULL, 10);
12570 if (nchars < 0 || errno)
12571 ash_msg_and_raise_error("invalid count");
12572 /* nchars == 0: off (bash 3.2 does this too) */
12578 #if ENABLE_ASH_READ_TIMEOUT
12580 timeout = bb_strtou(optionarg, NULL, 10);
12581 if (errno || timeout > UINT_MAX / 2048)
12582 ash_msg_and_raise_error("invalid timeout");
12584 #if 0 /* even bash have no -t N.NNN support */
12585 ts.tv_sec = bb_strtou(optionarg, &p, 10);
12587 /* EINVAL means number is ok, but not terminated by NUL */
12588 if (*p == '.' && errno == EINVAL) {
12592 ts.tv_usec = bb_strtou(p, &p2, 10);
12594 ash_msg_and_raise_error("invalid timeout");
12596 /* normalize to usec */
12598 ash_msg_and_raise_error("invalid timeout");
12599 while (scale++ < 6)
12602 } else if (ts.tv_sec < 0 || errno) {
12603 ash_msg_and_raise_error("invalid timeout");
12605 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
12606 ash_msg_and_raise_error("invalid timeout");
12615 fd = bb_strtou(optionarg, NULL, 10);
12616 if (fd < 0 || errno)
12617 ash_msg_and_raise_error("invalid file descriptor");
12623 if (prompt && isatty(fd)) {
12628 ap = (char**)arg_REPLY;
12629 ifs = bltinlookup("IFS");
12632 #if ENABLE_ASH_READ_NCHARS
12633 tcgetattr(fd, &tty);
12635 if (nchars || silent) {
12637 tty.c_lflag &= ~ICANON;
12638 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
12641 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12643 /* if tcgetattr failed, tcsetattr will fail too.
12644 * Ignoring, it's harmless. */
12645 tcsetattr(fd, TCSANOW, &tty);
12652 #if ENABLE_ASH_READ_TIMEOUT
12653 if (timeout) /* NB: ensuring end_ms is nonzero */
12654 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12658 const char *is_ifs;
12660 #if ENABLE_ASH_READ_TIMEOUT
12662 struct pollfd pfd[1];
12664 pfd[0].events = POLLIN;
12665 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12666 if ((int)timeout <= 0 /* already late? */
12667 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12668 ) { /* timed out! */
12669 #if ENABLE_ASH_READ_NCHARS
12670 tcsetattr(fd, TCSANOW, &old_tty);
12676 if (nonblock_safe_read(fd, &c, 1) != 1) {
12688 if (!rflag && c == '\\') {
12694 /* $IFS splitting */
12695 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
12696 is_ifs = strchr(ifs, c);
12697 if (startword && is_ifs) {
12700 /* it is a non-space ifs char */
12702 if (startword == 1) /* first one? */
12703 continue; /* yes, it is not next word yet */
12706 if (ap[1] != NULL && is_ifs) {
12709 beg = stackblock();
12710 setvar(*ap, beg, 0);
12712 /* can we skip one non-space ifs char? (2: yes) */
12713 startword = isspace(c) ? 2 : 1;
12720 /* end of do {} while: */
12721 #if ENABLE_ASH_READ_NCHARS
12727 #if ENABLE_ASH_READ_NCHARS
12728 tcsetattr(fd, TCSANOW, &old_tty);
12732 /* Remove trailing space ifs chars */
12733 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
12735 setvar(*ap, stackblock(), 0);
12736 while (*++ap != NULL)
12737 setvar(*ap, nullstr, 0);
12741 static int FAST_FUNC
12742 umaskcmd(int argc UNUSED_PARAM, char **argv)
12744 static const char permuser[3] ALIGN1 = "ugo";
12745 static const char permmode[3] ALIGN1 = "rwx";
12746 static const short permmask[] ALIGN2 = {
12747 S_IRUSR, S_IWUSR, S_IXUSR,
12748 S_IRGRP, S_IWGRP, S_IXGRP,
12749 S_IROTH, S_IWOTH, S_IXOTH
12752 /* TODO: use bb_parse_mode() instead */
12757 int symbolic_mode = 0;
12759 while (nextopt("S") != '\0') {
12770 if (symbolic_mode) {
12774 for (i = 0; i < 3; i++) {
12777 *p++ = permuser[i];
12779 for (j = 0; j < 3; j++) {
12780 if ((mask & permmask[3 * i + j]) == 0) {
12781 *p++ = permmode[j];
12789 out1fmt("%.4o\n", mask);
12792 if (isdigit((unsigned char) *ap)) {
12795 if (*ap >= '8' || *ap < '0')
12796 ash_msg_and_raise_error(msg_illnum, argv[1]);
12797 mask = (mask << 3) + (*ap - '0');
12798 } while (*++ap != '\0');
12801 mask = ~mask & 0777;
12802 if (!bb_parse_mode(ap, &mask)) {
12803 ash_msg_and_raise_error("illegal mode: %s", ap);
12805 umask(~mask & 0777);
12814 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12815 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12816 * ash by J.T. Conklin.
12821 uint8_t cmd; /* RLIMIT_xxx fit into it */
12822 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
12826 static const struct limits limits_tbl[] = {
12828 { RLIMIT_CPU, 0, 't' },
12830 #ifdef RLIMIT_FSIZE
12831 { RLIMIT_FSIZE, 9, 'f' },
12834 { RLIMIT_DATA, 10, 'd' },
12836 #ifdef RLIMIT_STACK
12837 { RLIMIT_STACK, 10, 's' },
12840 { RLIMIT_CORE, 9, 'c' },
12843 { RLIMIT_RSS, 10, 'm' },
12845 #ifdef RLIMIT_MEMLOCK
12846 { RLIMIT_MEMLOCK, 10, 'l' },
12848 #ifdef RLIMIT_NPROC
12849 { RLIMIT_NPROC, 0, 'p' },
12851 #ifdef RLIMIT_NOFILE
12852 { RLIMIT_NOFILE, 0, 'n' },
12855 { RLIMIT_AS, 10, 'v' },
12857 #ifdef RLIMIT_LOCKS
12858 { RLIMIT_LOCKS, 0, 'w' },
12861 static const char limits_name[] =
12863 "time(seconds)" "\0"
12865 #ifdef RLIMIT_FSIZE
12866 "file(blocks)" "\0"
12871 #ifdef RLIMIT_STACK
12875 "coredump(blocks)" "\0"
12880 #ifdef RLIMIT_MEMLOCK
12881 "locked memory(kb)" "\0"
12883 #ifdef RLIMIT_NPROC
12886 #ifdef RLIMIT_NOFILE
12892 #ifdef RLIMIT_LOCKS
12897 enum limtype { SOFT = 0x1, HARD = 0x2 };
12900 printlim(enum limtype how, const struct rlimit *limit,
12901 const struct limits *l)
12905 val = limit->rlim_max;
12907 val = limit->rlim_cur;
12909 if (val == RLIM_INFINITY)
12910 out1fmt("unlimited\n");
12912 val >>= l->factor_shift;
12913 out1fmt("%lld\n", (long long) val);
12917 static int FAST_FUNC
12918 ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12921 enum limtype how = SOFT | HARD;
12922 const struct limits *l;
12925 struct rlimit limit;
12928 while ((optc = nextopt("HSa"
12932 #ifdef RLIMIT_FSIZE
12938 #ifdef RLIMIT_STACK
12947 #ifdef RLIMIT_MEMLOCK
12950 #ifdef RLIMIT_NPROC
12953 #ifdef RLIMIT_NOFILE
12959 #ifdef RLIMIT_LOCKS
12977 for (l = limits_tbl; l->option != what; l++)
12980 set = *argptr ? 1 : 0;
12985 if (all || argptr[1])
12986 ash_msg_and_raise_error("too many arguments");
12987 if (strncmp(p, "unlimited\n", 9) == 0)
12988 val = RLIM_INFINITY;
12990 if (sizeof(val) == sizeof(int))
12991 val = bb_strtou(p, NULL, 10);
12992 else if (sizeof(val) == sizeof(long))
12993 val = bb_strtoul(p, NULL, 10);
12995 val = bb_strtoull(p, NULL, 10);
12997 ash_msg_and_raise_error("bad number");
12998 val <<= l->factor_shift;
13002 const char *lname = limits_name;
13003 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
13004 getrlimit(l->cmd, &limit);
13005 out1fmt("%-20s ", lname);
13006 lname += strlen(lname) + 1;
13007 printlim(how, &limit, l);
13012 getrlimit(l->cmd, &limit);
13015 limit.rlim_max = val;
13017 limit.rlim_cur = val;
13018 if (setrlimit(l->cmd, &limit) < 0)
13019 ash_msg_and_raise_error("error setting limit (%m)");
13021 printlim(how, &limit, l);
13026 /* ============ main() and helpers */
13029 * Called to exit the shell.
13031 static void exitshell(void) NORETURN;
13039 status = exitstatus;
13040 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13041 if (setjmp(loc.loc)) {
13042 if (exception_type == EXEXIT)
13043 /* dash bug: it just does _exit(exitstatus) here
13044 * but we have to do setjobctl(0) first!
13045 * (bug is still not fixed in dash-0.5.3 - if you run dash
13046 * under Midnight Commander, on exit from dash MC is backgrounded) */
13047 status = exitstatus;
13050 exception_handler = &loc;
13057 flush_stdout_stderr();
13067 /* from input.c: */
13068 basepf.next_to_pgetc = basepf.buf = basebuf;
13071 signal(SIGCHLD, SIG_DFL);
13077 struct stat st1, st2;
13080 for (envp = environ; envp && *envp; envp++) {
13081 if (strchr(*envp, '=')) {
13082 setvareq(*envp, VEXPORT|VTEXTFIXED);
13086 setvar("PPID", utoa(getppid()), 0);
13088 p = lookupvar("PWD");
13090 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13091 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13098 * Process the shell command line arguments.
13101 procargs(char **argv)
13104 const char *xminusc;
13109 /* if (xargv[0]) - mmm, this is always true! */
13111 for (i = 0; i < NOPTS; i++)
13115 /* it already printed err message */
13116 raise_exception(EXERROR);
13120 if (*xargv == NULL) {
13122 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13125 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13129 for (i = 0; i < NOPTS; i++)
13130 if (optlist[i] == 2)
13135 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13140 } else if (!sflag) {
13141 setinputfile(*xargv, 0);
13144 commandname = arg0;
13147 shellparam.p = xargv;
13148 #if ENABLE_ASH_GETOPTS
13149 shellparam.optind = 1;
13150 shellparam.optoff = -1;
13152 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13154 shellparam.nparam++;
13161 * Read /etc/profile or .profile.
13164 read_profile(const char *name)
13168 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13177 * This routine is called when an error or an interrupt occurs in an
13178 * interactive shell and control is returned to the main command loop.
13186 /* from input.c: */
13187 g_parsefile->left_in_buffer = 0;
13188 g_parsefile->left_in_line = 0; /* clear input buffer */
13190 /* from parser.c: */
13193 /* from redir.c: */
13194 clearredir(/*drop:*/ 0);
13198 static short profile_buf[16384];
13199 extern int etext();
13203 * Main routine. We initialize things, parse the arguments, execute
13204 * profiles if we're a login shell, and then call cmdloop to execute
13205 * commands. The setjmp call sets up the location to jump to when an
13206 * exception occurs. When an exception occurs the variable "state"
13207 * is used to figure out how far we had gotten.
13209 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13210 int ash_main(int argc UNUSED_PARAM, char **argv)
13212 const char *shinit;
13213 volatile smallint state;
13214 struct jmploc jmploc;
13215 struct stackmark smark;
13217 /* Initialize global data */
13221 #if ENABLE_ASH_ALIAS
13227 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13230 #if ENABLE_FEATURE_EDITING
13231 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13234 if (setjmp(jmploc.loc)) {
13240 e = exception_type;
13244 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13247 outcslow('\n', stderr);
13249 popstackmark(&smark);
13250 FORCE_INT_ON; /* enable interrupts */
13259 exception_handler = &jmploc;
13262 TRACE(("Shell args: "));
13263 trace_puts_args(argv);
13265 rootpid = getpid();
13268 setstackmark(&smark);
13271 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13273 const char *hp = lookupvar("HISTFILE");
13276 hp = lookupvar("HOME");
13278 char *defhp = concat_path_file(hp, ".ash_history");
13279 setvar("HISTFILE", defhp, 0);
13285 if (/* argv[0] && */ argv[0][0] == '-')
13289 read_profile("/etc/profile");
13292 read_profile(".profile");
13298 getuid() == geteuid() && getgid() == getegid() &&
13302 shinit = lookupvar("ENV");
13303 if (shinit != NULL && *shinit != '\0') {
13304 read_profile(shinit);
13310 /* evalstring pushes parsefile stack.
13311 * Ensure we don't falsely claim that 0 (stdin)
13312 * is one of stacked source fds.
13313 * Testcase: ash -c 'exec 1>&0' must not complain. */
13315 g_parsefile->fd = -1;
13316 evalstring(minusc, 0);
13319 if (sflag || minusc == NULL) {
13320 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13322 const char *hp = lookupvar("HISTFILE");
13324 line_input_state->hist_file = hp;
13327 state4: /* XXX ??? - why isn't this before the "if" statement */
13335 extern void _mcleanup(void);
13345 * Copyright (c) 1989, 1991, 1993, 1994
13346 * The Regents of the University of California. All rights reserved.
13348 * This code is derived from software contributed to Berkeley by
13349 * Kenneth Almquist.
13351 * Redistribution and use in source and binary forms, with or without
13352 * modification, are permitted provided that the following conditions
13354 * 1. Redistributions of source code must retain the above copyright
13355 * notice, this list of conditions and the following disclaimer.
13356 * 2. Redistributions in binary form must reproduce the above copyright
13357 * notice, this list of conditions and the following disclaimer in the
13358 * documentation and/or other materials provided with the distribution.
13359 * 3. Neither the name of the University nor the names of its contributors
13360 * may be used to endorse or promote products derived from this software
13361 * without specific prior written permission.
13363 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13364 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13365 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13366 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13367 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13368 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13369 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13370 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13371 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13372 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF