1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
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 */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
39 #include "busybox.h" /* for applet_names */
43 #include <sys/times.h>
45 #include "shell_common.h"
46 #if ENABLE_SH_MATH_SUPPORT
49 #if ENABLE_ASH_RANDOM_SUPPORT
52 # define CLEAR_RANDOM_T(rnd) ((void)0)
55 #include "NUM_APPLETS.h"
57 /* STANDALONE does not make sense, and won't compile */
58 # undef CONFIG_FEATURE_SH_STANDALONE
59 # undef ENABLE_FEATURE_SH_STANDALONE
60 # undef IF_FEATURE_SH_STANDALONE
61 # undef IF_NOT_FEATURE_SH_STANDALONE
62 # define ENABLE_FEATURE_SH_STANDALONE 0
63 # define IF_FEATURE_SH_STANDALONE(...)
64 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
68 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
72 # error "Do not even bother, ash will not run on NOMMU machine"
75 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
76 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
77 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
79 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
80 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
85 //config: depends on !NOMMU
87 //config: Tha 'ash' shell adds about 60k in the default configuration and is
88 //config: the most complete and most pedantically correct shell included with
89 //config: busybox. This shell is actually a derivative of the Debian 'dash'
90 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
91 //config: (written by Kenneth Almquist) from NetBSD.
93 //config:config ASH_BASH_COMPAT
94 //config: bool "bash-compatible extensions"
96 //config: depends on ASH
98 //config: Enable bash-compatible extensions.
100 //config:config ASH_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable"
103 //config: depends on ASH
105 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_JOB_CONTROL
108 //config: bool "Job control"
110 //config: depends on ASH
112 //config: Enable job control in the ash shell.
114 //config:config ASH_ALIAS
115 //config: bool "Alias support"
117 //config: depends on ASH
119 //config: Enable alias support in the ash shell.
121 //config:config ASH_GETOPTS
122 //config: bool "Builtin getopt to parse positional parameters"
124 //config: depends on ASH
126 //config: Enable support for getopts builtin in ash.
128 //config:config ASH_BUILTIN_ECHO
129 //config: bool "Builtin version of 'echo'"
131 //config: depends on ASH
133 //config: Enable support for echo builtin in ash.
135 //config:config ASH_BUILTIN_PRINTF
136 //config: bool "Builtin version of 'printf'"
138 //config: depends on ASH
140 //config: Enable support for printf builtin in ash.
142 //config:config ASH_BUILTIN_TEST
143 //config: bool "Builtin version of 'test'"
145 //config: depends on ASH
147 //config: Enable support for test builtin in ash.
149 //config:config ASH_CMDCMD
150 //config: bool "'command' command to override shell builtins"
152 //config: depends on ASH
154 //config: Enable support for the ash 'command' builtin, which allows
155 //config: you to run the specified command with the specified arguments,
156 //config: even when there is an ash builtin command with the same name.
158 //config:config ASH_MAIL
159 //config: bool "Check for new mail on interactive shells"
161 //config: depends on ASH
163 //config: Enable "check for new mail" function in the ash shell.
165 //config:config ASH_OPTIMIZE_FOR_SIZE
166 //config: bool "Optimize for size instead of speed"
168 //config: depends on ASH
170 //config: Compile ash for reduced size at the price of speed.
172 //config:config ASH_RANDOM_SUPPORT
173 //config: bool "Pseudorandom generator and $RANDOM variable"
175 //config: depends on ASH
177 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
178 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
179 //config: You can reset the generator by using a specified start value.
180 //config: After "unset RANDOM" the generator will switch off and this
181 //config: variable will no longer have special treatment.
183 //config:config ASH_EXPAND_PRMT
184 //config: bool "Expand prompt string"
186 //config: depends on ASH
188 //config: "PS#" may contain volatile content, such as backquote commands.
189 //config: This option recreates the prompt string from the environment
190 //config: variable each time it is displayed.
194 /* ============ Hash table sizes. Configurable. */
198 #define CMDTABLESIZE 31 /* should be prime */
201 /* ============ Shell options */
203 static const char *const optletters_optnames[] = {
218 #if ENABLE_ASH_BASH_COMPAT
227 #define optletters(n) optletters_optnames[n][0]
228 #define optnames(n) (optletters_optnames[n] + 1)
230 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
233 /* ============ Misc data */
235 #define msg_illnum "Illegal number: %s"
238 * We enclose jmp_buf in a structure so that we can declare pointers to
239 * jump locations. The global variable handler contains the location to
240 * jump to when an exception occurs, and the global variable exception_type
241 * contains a code identifying the exception. To implement nested
242 * exception handlers, the user should save the value of handler on entry
243 * to an inner scope, set handler to point to a jmploc structure for the
244 * inner scope, and restore handler on exit from the scope.
250 struct globals_misc {
251 /* pid of main shell */
253 /* shell level: 0 for the main shell, 1 for its children, and so on */
255 #define rootshell (!shlvl)
256 char *minusc; /* argument to -c option */
258 char *curdir; // = nullstr; /* current working directory */
259 char *physdir; // = nullstr; /* physical working directory */
261 char *arg0; /* value of $0 */
263 struct jmploc *exception_handler;
265 volatile int suppress_int; /* counter */
266 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
267 /* last pending signal */
268 volatile /*sig_atomic_t*/ smallint pending_sig;
269 smallint exception_type; /* kind of exception (0..5) */
271 #define EXINT 0 /* SIGINT received */
272 #define EXERROR 1 /* a generic error */
273 #define EXSHELLPROC 2 /* execute a shell procedure */
274 #define EXEXEC 3 /* command execution failed */
275 #define EXEXIT 4 /* exit the shell */
276 #define EXSIG 5 /* trapped signal in wait(1) */
279 char nullstr[1]; /* zero length string */
282 #define eflag optlist[0]
283 #define fflag optlist[1]
284 #define Iflag optlist[2]
285 #define iflag optlist[3]
286 #define mflag optlist[4]
287 #define nflag optlist[5]
288 #define sflag optlist[6]
289 #define xflag optlist[7]
290 #define vflag optlist[8]
291 #define Cflag optlist[9]
292 #define aflag optlist[10]
293 #define bflag optlist[11]
294 #define uflag optlist[12]
295 #define viflag optlist[13]
296 #if ENABLE_ASH_BASH_COMPAT
297 # define pipefail optlist[14]
302 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
303 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
306 /* trap handler commands */
308 * Sigmode records the current value of the signal handlers for the various
309 * modes. A value of zero means that the current handler is not known.
310 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
312 char sigmode[NSIG - 1];
313 #define S_DFL 1 /* default signal handling (SIG_DFL) */
314 #define S_CATCH 2 /* signal is caught */
315 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
316 #define S_HARD_IGN 4 /* signal is ignored permenantly */
318 /* indicates specified signal received */
319 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
320 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
322 char **trap_ptr; /* used only by "trap hack" */
324 /* Rarely referenced stuff */
325 #if ENABLE_ASH_RANDOM_SUPPORT
328 pid_t backgndpid; /* pid of last background process */
329 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
331 extern struct globals_misc *const ash_ptr_to_globals_misc;
332 #define G_misc (*ash_ptr_to_globals_misc)
333 #define rootpid (G_misc.rootpid )
334 #define shlvl (G_misc.shlvl )
335 #define minusc (G_misc.minusc )
336 #define curdir (G_misc.curdir )
337 #define physdir (G_misc.physdir )
338 #define arg0 (G_misc.arg0 )
339 #define exception_handler (G_misc.exception_handler)
340 #define exception_type (G_misc.exception_type )
341 #define suppress_int (G_misc.suppress_int )
342 #define pending_int (G_misc.pending_int )
343 #define pending_sig (G_misc.pending_sig )
344 #define isloginsh (G_misc.isloginsh )
345 #define nullstr (G_misc.nullstr )
346 #define optlist (G_misc.optlist )
347 #define sigmode (G_misc.sigmode )
348 #define gotsig (G_misc.gotsig )
349 #define may_have_traps (G_misc.may_have_traps )
350 #define trap (G_misc.trap )
351 #define trap_ptr (G_misc.trap_ptr )
352 #define random_gen (G_misc.random_gen )
353 #define backgndpid (G_misc.backgndpid )
354 #define job_warning (G_misc.job_warning)
355 #define INIT_G_misc() do { \
356 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
364 /* ============ DEBUG */
366 static void trace_printf(const char *fmt, ...);
367 static void trace_vprintf(const char *fmt, va_list va);
368 # define TRACE(param) trace_printf param
369 # define TRACEV(param) trace_vprintf param
370 # define close(fd) do { \
372 if (close(dfd) < 0) \
373 bb_error_msg("bug on %d: closing %d(0x%x)", \
374 __LINE__, dfd, dfd); \
377 # define TRACE(param)
378 # define TRACEV(param)
382 /* ============ Utility functions */
383 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
385 static int isdigit_str9(const char *str)
387 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
388 while (--maxlen && isdigit(*str))
390 return (*str == '\0');
393 static const char *var_end(const char *var)
402 /* ============ Interrupts / exceptions */
404 static void exitshell(void) NORETURN;
407 * These macros allow the user to suspend the handling of interrupt signals
408 * over a period of time. This is similar to SIGHOLD or to sigblock, but
409 * much more efficient and portable. (But hacking the kernel is so much
410 * more fun than worrying about efficiency and portability. :-))
412 #define INT_OFF do { \
418 * Called to raise an exception. Since C doesn't include exceptions, we
419 * just do a longjmp to the exception handler. The type of exception is
420 * stored in the global variable "exception_type".
422 static void raise_exception(int) NORETURN;
424 raise_exception(int e)
427 if (exception_handler == NULL)
432 longjmp(exception_handler->loc, 1);
435 #define raise_exception(e) do { \
436 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
437 raise_exception(e); \
442 * Called from trap.c when a SIGINT is received. (If the user specifies
443 * that SIGINT is to be trapped or ignored using the trap builtin, then
444 * this routine is not called.) Suppressint is nonzero when interrupts
445 * are held using the INT_OFF macro. (The test for iflag is just
446 * defensive programming.)
448 static void raise_interrupt(void) NORETURN;
450 raise_interrupt(void)
455 /* Signal is not automatically unmasked after it is raised,
456 * do it ourself - unmask all signals */
457 sigprocmask_allsigs(SIG_UNBLOCK);
458 /* pending_sig = 0; - now done in signal_handler() */
461 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
462 if (!(rootshell && iflag)) {
463 /* Kill ourself with SIGINT */
464 signal(SIGINT, SIG_DFL);
469 raise_exception(ex_type);
473 #define raise_interrupt() do { \
474 TRACE(("raising interrupt on line %d\n", __LINE__)); \
479 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
483 if (--suppress_int == 0 && pending_int) {
487 #define INT_ON int_on()
488 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
496 #define FORCE_INT_ON force_int_on()
498 #define SAVE_INT(v) ((v) = suppress_int)
500 #define RESTORE_INT(v) do { \
502 suppress_int = (v); \
503 if (suppress_int == 0 && pending_int) \
508 /* ============ Stdout/stderr output */
511 outstr(const char *p, FILE *file)
519 flush_stdout_stderr(void)
527 outcslow(int c, FILE *dest)
535 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
537 out1fmt(const char *fmt, ...)
544 r = vprintf(fmt, ap);
550 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
552 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
559 ret = vsnprintf(outbuf, length, fmt, ap);
566 out1str(const char *p)
572 out2str(const char *p)
575 flush_stdout_stderr();
579 /* ============ Parser structures */
581 /* control characters in argument strings */
582 #define CTL_FIRST CTLESC
583 #define CTLESC ((unsigned char)'\201') /* escape next character */
584 #define CTLVAR ((unsigned char)'\202') /* variable defn */
585 #define CTLENDVAR ((unsigned char)'\203')
586 #define CTLBACKQ ((unsigned char)'\204')
587 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
588 /* CTLBACKQ | CTLQUOTE == '\205' */
589 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
590 #define CTLENDARI ((unsigned char)'\207')
591 #define CTLQUOTEMARK ((unsigned char)'\210')
592 #define CTL_LAST CTLQUOTEMARK
594 /* variable substitution byte (follows CTLVAR) */
595 #define VSTYPE 0x0f /* type of variable substitution */
596 #define VSNUL 0x10 /* colon--treat the empty string as unset */
597 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
599 /* values of VSTYPE field */
600 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
601 #define VSMINUS 0x2 /* ${var-text} */
602 #define VSPLUS 0x3 /* ${var+text} */
603 #define VSQUESTION 0x4 /* ${var?message} */
604 #define VSASSIGN 0x5 /* ${var=text} */
605 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
606 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
607 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
608 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
609 #define VSLENGTH 0xa /* ${#var} */
610 #if ENABLE_ASH_BASH_COMPAT
611 #define VSSUBSTR 0xc /* ${var:position:length} */
612 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
613 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
616 static const char dolatstr[] ALIGN1 = {
617 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
637 #if ENABLE_ASH_BASH_COMPAT
654 smallint type; /* Nxxxx */
657 union node *redirect;
662 smallint pipe_backgnd;
663 struct nodelist *cmdlist;
669 union node *redirect;
682 union node *elsepart;
709 struct nodelist *backquote;
712 /* nfile and ndup layout must match!
713 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
714 * that it is actually NTO2 (>&file), and change its type.
731 char *_unused_expfname;
750 struct nredir nredir;
751 struct nbinary nbinary;
755 struct nclist nclist;
764 * NODE_EOF is returned by parsecmd when it encounters an end of file.
765 * It must be distinct from NULL.
767 #define NODE_EOF ((union node *) -1L)
770 struct nodelist *next;
783 freefunc(struct funcnode *f)
785 if (f && --f->count < 0)
790 /* ============ Debugging output */
794 static FILE *tracefile;
797 trace_printf(const char *fmt, ...)
804 fprintf(tracefile, "%u ", (int) time(NULL));
806 fprintf(tracefile, "[%u] ", (int) getpid());
808 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
810 vfprintf(tracefile, fmt, va);
815 trace_vprintf(const char *fmt, va_list va)
820 fprintf(tracefile, "%u ", (int) time(NULL));
822 fprintf(tracefile, "[%u] ", (int) getpid());
824 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
825 vfprintf(tracefile, fmt, va);
829 trace_puts(const char *s)
837 trace_puts_quoted(char *s)
844 putc('"', tracefile);
845 for (p = s; *p; p++) {
846 switch ((unsigned char)*p) {
847 case '\n': c = 'n'; goto backslash;
848 case '\t': c = 't'; goto backslash;
849 case '\r': c = 'r'; goto backslash;
850 case '\"': c = '\"'; goto backslash;
851 case '\\': c = '\\'; goto backslash;
852 case CTLESC: c = 'e'; goto backslash;
853 case CTLVAR: c = 'v'; goto backslash;
854 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
855 case CTLBACKQ: c = 'q'; goto backslash;
856 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
858 putc('\\', tracefile);
862 if (*p >= ' ' && *p <= '~')
865 putc('\\', tracefile);
866 putc((*p >> 6) & 03, tracefile);
867 putc((*p >> 3) & 07, tracefile);
868 putc(*p & 07, tracefile);
873 putc('"', tracefile);
877 trace_puts_args(char **ap)
884 trace_puts_quoted(*ap);
886 putc('\n', tracefile);
889 putc(' ', tracefile);
904 /* leave open because libedit might be using it */
907 strcpy(s, "./trace");
909 if (!freopen(s, "a", tracefile)) {
910 fprintf(stderr, "Can't re-open %s\n", s);
915 tracefile = fopen(s, "a");
916 if (tracefile == NULL) {
917 fprintf(stderr, "Can't open %s\n", s);
923 flags = fcntl(fileno(tracefile), F_GETFL);
925 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
927 setlinebuf(tracefile);
928 fputs("\nTracing started.\n", tracefile);
932 indent(int amount, char *pfx, FILE *fp)
936 for (i = 0; i < amount; i++) {
937 if (pfx && i == amount - 1)
943 /* little circular references here... */
944 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
947 sharg(union node *arg, FILE *fp)
950 struct nodelist *bqlist;
951 unsigned char subtype;
953 if (arg->type != NARG) {
954 out1fmt("<node type %d>\n", arg->type);
957 bqlist = arg->narg.backquote;
958 for (p = arg->narg.text; *p; p++) {
959 switch ((unsigned char)*p) {
968 if (subtype == VSLENGTH)
979 switch (subtype & VSTYPE) {
1005 case VSTRIMRIGHTMAX:
1012 out1fmt("<subtype %d>", subtype);
1019 case CTLBACKQ|CTLQUOTE:
1022 shtree(bqlist->n, -1, NULL, fp);
1033 shcmd(union node *cmd, FILE *fp)
1041 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1047 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1051 switch (np->nfile.type) {
1052 case NTO: s = ">>"+1; dftfd = 1; break;
1053 case NCLOBBER: s = ">|"; dftfd = 1; break;
1054 case NAPPEND: s = ">>"; dftfd = 1; break;
1055 #if ENABLE_ASH_BASH_COMPAT
1058 case NTOFD: s = ">&"; dftfd = 1; break;
1059 case NFROM: s = "<"; break;
1060 case NFROMFD: s = "<&"; break;
1061 case NFROMTO: s = "<>"; break;
1062 default: s = "*error*"; break;
1064 if (np->nfile.fd != dftfd)
1065 fprintf(fp, "%d", np->nfile.fd);
1067 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1068 fprintf(fp, "%d", np->ndup.dupfd);
1070 sharg(np->nfile.fname, fp);
1077 shtree(union node *n, int ind, char *pfx, FILE *fp)
1079 struct nodelist *lp;
1085 indent(ind, pfx, fp);
1087 if (n == NODE_EOF) {
1102 shtree(n->nbinary.ch1, ind, NULL, fp);
1105 shtree(n->nbinary.ch2, ind, NULL, fp);
1113 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1114 shtree(lp->n, 0, NULL, fp);
1118 if (n->npipe.pipe_backgnd)
1124 fprintf(fp, "<node type %d>", n->type);
1132 showtree(union node *n)
1134 trace_puts("showtree called\n");
1135 shtree(n, 1, NULL, stderr);
1141 /* ============ Parser data */
1144 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1147 struct strlist *next;
1154 struct strpush *prev; /* preceding string on stack */
1156 int prev_left_in_line;
1157 #if ENABLE_ASH_ALIAS
1158 struct alias *ap; /* if push was associated with an alias */
1160 char *string; /* remember the string since it may change */
1164 struct parsefile *prev; /* preceding file on stack */
1165 int linno; /* current line */
1166 int pf_fd; /* file descriptor (or -1 if string) */
1167 int left_in_line; /* number of chars left in this line */
1168 int left_in_buffer; /* number of chars left in this buffer past the line */
1169 char *next_to_pgetc; /* next char in buffer */
1170 char *buf; /* input buffer */
1171 struct strpush *strpush; /* for pushing strings at this level */
1172 struct strpush basestrpush; /* so pushing one is fast */
1175 static struct parsefile basepf; /* top level input file */
1176 static struct parsefile *g_parsefile = &basepf; /* current input file */
1177 static int startlinno; /* line # where last token started */
1178 static char *commandname; /* currently executing command */
1179 static struct strlist *cmdenviron; /* environment for builtin command */
1180 static uint8_t exitstatus; /* exit status of last command */
1183 /* ============ Message printing */
1186 ash_vmsg(const char *msg, va_list ap)
1188 fprintf(stderr, "%s: ", arg0);
1190 if (strcmp(arg0, commandname))
1191 fprintf(stderr, "%s: ", commandname);
1192 if (!iflag || g_parsefile->pf_fd > 0)
1193 fprintf(stderr, "line %d: ", startlinno);
1195 vfprintf(stderr, msg, ap);
1196 outcslow('\n', stderr);
1200 * Exverror is called to raise the error exception. If the second argument
1201 * is not NULL then error prints an error message using printf style
1202 * formatting. It then raises the error exception.
1204 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1206 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1210 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1212 TRACE(("\") pid=%d\n", getpid()));
1214 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1219 flush_stdout_stderr();
1220 raise_exception(cond);
1224 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1226 ash_msg_and_raise_error(const char *msg, ...)
1231 ash_vmsg_and_raise(EXERROR, msg, ap);
1236 static void raise_error_syntax(const char *) NORETURN;
1238 raise_error_syntax(const char *msg)
1240 ash_msg_and_raise_error("syntax error: %s", msg);
1244 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1246 ash_msg_and_raise(int cond, const char *msg, ...)
1251 ash_vmsg_and_raise(cond, msg, ap);
1257 * error/warning routines for external builtins
1260 ash_msg(const char *fmt, ...)
1270 * Return a string describing an error. The returned string may be a
1271 * pointer to a static buffer that will be overwritten on the next call.
1272 * Action describes the operation that got the error.
1275 errmsg(int e, const char *em)
1277 if (e == ENOENT || e == ENOTDIR) {
1284 /* ============ Memory allocation */
1287 /* I consider these wrappers nearly useless:
1288 * ok, they return you to nearest exception handler, but
1289 * how much memory do you leak in the process, making
1290 * memory starvation worse?
1293 ckrealloc(void * p, size_t nbytes)
1295 p = realloc(p, nbytes);
1297 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1302 ckmalloc(size_t nbytes)
1304 return ckrealloc(NULL, nbytes);
1308 ckzalloc(size_t nbytes)
1310 return memset(ckmalloc(nbytes), 0, nbytes);
1314 ckstrdup(const char *s)
1316 char *p = strdup(s);
1318 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1322 /* Using bbox equivalents. They exit if out of memory */
1323 # define ckrealloc xrealloc
1324 # define ckmalloc xmalloc
1325 # define ckzalloc xzalloc
1326 # define ckstrdup xstrdup
1330 * It appears that grabstackstr() will barf with such alignments
1331 * because stalloc() will return a string allocated in a new stackblock.
1333 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1335 /* Most machines require the value returned from malloc to be aligned
1336 * in some way. The following macro will get this right
1337 * on many machines. */
1338 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1339 /* Minimum size of a block */
1340 MINSIZE = SHELL_ALIGN(504),
1343 struct stack_block {
1344 struct stack_block *prev;
1345 char space[MINSIZE];
1349 struct stack_block *stackp;
1352 struct stackmark *marknext;
1356 struct globals_memstack {
1357 struct stack_block *g_stackp; // = &stackbase;
1358 struct stackmark *markp;
1359 char *g_stacknxt; // = stackbase.space;
1360 char *sstrend; // = stackbase.space + MINSIZE;
1361 size_t g_stacknleft; // = MINSIZE;
1362 int herefd; // = -1;
1363 struct stack_block stackbase;
1365 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1366 #define G_memstack (*ash_ptr_to_globals_memstack)
1367 #define g_stackp (G_memstack.g_stackp )
1368 #define markp (G_memstack.markp )
1369 #define g_stacknxt (G_memstack.g_stacknxt )
1370 #define sstrend (G_memstack.sstrend )
1371 #define g_stacknleft (G_memstack.g_stacknleft)
1372 #define herefd (G_memstack.herefd )
1373 #define stackbase (G_memstack.stackbase )
1374 #define INIT_G_memstack() do { \
1375 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1377 g_stackp = &stackbase; \
1378 g_stacknxt = stackbase.space; \
1379 g_stacknleft = MINSIZE; \
1380 sstrend = stackbase.space + MINSIZE; \
1385 #define stackblock() ((void *)g_stacknxt)
1386 #define stackblocksize() g_stacknleft
1389 * Parse trees for commands are allocated in lifo order, so we use a stack
1390 * to make this more efficient, and also to avoid all sorts of exception
1391 * handling code to handle interrupts in the middle of a parse.
1393 * The size 504 was chosen because the Ultrix malloc handles that size
1397 stalloc(size_t nbytes)
1402 aligned = SHELL_ALIGN(nbytes);
1403 if (aligned > g_stacknleft) {
1406 struct stack_block *sp;
1408 blocksize = aligned;
1409 if (blocksize < MINSIZE)
1410 blocksize = MINSIZE;
1411 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1412 if (len < blocksize)
1413 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1416 sp->prev = g_stackp;
1417 g_stacknxt = sp->space;
1418 g_stacknleft = blocksize;
1419 sstrend = g_stacknxt + blocksize;
1424 g_stacknxt += aligned;
1425 g_stacknleft -= aligned;
1430 stzalloc(size_t nbytes)
1432 return memset(stalloc(nbytes), 0, nbytes);
1439 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1440 write(STDERR_FILENO, "stunalloc\n", 10);
1444 g_stacknleft += g_stacknxt - (char *)p;
1449 * Like strdup but works with the ash stack.
1452 ststrdup(const char *p)
1454 size_t len = strlen(p) + 1;
1455 return memcpy(stalloc(len), p, len);
1459 setstackmark(struct stackmark *mark)
1461 mark->stackp = g_stackp;
1462 mark->stacknxt = g_stacknxt;
1463 mark->stacknleft = g_stacknleft;
1464 mark->marknext = markp;
1469 popstackmark(struct stackmark *mark)
1471 struct stack_block *sp;
1477 markp = mark->marknext;
1478 while (g_stackp != mark->stackp) {
1480 g_stackp = sp->prev;
1483 g_stacknxt = mark->stacknxt;
1484 g_stacknleft = mark->stacknleft;
1485 sstrend = mark->stacknxt + mark->stacknleft;
1490 * When the parser reads in a string, it wants to stick the string on the
1491 * stack and only adjust the stack pointer when it knows how big the
1492 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1493 * of space on top of the stack and stackblocklen returns the length of
1494 * this block. Growstackblock will grow this space by at least one byte,
1495 * possibly moving it (like realloc). Grabstackblock actually allocates the
1496 * part of the block that has been used.
1499 growstackblock(void)
1503 newlen = g_stacknleft * 2;
1504 if (newlen < g_stacknleft)
1505 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1509 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1510 struct stack_block *oldstackp;
1511 struct stackmark *xmark;
1512 struct stack_block *sp;
1513 struct stack_block *prevstackp;
1517 oldstackp = g_stackp;
1519 prevstackp = sp->prev;
1520 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1521 sp = ckrealloc(sp, grosslen);
1522 sp->prev = prevstackp;
1524 g_stacknxt = sp->space;
1525 g_stacknleft = newlen;
1526 sstrend = sp->space + newlen;
1529 * Stack marks pointing to the start of the old block
1530 * must be relocated to point to the new block
1533 while (xmark != NULL && xmark->stackp == oldstackp) {
1534 xmark->stackp = g_stackp;
1535 xmark->stacknxt = g_stacknxt;
1536 xmark->stacknleft = g_stacknleft;
1537 xmark = xmark->marknext;
1541 char *oldspace = g_stacknxt;
1542 size_t oldlen = g_stacknleft;
1543 char *p = stalloc(newlen);
1545 /* free the space we just allocated */
1546 g_stacknxt = memcpy(p, oldspace, oldlen);
1547 g_stacknleft += newlen;
1552 grabstackblock(size_t len)
1554 len = SHELL_ALIGN(len);
1556 g_stacknleft -= len;
1560 * The following routines are somewhat easier to use than the above.
1561 * The user declares a variable of type STACKSTR, which may be declared
1562 * to be a register. The macro STARTSTACKSTR initializes things. Then
1563 * the user uses the macro STPUTC to add characters to the string. In
1564 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1565 * grown as necessary. When the user is done, she can just leave the
1566 * string there and refer to it using stackblock(). Or she can allocate
1567 * the space for it using grabstackstr(). If it is necessary to allow
1568 * someone else to use the stack temporarily and then continue to grow
1569 * the string, the user should use grabstack to allocate the space, and
1570 * then call ungrabstr(p) to return to the previous mode of operation.
1572 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1573 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1574 * is space for at least one character.
1579 size_t len = stackblocksize();
1580 if (herefd >= 0 && len >= 1024) {
1581 full_write(herefd, stackblock(), len);
1582 return stackblock();
1585 return (char *)stackblock() + len;
1589 * Called from CHECKSTRSPACE.
1592 makestrspace(size_t newlen, char *p)
1594 size_t len = p - g_stacknxt;
1595 size_t size = stackblocksize();
1600 size = stackblocksize();
1602 if (nleft >= newlen)
1606 return (char *)stackblock() + len;
1610 stack_nputstr(const char *s, size_t n, char *p)
1612 p = makestrspace(n, p);
1613 p = (char *)memcpy(p, s, n) + n;
1618 stack_putstr(const char *s, char *p)
1620 return stack_nputstr(s, strlen(s), p);
1624 _STPUTC(int c, char *p)
1632 #define STARTSTACKSTR(p) ((p) = stackblock())
1633 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1634 #define CHECKSTRSPACE(n, p) do { \
1637 size_t m = sstrend - q; \
1639 (p) = makestrspace(l, q); \
1641 #define USTPUTC(c, p) (*(p)++ = (c))
1642 #define STACKSTRNUL(p) do { \
1643 if ((p) == sstrend) \
1644 (p) = growstackstr(); \
1647 #define STUNPUTC(p) (--(p))
1648 #define STTOPC(p) ((p)[-1])
1649 #define STADJUST(amount, p) ((p) += (amount))
1651 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1652 #define ungrabstackstr(s, p) stunalloc(s)
1653 #define stackstrend() ((void *)sstrend)
1656 /* ============ String helpers */
1659 * prefix -- see if pfx is a prefix of string.
1662 prefix(const char *string, const char *pfx)
1665 if (*pfx++ != *string++)
1668 return (char *) string;
1672 * Check for a valid number. This should be elsewhere.
1675 is_number(const char *p)
1680 } while (*++p != '\0');
1685 * Convert a string of digits to an integer, printing an error message on
1689 number(const char *s)
1692 ash_msg_and_raise_error(msg_illnum, s);
1697 * Produce a possibly single quoted string suitable as input to the shell.
1698 * The return string is allocated on the stack.
1701 single_quote(const char *s)
1711 len = strchrnul(s, '\'') - s;
1713 q = p = makestrspace(len + 3, p);
1716 q = (char *)memcpy(q, s, len) + len;
1725 do len++; while (*++s == '\'');
1727 q = p = makestrspace(len + 3, p);
1730 q = (char *)memcpy(q, s - len, len) + len;
1738 return stackblock();
1742 /* ============ nextopt */
1744 static char **argptr; /* argument list for builtin commands */
1745 static char *optionarg; /* set by nextopt (like getopt) */
1746 static char *optptr; /* used by nextopt */
1749 * XXX - should get rid of. Have all builtins use getopt(3).
1750 * The library getopt must have the BSD extension static variable
1751 * "optreset", otherwise it can't be used within the shell safely.
1753 * Standard option processing (a la getopt) for builtin routines.
1754 * The only argument that is passed to nextopt is the option string;
1755 * the other arguments are unnecessary. It returns the character,
1756 * or '\0' on end of input.
1759 nextopt(const char *optstring)
1766 if (p == NULL || *p == '\0') {
1767 /* We ate entire "-param", take next one */
1773 if (*++p == '\0') /* just "-" ? */
1776 if (LONE_DASH(p)) /* "--" ? */
1778 /* p => next "-param" */
1780 /* p => some option char in the middle of a "-param" */
1782 for (q = optstring; *q != c;) {
1784 ash_msg_and_raise_error("illegal option -%c", c);
1792 ash_msg_and_raise_error("no arg for -%c option", c);
1802 /* ============ Shell variables */
1805 * The parsefile structure pointed to by the global variable parsefile
1806 * contains information about the current file being read.
1809 int nparam; /* # of positional parameters (without $0) */
1810 #if ENABLE_ASH_GETOPTS
1811 int optind; /* next parameter to be processed by getopts */
1812 int optoff; /* used by getopts */
1814 unsigned char malloced; /* if parameter list dynamically allocated */
1815 char **p; /* parameter list */
1819 * Free the list of positional parameters.
1822 freeparam(volatile struct shparam *param)
1824 if (param->malloced) {
1826 ap = ap1 = param->p;
1833 #if ENABLE_ASH_GETOPTS
1834 static void FAST_FUNC getoptsreset(const char *value);
1838 struct var *next; /* next entry in hash list */
1839 int flags; /* flags are defined above */
1840 const char *var_text; /* name=value */
1841 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1842 /* the variable gets set/unset */
1846 struct localvar *next; /* next local variable in list */
1847 struct var *vp; /* the variable that was made local */
1848 int flags; /* saved flags */
1849 const char *text; /* saved text */
1853 #define VEXPORT 0x01 /* variable is exported */
1854 #define VREADONLY 0x02 /* variable cannot be modified */
1855 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1856 #define VTEXTFIXED 0x08 /* text is statically allocated */
1857 #define VSTACK 0x10 /* text is allocated on the stack */
1858 #define VUNSET 0x20 /* the variable is not set */
1859 #define VNOFUNC 0x40 /* don't call the callback function */
1860 #define VNOSET 0x80 /* do not set variable - just readonly test */
1861 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1862 #if ENABLE_ASH_RANDOM_SUPPORT
1863 # define VDYNAMIC 0x200 /* dynamic variable */
1869 /* Need to be before varinit_data[] */
1870 #if ENABLE_LOCALE_SUPPORT
1871 static void FAST_FUNC
1872 change_lc_all(const char *value)
1874 if (value && *value != '\0')
1875 setlocale(LC_ALL, value);
1877 static void FAST_FUNC
1878 change_lc_ctype(const char *value)
1880 if (value && *value != '\0')
1881 setlocale(LC_CTYPE, value);
1885 static void chkmail(void);
1886 static void changemail(const char *var_value) FAST_FUNC;
1888 # define chkmail() ((void)0)
1890 static void changepath(const char *) FAST_FUNC;
1891 #if ENABLE_ASH_RANDOM_SUPPORT
1892 static void change_random(const char *) FAST_FUNC;
1895 static const struct {
1897 const char *var_text;
1898 void (*var_func)(const char *) FAST_FUNC;
1899 } varinit_data[] = {
1900 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1902 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1903 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1905 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1906 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1907 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1908 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1909 #if ENABLE_ASH_GETOPTS
1910 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1912 #if ENABLE_ASH_RANDOM_SUPPORT
1913 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1915 #if ENABLE_LOCALE_SUPPORT
1916 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1917 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1919 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1920 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1926 struct globals_var {
1927 struct shparam shellparam; /* $@ current positional parameters */
1928 struct redirtab *redirlist;
1930 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1931 struct var *vartab[VTABSIZE];
1932 struct var varinit[ARRAY_SIZE(varinit_data)];
1934 extern struct globals_var *const ash_ptr_to_globals_var;
1935 #define G_var (*ash_ptr_to_globals_var)
1936 #define shellparam (G_var.shellparam )
1937 //#define redirlist (G_var.redirlist )
1938 #define g_nullredirs (G_var.g_nullredirs )
1939 #define preverrout_fd (G_var.preverrout_fd)
1940 #define vartab (G_var.vartab )
1941 #define varinit (G_var.varinit )
1942 #define INIT_G_var() do { \
1944 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1946 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1947 varinit[i].flags = varinit_data[i].flags; \
1948 varinit[i].var_text = varinit_data[i].var_text; \
1949 varinit[i].var_func = varinit_data[i].var_func; \
1953 #define vifs varinit[0]
1955 # define vmail (&vifs)[1]
1956 # define vmpath (&vmail)[1]
1957 # define vpath (&vmpath)[1]
1959 # define vpath (&vifs)[1]
1961 #define vps1 (&vpath)[1]
1962 #define vps2 (&vps1)[1]
1963 #define vps4 (&vps2)[1]
1964 #if ENABLE_ASH_GETOPTS
1965 # define voptind (&vps4)[1]
1966 # if ENABLE_ASH_RANDOM_SUPPORT
1967 # define vrandom (&voptind)[1]
1970 # if ENABLE_ASH_RANDOM_SUPPORT
1971 # define vrandom (&vps4)[1]
1976 * The following macros access the values of the above variables.
1977 * They have to skip over the name. They return the null string
1978 * for unset variables.
1980 #define ifsval() (vifs.var_text + 4)
1981 #define ifsset() ((vifs.flags & VUNSET) == 0)
1983 # define mailval() (vmail.var_text + 5)
1984 # define mpathval() (vmpath.var_text + 9)
1985 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1987 #define pathval() (vpath.var_text + 5)
1988 #define ps1val() (vps1.var_text + 4)
1989 #define ps2val() (vps2.var_text + 4)
1990 #define ps4val() (vps4.var_text + 4)
1991 #if ENABLE_ASH_GETOPTS
1992 # define optindval() (voptind.var_text + 7)
1995 #if ENABLE_ASH_GETOPTS
1996 static void FAST_FUNC
1997 getoptsreset(const char *value)
1999 shellparam.optind = number(value);
2000 shellparam.optoff = -1;
2004 /* math.h has these, otherwise define our private copies */
2005 #if !ENABLE_SH_MATH_SUPPORT
2006 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2007 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2009 * Return the pointer to the first char which is not part of a legal variable name
2010 * (a letter or underscore followed by letters, underscores, and digits).
2013 endofname(const char *name)
2015 if (!is_name(*name))
2018 if (!is_in_name(*name))
2026 * Compares two strings up to the first = or '\0'. The first
2027 * string must be terminated by '='; the second may be terminated by
2028 * either '=' or '\0'.
2031 varcmp(const char *p, const char *q)
2035 while ((c = *p) == (d = *q)) {
2050 * Find the appropriate entry in the hash table from the name.
2052 static struct var **
2053 hashvar(const char *p)
2057 hashval = ((unsigned char) *p) << 4;
2058 while (*p && *p != '=')
2059 hashval += (unsigned char) *p++;
2060 return &vartab[hashval % VTABSIZE];
2064 vpcmp(const void *a, const void *b)
2066 return varcmp(*(const char **)a, *(const char **)b);
2070 * This routine initializes the builtin variables.
2080 * PS1 depends on uid
2082 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2083 vps1.var_text = "PS1=\\w \\$ ";
2086 vps1.var_text = "PS1=# ";
2089 end = vp + ARRAY_SIZE(varinit);
2091 vpp = hashvar(vp->var_text);
2094 } while (++vp < end);
2097 static struct var **
2098 findvar(struct var **vpp, const char *name)
2100 for (; *vpp; vpp = &(*vpp)->next) {
2101 if (varcmp((*vpp)->var_text, name) == 0) {
2109 * Find the value of a variable. Returns NULL if not set.
2111 static const char* FAST_FUNC
2112 lookupvar(const char *name)
2116 v = *findvar(hashvar(name), name);
2118 #if ENABLE_ASH_RANDOM_SUPPORT
2120 * Dynamic variables are implemented roughly the same way they are
2121 * in bash. Namely, they're "special" so long as they aren't unset.
2122 * As soon as they're unset, they're no longer dynamic, and dynamic
2123 * lookup will no longer happen at that point. -- PFM.
2125 if (v->flags & VDYNAMIC)
2128 if (!(v->flags & VUNSET))
2129 return var_end(v->var_text);
2135 * Search the environment of a builtin command.
2138 bltinlookup(const char *name)
2142 for (sp = cmdenviron; sp; sp = sp->next) {
2143 if (varcmp(sp->text, name) == 0)
2144 return var_end(sp->text);
2146 return lookupvar(name);
2150 * Same as setvar except that the variable and value are passed in
2151 * the first argument as name=value. Since the first argument will
2152 * be actually stored in the table, it should not be a string that
2154 * Called with interrupts off.
2157 setvareq(char *s, int flags)
2159 struct var *vp, **vpp;
2162 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2163 vp = *findvar(vpp, s);
2165 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2168 if (flags & VNOSAVE)
2171 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2177 if (vp->var_func && !(flags & VNOFUNC))
2178 vp->var_func(var_end(s));
2180 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2181 free((char*)vp->var_text);
2183 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2185 /* variable s is not found */
2188 vp = ckzalloc(sizeof(*vp));
2190 /*vp->func = NULL; - ckzalloc did it */
2193 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2200 * Set the value of a variable. The flags argument is ored with the
2201 * flags of the variable. If val is NULL, the variable is unset.
2204 setvar(const char *name, const char *val, int flags)
2212 q = endofname(name);
2213 p = strchrnul(q, '=');
2215 if (!namelen || p != q)
2216 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2221 vallen = strlen(val);
2225 nameeq = ckmalloc(namelen + vallen + 2);
2226 p = memcpy(nameeq, name, namelen) + namelen;
2229 p = memcpy(p, val, vallen) + vallen;
2232 setvareq(nameeq, flags | VNOSAVE);
2236 static void FAST_FUNC
2237 setvar2(const char *name, const char *val)
2239 setvar(name, val, 0);
2242 #if ENABLE_ASH_GETOPTS
2244 * Safe version of setvar, returns 1 on success 0 on failure.
2247 setvarsafe(const char *name, const char *val, int flags)
2250 volatile int saveint;
2251 struct jmploc *volatile savehandler = exception_handler;
2252 struct jmploc jmploc;
2255 if (setjmp(jmploc.loc))
2258 exception_handler = &jmploc;
2259 setvar(name, val, flags);
2262 exception_handler = savehandler;
2263 RESTORE_INT(saveint);
2269 * Unset the specified variable.
2272 unsetvar(const char *s)
2278 vpp = findvar(hashvar(s), s);
2282 int flags = vp->flags;
2285 if (flags & VREADONLY)
2287 #if ENABLE_ASH_RANDOM_SUPPORT
2288 vp->flags &= ~VDYNAMIC;
2292 if ((flags & VSTRFIXED) == 0) {
2294 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2295 free((char*)vp->var_text);
2301 vp->flags &= ~VEXPORT;
2311 * Process a linked list of variable assignments.
2314 listsetvar(struct strlist *list_set_var, int flags)
2316 struct strlist *lp = list_set_var;
2322 setvareq(lp->text, flags);
2329 * Generate a list of variables satisfying the given conditions.
2332 listvars(int on, int off, char ***end)
2343 for (vp = *vpp; vp; vp = vp->next) {
2344 if ((vp->flags & mask) == on) {
2345 if (ep == stackstrend())
2346 ep = growstackstr();
2347 *ep++ = (char*)vp->var_text;
2350 } while (++vpp < vartab + VTABSIZE);
2351 if (ep == stackstrend())
2352 ep = growstackstr();
2356 return grabstackstr(ep);
2360 /* ============ Path search helper
2362 * The variable path (passed by reference) should be set to the start
2363 * of the path before the first call; path_advance will update
2364 * this value as it proceeds. Successive calls to path_advance will return
2365 * the possible path expansions in sequence. If an option (indicated by
2366 * a percent sign) appears in the path entry then the global variable
2367 * pathopt will be set to point to it; otherwise pathopt will be set to
2370 static const char *pathopt; /* set by path_advance */
2373 path_advance(const char **path, const char *name)
2383 for (p = start; *p && *p != ':' && *p != '%'; p++)
2385 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2386 while (stackblocksize() < len)
2390 memcpy(q, start, p - start);
2398 while (*p && *p != ':')
2405 return stalloc(len);
2409 /* ============ Prompt */
2411 static smallint doprompt; /* if set, prompt the user */
2412 static smallint needprompt; /* true if interactive and at start of line */
2414 #if ENABLE_FEATURE_EDITING
2415 static line_input_t *line_input_state;
2416 static const char *cmdedit_prompt;
2418 putprompt(const char *s)
2420 if (ENABLE_ASH_EXPAND_PRMT) {
2421 free((char*)cmdedit_prompt);
2422 cmdedit_prompt = ckstrdup(s);
2429 putprompt(const char *s)
2435 #if ENABLE_ASH_EXPAND_PRMT
2436 /* expandstr() needs parsing machinery, so it is far away ahead... */
2437 static const char *expandstr(const char *ps);
2439 #define expandstr(s) s
2443 setprompt_if(smallint do_set, int whichprompt)
2446 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2453 switch (whichprompt) {
2463 #if ENABLE_ASH_EXPAND_PRMT
2464 setstackmark(&smark);
2465 stalloc(stackblocksize());
2467 putprompt(expandstr(prompt));
2468 #if ENABLE_ASH_EXPAND_PRMT
2469 popstackmark(&smark);
2474 /* ============ The cd and pwd commands */
2476 #define CD_PHYSICAL 1
2486 while ((i = nextopt("LP")) != '\0') {
2488 flags ^= CD_PHYSICAL;
2497 * Update curdir (the name of the current directory) in response to a
2501 updatepwd(const char *dir)
2508 cdcomppath = ststrdup(dir);
2511 if (curdir == nullstr)
2513 new = stack_putstr(curdir, new);
2515 new = makestrspace(strlen(dir) + 2, new);
2516 lim = (char *)stackblock() + 1;
2520 if (new > lim && *lim == '/')
2525 if (dir[1] == '/' && dir[2] != '/') {
2531 p = strtok(cdcomppath, "/");
2535 if (p[1] == '.' && p[2] == '\0') {
2547 new = stack_putstr(p, new);
2555 return stackblock();
2559 * Find out what the current directory is. If we already know the current
2560 * directory, this routine returns immediately.
2565 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2566 return dir ? dir : nullstr;
2570 setpwd(const char *val, int setold)
2574 oldcur = dir = curdir;
2577 setvar("OLDPWD", oldcur, VEXPORT);
2580 if (physdir != nullstr) {
2581 if (physdir != oldcur)
2585 if (oldcur == val || !val) {
2591 dir = ckstrdup(val);
2592 if (oldcur != dir && oldcur != nullstr) {
2597 setvar("PWD", dir, VEXPORT);
2600 static void hashcd(void);
2603 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2604 * know that the current directory has changed.
2607 docd(const char *dest, int flags)
2609 const char *dir = NULL;
2612 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2615 if (!(flags & CD_PHYSICAL)) {
2616 dir = updatepwd(dest);
2630 static int FAST_FUNC
2631 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2643 dest = bltinlookup("HOME");
2644 else if (LONE_DASH(dest)) {
2645 dest = bltinlookup("OLDPWD");
2667 path = bltinlookup("CDPATH");
2676 p = path_advance(&path, dest);
2677 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2681 if (!docd(p, flags))
2686 ash_msg_and_raise_error("can't cd to %s", dest);
2689 if (flags & CD_PRINT)
2690 out1fmt("%s\n", curdir);
2694 static int FAST_FUNC
2695 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2698 const char *dir = curdir;
2702 if (physdir == nullstr)
2706 out1fmt("%s\n", dir);
2711 /* ============ ... */
2714 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2716 /* Syntax classes */
2717 #define CWORD 0 /* character is nothing special */
2718 #define CNL 1 /* newline character */
2719 #define CBACK 2 /* a backslash character */
2720 #define CSQUOTE 3 /* single quote */
2721 #define CDQUOTE 4 /* double quote */
2722 #define CENDQUOTE 5 /* a terminating quote */
2723 #define CBQUOTE 6 /* backwards single quote */
2724 #define CVAR 7 /* a dollar sign */
2725 #define CENDVAR 8 /* a '}' character */
2726 #define CLP 9 /* a left paren in arithmetic */
2727 #define CRP 10 /* a right paren in arithmetic */
2728 #define CENDFILE 11 /* end of file */
2729 #define CCTL 12 /* like CWORD, except it must be escaped */
2730 #define CSPCL 13 /* these terminate a word */
2731 #define CIGN 14 /* character should be ignored */
2734 #if ENABLE_ASH_ALIAS
2738 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2740 #if ENABLE_SH_MATH_SUPPORT
2741 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2743 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2745 static const uint16_t S_I_T[] = {
2746 #if ENABLE_ASH_ALIAS
2747 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2749 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2750 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2751 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2752 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2753 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2754 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2755 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2756 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2757 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2758 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2759 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2760 #if !USE_SIT_FUNCTION
2761 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2762 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2763 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2767 /* Constants below must match table above */
2769 #if ENABLE_ASH_ALIAS
2770 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2772 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2773 CNL_CNL_CNL_CNL , /* 2 */
2774 CWORD_CCTL_CCTL_CWORD , /* 3 */
2775 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2776 CVAR_CVAR_CWORD_CVAR , /* 5 */
2777 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2778 CSPCL_CWORD_CWORD_CLP , /* 7 */
2779 CSPCL_CWORD_CWORD_CRP , /* 8 */
2780 CBACK_CBACK_CCTL_CBACK , /* 9 */
2781 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2782 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2783 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2784 CWORD_CWORD_CWORD_CWORD , /* 13 */
2785 CCTL_CCTL_CCTL_CCTL , /* 14 */
2788 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2789 * caller must ensure proper cast on it if c is *char_ptr!
2791 /* Values for syntax param */
2792 #define BASESYNTAX 0 /* not in quotes */
2793 #define DQSYNTAX 1 /* in double quotes */
2794 #define SQSYNTAX 2 /* in single quotes */
2795 #define ARISYNTAX 3 /* in arithmetic */
2796 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2798 #if USE_SIT_FUNCTION
2801 SIT(int c, int syntax)
2803 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2804 # if ENABLE_ASH_ALIAS
2805 static const uint8_t syntax_index_table[] ALIGN1 = {
2806 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2807 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2808 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2812 static const uint8_t syntax_index_table[] ALIGN1 = {
2813 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2814 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2815 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2824 # if ENABLE_ASH_ALIAS
2830 /* Cast is purely for paranoia here,
2831 * just in case someone passed signed char to us */
2832 if ((unsigned char)c >= CTL_FIRST
2833 && (unsigned char)c <= CTL_LAST
2837 s = strchrnul(spec_symbls, c);
2840 indx = syntax_index_table[s - spec_symbls];
2842 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2845 #else /* !USE_SIT_FUNCTION */
2847 static const uint8_t syntax_index_table[] = {
2848 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2849 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2859 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2860 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2882 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2883 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2884 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2886 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2888 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2889 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2890 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2891 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2892 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2894 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2895 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2896 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2897 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2910 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2911 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2912 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2941 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2942 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2943 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2946 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2974 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2975 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2976 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2977 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2979 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2980 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2981 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2982 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2983 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2984 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2985 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2986 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3105 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3106 # if ENABLE_ASH_ALIAS
3107 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3111 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3113 #endif /* !USE_SIT_FUNCTION */
3116 /* ============ Alias handling */
3118 #if ENABLE_ASH_ALIAS
3120 #define ALIASINUSE 1
3131 static struct alias **atab; // [ATABSIZE];
3132 #define INIT_G_alias() do { \
3133 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3137 static struct alias **
3138 __lookupalias(const char *name) {
3139 unsigned int hashval;
3146 ch = (unsigned char)*p;
3150 ch = (unsigned char)*++p;
3152 app = &atab[hashval % ATABSIZE];
3154 for (; *app; app = &(*app)->next) {
3155 if (strcmp(name, (*app)->name) == 0) {
3163 static struct alias *
3164 lookupalias(const char *name, int check)
3166 struct alias *ap = *__lookupalias(name);
3168 if (check && ap && (ap->flag & ALIASINUSE))
3173 static struct alias *
3174 freealias(struct alias *ap)
3178 if (ap->flag & ALIASINUSE) {
3179 ap->flag |= ALIASDEAD;
3191 setalias(const char *name, const char *val)
3193 struct alias *ap, **app;
3195 app = __lookupalias(name);
3199 if (!(ap->flag & ALIASINUSE)) {
3202 ap->val = ckstrdup(val);
3203 ap->flag &= ~ALIASDEAD;
3206 ap = ckzalloc(sizeof(struct alias));
3207 ap->name = ckstrdup(name);
3208 ap->val = ckstrdup(val);
3209 /*ap->flag = 0; - ckzalloc did it */
3210 /*ap->next = NULL;*/
3217 unalias(const char *name)
3221 app = __lookupalias(name);
3225 *app = freealias(*app);
3236 struct alias *ap, **app;
3240 for (i = 0; i < ATABSIZE; i++) {
3242 for (ap = *app; ap; ap = *app) {
3243 *app = freealias(*app);
3253 printalias(const struct alias *ap)
3255 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3259 * TODO - sort output
3261 static int FAST_FUNC
3262 aliascmd(int argc UNUSED_PARAM, char **argv)
3271 for (i = 0; i < ATABSIZE; i++) {
3272 for (ap = atab[i]; ap; ap = ap->next) {
3278 while ((n = *++argv) != NULL) {
3279 v = strchr(n+1, '=');
3280 if (v == NULL) { /* n+1: funny ksh stuff */
3281 ap = *__lookupalias(n);
3283 fprintf(stderr, "%s: %s not found\n", "alias", n);
3296 static int FAST_FUNC
3297 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3301 while ((i = nextopt("a")) != '\0') {
3307 for (i = 0; *argptr; argptr++) {
3308 if (unalias(*argptr)) {
3309 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3317 #endif /* ASH_ALIAS */
3320 /* ============ jobs.c */
3322 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3325 #define FORK_NOJOB 2
3327 /* mode flags for showjob(s) */
3328 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3329 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3330 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3333 * A job structure contains information about a job. A job is either a
3334 * single process or a set of processes contained in a pipeline. In the
3335 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3339 pid_t ps_pid; /* process id */
3340 int ps_status; /* last process status from wait() */
3341 char *ps_cmd; /* text of command being run */
3345 struct procstat ps0; /* status of process */
3346 struct procstat *ps; /* status or processes when more than one */
3348 int stopstatus; /* status of a stopped job */
3351 nprocs: 16, /* number of processes */
3353 #define JOBRUNNING 0 /* at least one proc running */
3354 #define JOBSTOPPED 1 /* all procs are stopped */
3355 #define JOBDONE 2 /* all procs are completed */
3357 sigint: 1, /* job was killed by SIGINT */
3358 jobctl: 1, /* job running under job control */
3360 waited: 1, /* true if this entry has been waited for */
3361 used: 1, /* true if this entry is in used */
3362 changed: 1; /* true if status has changed */
3363 struct job *prev_job; /* previous job */
3366 static struct job *makejob(/*union node *,*/ int);
3367 static int forkshell(struct job *, union node *, int);
3368 static int waitforjob(struct job *);
3371 enum { doing_jobctl = 0 };
3372 #define setjobctl(on) do {} while (0)
3374 static smallint doing_jobctl; //references:8
3375 static void setjobctl(int);
3382 ignoresig(int signo)
3384 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3385 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3386 /* No, need to do it */
3387 signal(signo, SIG_IGN);
3389 sigmode[signo - 1] = S_HARD_IGN;
3393 * Only one usage site - in setsignal()
3396 signal_handler(int signo)
3398 gotsig[signo - 1] = 1;
3400 if (signo == SIGINT && !trap[SIGINT]) {
3401 if (!suppress_int) {
3403 raise_interrupt(); /* does not return */
3407 pending_sig = signo;
3412 * Set the signal handler for the specified signal. The routine figures
3413 * out what it should be set to.
3416 setsignal(int signo)
3419 char cur_act, new_act;
3420 struct sigaction act;
3424 if (t != NULL) { /* trap for this sig is set */
3426 if (t[0] == '\0') /* trap is "": ignore this sig */
3430 if (rootshell && new_act == S_DFL) {
3433 if (iflag || minusc || sflag == 0)
3442 * "In all cases, bash ignores SIGQUIT. Non-builtin
3443 * commands run by bash have signal handlers
3444 * set to the values inherited by the shell
3445 * from its parent". */
3461 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3462 //whereas we have to restore it to what shell got on entry
3463 //from the parent. See comment above
3465 t = &sigmode[signo - 1];
3468 /* current setting is not yet known */
3469 if (sigaction(signo, NULL, &act)) {
3470 /* pretend it worked; maybe we should give a warning,
3471 * but other shells don't. We don't alter sigmode,
3472 * so we retry every time.
3473 * btw, in Linux it never fails. --vda */
3476 if (act.sa_handler == SIG_IGN) {
3477 cur_act = S_HARD_IGN;
3479 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3481 cur_act = S_IGN; /* don't hard ignore these */
3485 if (cur_act == S_HARD_IGN || cur_act == new_act)
3488 act.sa_handler = SIG_DFL;
3491 act.sa_handler = signal_handler;
3492 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3493 sigfillset(&act.sa_mask); /* ditto */
3496 act.sa_handler = SIG_IGN;
3499 sigaction_set(signo, &act);
3504 /* mode flags for set_curjob */
3505 #define CUR_DELETE 2
3506 #define CUR_RUNNING 1
3507 #define CUR_STOPPED 0
3509 /* mode flags for dowait */
3510 #define DOWAIT_NONBLOCK WNOHANG
3511 #define DOWAIT_BLOCK 0
3514 /* pgrp of shell on invocation */
3515 static int initialpgrp; //references:2
3516 static int ttyfd = -1; //5
3519 static struct job *jobtab; //5
3521 static unsigned njobs; //4
3523 static struct job *curjob; //lots
3524 /* number of presumed living untracked jobs */
3525 static int jobless; //4
3528 set_curjob(struct job *jp, unsigned mode)
3531 struct job **jpp, **curp;
3533 /* first remove from list */
3534 jpp = curp = &curjob;
3539 jpp = &jp1->prev_job;
3541 *jpp = jp1->prev_job;
3543 /* Then re-insert in correct position */
3551 /* job being deleted */
3554 /* newly created job or backgrounded job,
3555 put after all stopped jobs. */
3559 if (!jp1 || jp1->state != JOBSTOPPED)
3562 jpp = &jp1->prev_job;
3568 /* newly stopped job - becomes curjob */
3569 jp->prev_job = *jpp;
3577 jobno(const struct job *jp)
3579 return jp - jobtab + 1;
3584 * Convert a job name to a job structure.
3587 #define getjob(name, getctl) getjob(name)
3590 getjob(const char *name, int getctl)
3594 const char *err_msg = "%s: no such job";
3598 char *(*match)(const char *, const char *);
3613 if (c == '+' || c == '%') {
3615 err_msg = "No current job";
3621 err_msg = "No previous job";
3632 jp = jobtab + num - 1;
3647 if (match(jp->ps[0].ps_cmd, p)) {
3651 err_msg = "%s: ambiguous";
3661 err_msg = "job %s not created under job control";
3662 if (getctl && jp->jobctl == 0)
3667 ash_msg_and_raise_error(err_msg, name);
3671 * Mark a job structure as unused.
3674 freejob(struct job *jp)
3676 struct procstat *ps;
3680 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3681 if (ps->ps_cmd != nullstr)
3684 if (jp->ps != &jp->ps0)
3687 set_curjob(jp, CUR_DELETE);
3693 xtcsetpgrp(int fd, pid_t pgrp)
3695 if (tcsetpgrp(fd, pgrp))
3696 ash_msg_and_raise_error("can't set tty process group (%m)");
3700 * Turn job control on and off.
3702 * Note: This code assumes that the third arg to ioctl is a character
3703 * pointer, which is true on Berkeley systems but not System V. Since
3704 * System V doesn't have job control yet, this isn't a problem now.
3706 * Called with interrupts off.
3714 if (on == doing_jobctl || rootshell == 0)
3718 ofd = fd = open(_PATH_TTY, O_RDWR);
3720 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3721 * That sometimes helps to acquire controlling tty.
3722 * Obviously, a workaround for bugs when someone
3723 * failed to provide a controlling tty to bash! :) */
3729 fd = fcntl(fd, F_DUPFD, 10);
3734 /* fd is a tty at this point */
3735 close_on_exec_on(fd);
3736 while (1) { /* while we are in the background */
3737 pgrp = tcgetpgrp(fd);
3740 ash_msg("can't access tty; job control turned off");
3744 if (pgrp == getpgrp())
3755 xtcsetpgrp(fd, pgrp);
3757 /* turning job control off */
3760 /* was xtcsetpgrp, but this can make exiting ash
3761 * loop forever if pty is already deleted */
3762 tcsetpgrp(fd, pgrp);
3776 static int FAST_FUNC
3777 killcmd(int argc, char **argv)
3779 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3782 if (argv[i][0] == '%') {
3784 * "kill %N" - job kill
3785 * Converting to pgrp / pid kill
3791 jp = getjob(argv[i], 0);
3793 * In jobs started under job control, we signal
3794 * entire process group by kill -PGRP_ID.
3795 * This happens, f.e., in interactive shell.
3797 * Otherwise, we signal each child via
3798 * kill PID1 PID2 PID3.
3800 * sh -c 'sleep 1|sleep 1 & kill %1'
3801 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3802 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3804 n = jp->nprocs; /* can't be 0 (I hope) */
3807 dst = alloca(n * sizeof(int)*4);
3809 for (j = 0; j < n; j++) {
3810 struct procstat *ps = &jp->ps[j];
3811 /* Skip non-running and not-stopped members
3812 * (i.e. dead members) of the job
3814 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3817 * kill_main has matching code to expect
3818 * leading space. Needed to not confuse
3819 * negative pids with "kill -SIGNAL_NO" syntax
3821 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3825 } while (argv[++i]);
3827 return kill_main(argc, argv);
3831 showpipe(struct job *jp /*, FILE *out*/)
3833 struct procstat *ps;
3834 struct procstat *psend;
3836 psend = jp->ps + jp->nprocs;
3837 for (ps = jp->ps + 1; ps < psend; ps++)
3838 printf(" | %s", ps->ps_cmd);
3839 outcslow('\n', stdout);
3840 flush_stdout_stderr();
3845 restartjob(struct job *jp, int mode)
3847 struct procstat *ps;
3853 if (jp->state == JOBDONE)
3855 jp->state = JOBRUNNING;
3856 pgid = jp->ps[0].ps_pid;
3857 if (mode == FORK_FG)
3858 xtcsetpgrp(ttyfd, pgid);
3859 killpg(pgid, SIGCONT);
3863 if (WIFSTOPPED(ps->ps_status)) {
3869 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3874 static int FAST_FUNC
3875 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3881 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3885 jp = getjob(*argv, 1);
3886 if (mode == FORK_BG) {
3887 set_curjob(jp, CUR_RUNNING);
3888 printf("[%d] ", jobno(jp));
3890 out1str(jp->ps[0].ps_cmd);
3891 showpipe(jp /*, stdout*/);
3892 retval = restartjob(jp, mode);
3893 } while (*argv && *++argv);
3899 sprint_status(char *s, int status, int sigonly)
3905 if (!WIFEXITED(status)) {
3907 if (WIFSTOPPED(status))
3908 st = WSTOPSIG(status);
3911 st = WTERMSIG(status);
3913 if (st == SIGINT || st == SIGPIPE)
3916 if (WIFSTOPPED(status))
3921 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3922 col = fmtstr(s, 32, strsignal(st));
3923 if (WCOREDUMP(status)) {
3924 col += fmtstr(s + col, 16, " (core dumped)");
3926 } else if (!sigonly) {
3927 st = WEXITSTATUS(status);
3929 col = fmtstr(s, 16, "Done(%d)", st);
3931 col = fmtstr(s, 16, "Done");
3938 dowait(int wait_flags, struct job *job)
3943 struct job *thisjob;
3946 TRACE(("dowait(0x%x) called\n", wait_flags));
3948 /* Do a wait system call. If job control is compiled in, we accept
3949 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3950 * NB: _not_ safe_waitpid, we need to detect EINTR */
3952 wait_flags |= WUNTRACED;
3953 pid = waitpid(-1, &status, wait_flags);
3954 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3955 pid, status, errno, strerror(errno)));
3961 for (jp = curjob; jp; jp = jp->prev_job) {
3962 struct procstat *ps;
3963 struct procstat *psend;
3964 if (jp->state == JOBDONE)
3968 psend = ps + jp->nprocs;
3970 if (ps->ps_pid == pid) {
3971 TRACE(("Job %d: changing status of proc %d "
3972 "from 0x%x to 0x%x\n",
3973 jobno(jp), pid, ps->ps_status, status));
3974 ps->ps_status = status;
3977 if (ps->ps_status == -1)
3980 if (state == JOBRUNNING)
3982 if (WIFSTOPPED(ps->ps_status)) {
3983 jp->stopstatus = ps->ps_status;
3987 } while (++ps < psend);
3992 if (!WIFSTOPPED(status))
3998 if (state != JOBRUNNING) {
3999 thisjob->changed = 1;
4001 if (thisjob->state != state) {
4002 TRACE(("Job %d: changing state from %d to %d\n",
4003 jobno(thisjob), thisjob->state, state));
4004 thisjob->state = state;
4006 if (state == JOBSTOPPED) {
4007 set_curjob(thisjob, CUR_STOPPED);
4016 if (thisjob && thisjob == job) {
4020 len = sprint_status(s, status, 1);
4031 blocking_wait_with_raise_on_sig(void)
4033 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4034 if (pid <= 0 && pending_sig)
4035 raise_exception(EXSIG);
4041 showjob(FILE *out, struct job *jp, int mode)
4043 struct procstat *ps;
4044 struct procstat *psend;
4051 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4052 /* just output process (group) id of pipeline */
4053 fprintf(out, "%d\n", ps->ps_pid);
4057 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4062 else if (curjob && jp == curjob->prev_job)
4065 if (mode & SHOW_PIDS)
4066 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4068 psend = ps + jp->nprocs;
4070 if (jp->state == JOBRUNNING) {
4071 strcpy(s + col, "Running");
4072 col += sizeof("Running") - 1;
4074 int status = psend[-1].ps_status;
4075 if (jp->state == JOBSTOPPED)
4076 status = jp->stopstatus;
4077 col += sprint_status(s + col, status, 0);
4079 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4081 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4082 * or prints several "PID | <cmdN>" lines,
4083 * depending on SHOW_PIDS bit.
4084 * We do not print status of individual processes
4085 * between PID and <cmdN>. bash does it, but not very well:
4086 * first line shows overall job status, not process status,
4087 * making it impossible to know 1st process status.
4091 /* for each process */
4094 if (mode & SHOW_PIDS)
4095 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4097 fprintf(out, "%s%*c%s%s",
4099 33 - col >= 0 ? 33 - col : 0, ' ',
4100 ps == jp->ps ? "" : "| ",
4103 } while (++ps != psend);
4104 outcslow('\n', out);
4108 if (jp->state == JOBDONE) {
4109 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4115 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4116 * statuses have changed since the last call to showjobs.
4119 showjobs(FILE *out, int mode)
4123 TRACE(("showjobs(0x%x) called\n", mode));
4125 /* Handle all finished jobs */
4126 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4129 for (jp = curjob; jp; jp = jp->prev_job) {
4130 if (!(mode & SHOW_CHANGED) || jp->changed) {
4131 showjob(out, jp, mode);
4136 static int FAST_FUNC
4137 jobscmd(int argc UNUSED_PARAM, char **argv)
4142 while ((m = nextopt("lp")) != '\0') {
4146 mode |= SHOW_ONLY_PGID;
4152 showjob(stdout, getjob(*argv, 0), mode);
4155 showjobs(stdout, mode);
4162 /* Called only on finished or stopped jobs (no members are running) */
4164 getstatus(struct job *job)
4168 struct procstat *ps;
4170 /* Fetch last member's status */
4171 ps = job->ps + job->nprocs - 1;
4172 status = ps->ps_status;
4174 /* "set -o pipefail" mode: use last _nonzero_ status */
4175 while (status == 0 && --ps >= job->ps)
4176 status = ps->ps_status;
4179 retval = WEXITSTATUS(status);
4180 if (!WIFEXITED(status)) {
4182 retval = WSTOPSIG(status);
4183 if (!WIFSTOPPED(status))
4186 /* XXX: limits number of signals */
4187 retval = WTERMSIG(status);
4189 if (retval == SIGINT)
4195 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4196 jobno(job), job->nprocs, status, retval));
4200 static int FAST_FUNC
4201 waitcmd(int argc UNUSED_PARAM, char **argv)
4208 raise_exception(EXSIG);
4215 /* wait for all jobs */
4219 if (!jp) /* no running procs */
4221 if (jp->state == JOBRUNNING)
4226 blocking_wait_with_raise_on_sig();
4228 * "When bash is waiting for an asynchronous command via
4229 * the wait builtin, the reception of a signal for which a trap
4230 * has been set will cause the wait builtin to return immediately
4231 * with an exit status greater than 128, immediately after which
4232 * the trap is executed."
4234 * blocking_wait_with_raise_on_sig raises signal handlers
4235 * if it gets no pid (pid < 0). However,
4236 * if child sends us a signal *and immediately exits*,
4237 * blocking_wait_with_raise_on_sig gets pid > 0
4238 * and does not handle pending_sig. Check this case: */
4240 raise_exception(EXSIG);
4246 if (**argv != '%') {
4247 pid_t pid = number(*argv);
4252 if (job->ps[job->nprocs - 1].ps_pid == pid)
4254 job = job->prev_job;
4257 job = getjob(*argv, 0);
4259 /* loop until process terminated or stopped */
4260 while (job->state == JOBRUNNING)
4261 blocking_wait_with_raise_on_sig();
4263 retval = getstatus(job);
4276 struct job *jp, *jq;
4278 len = njobs * sizeof(*jp);
4280 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4282 offset = (char *)jp - (char *)jq;
4284 /* Relocate pointers */
4287 jq = (struct job *)((char *)jq + l);
4291 #define joff(p) ((struct job *)((char *)(p) + l))
4292 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4293 if (joff(jp)->ps == &jq->ps0)
4294 jmove(joff(jp)->ps);
4295 if (joff(jp)->prev_job)
4296 jmove(joff(jp)->prev_job);
4306 jp = (struct job *)((char *)jp + len);
4310 } while (--jq >= jp);
4315 * Return a new job structure.
4316 * Called with interrupts off.
4319 makejob(/*union node *node,*/ int nprocs)
4324 for (i = njobs, jp = jobtab; ; jp++) {
4331 if (jp->state != JOBDONE || !jp->waited)
4340 memset(jp, 0, sizeof(*jp));
4342 /* jp->jobctl is a bitfield.
4343 * "jp->jobctl |= jobctl" likely to give awful code */
4347 jp->prev_job = curjob;
4352 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4354 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4361 * Return a string identifying a command (to be printed by the
4364 static char *cmdnextc;
4367 cmdputs(const char *s)
4369 static const char vstype[VSTYPE + 1][3] = {
4370 "", "}", "-", "+", "?", "=",
4371 "%", "%%", "#", "##"
4372 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4375 const char *p, *str;
4379 unsigned char subtype = 0;
4383 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4385 while ((c = *p++) != '\0') {
4393 if ((subtype & VSTYPE) == VSLENGTH)
4397 if (!(subtype & VSQUOTE) == !(quoted & 1))
4403 str = "\"}" + !(quoted & 1);
4410 case CTLBACKQ+CTLQUOTE:
4413 #if ENABLE_SH_MATH_SUPPORT
4428 if ((subtype & VSTYPE) != VSNORMAL)
4430 str = vstype[subtype & VSTYPE];
4431 if (subtype & VSNUL)
4440 /* These can only happen inside quotes */
4453 while ((c = *str++) != '\0') {
4456 } /* while *p++ not NUL */
4459 USTPUTC('"', nextc);
4465 /* cmdtxt() and cmdlist() call each other */
4466 static void cmdtxt(union node *n);
4469 cmdlist(union node *np, int sep)
4471 for (; np; np = np->narg.next) {
4475 if (sep && np->narg.next)
4481 cmdtxt(union node *n)
4484 struct nodelist *lp;
4495 lp = n->npipe.cmdlist;
4513 cmdtxt(n->nbinary.ch1);
4529 cmdtxt(n->nif.test);
4531 if (n->nif.elsepart) {
4532 cmdtxt(n->nif.ifpart);
4534 n = n->nif.elsepart;
4552 cmdtxt(n->nbinary.ch1);
4562 cmdputs(n->nfor.var);
4564 cmdlist(n->nfor.args, 1);
4569 cmdputs(n->narg.text);
4573 cmdlist(n->ncmd.args, 1);
4574 cmdlist(n->ncmd.redirect, 0);
4587 cmdputs(n->ncase.expr->narg.text);
4589 for (np = n->ncase.cases; np; np = np->nclist.next) {
4590 cmdtxt(np->nclist.pattern);
4592 cmdtxt(np->nclist.body);
4606 #if ENABLE_ASH_BASH_COMPAT
4621 cmdputs(utoa(n->nfile.fd));
4623 if (n->type == NTOFD || n->type == NFROMFD) {
4624 cmdputs(utoa(n->ndup.dupfd));
4633 commandtext(union node *n)
4637 STARTSTACKSTR(cmdnextc);
4639 name = stackblock();
4640 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4641 name, cmdnextc, cmdnextc));
4642 return ckstrdup(name);
4647 * Fork off a subshell. If we are doing job control, give the subshell its
4648 * own process group. Jp is a job structure that the job is to be added to.
4649 * N is the command that will be evaluated by the child. Both jp and n may
4650 * be NULL. The mode parameter can be one of the following:
4651 * FORK_FG - Fork off a foreground process.
4652 * FORK_BG - Fork off a background process.
4653 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4654 * process group even if job control is on.
4656 * When job control is turned off, background processes have their standard
4657 * input redirected to /dev/null (except for the second and later processes
4660 * Called with interrupts off.
4663 * Clear traps on a fork.
4670 for (tp = trap; tp < &trap[NSIG]; tp++) {
4671 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4673 if (trap_ptr == trap)
4675 /* else: it "belongs" to trap_ptr vector, don't free */
4677 if ((tp - trap) != 0)
4678 setsignal(tp - trap);
4685 /* Lives far away from here, needed for forkchild */
4686 static void closescript(void);
4688 /* Called after fork(), in child */
4689 static NOINLINE void
4690 forkchild(struct job *jp, union node *n, int mode)
4694 TRACE(("Child shell %d\n", getpid()));
4698 /* man bash: "Non-builtin commands run by bash have signal handlers
4699 * set to the values inherited by the shell from its parent".
4700 * Do we do it correctly? */
4704 if (mode == FORK_NOJOB /* is it `xxx` ? */
4705 && n && n->type == NCMD /* is it single cmd? */
4706 /* && n->ncmd.args->type == NARG - always true? */
4707 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4708 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4709 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4711 TRACE(("Trap hack\n"));
4712 /* Awful hack for `trap` or $(trap).
4714 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4715 * contains an example where "trap" is executed in a subshell:
4717 * save_traps=$(trap)
4719 * eval "$save_traps"
4721 * Standard does not say that "trap" in subshell shall print
4722 * parent shell's traps. It only says that its output
4723 * must have suitable form, but then, in the above example
4724 * (which is not supposed to be normative), it implies that.
4726 * bash (and probably other shell) does implement it
4727 * (traps are reset to defaults, but "trap" still shows them),
4728 * but as a result, "trap" logic is hopelessly messed up:
4731 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4732 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4733 * # true | trap <--- trap is in subshell - no output (ditto)
4734 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4735 * trap -- 'echo Ho' SIGWINCH
4736 * # echo `(trap)` <--- in subshell in subshell - output
4737 * trap -- 'echo Ho' SIGWINCH
4738 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4739 * trap -- 'echo Ho' SIGWINCH
4741 * The rules when to forget and when to not forget traps
4742 * get really complex and nonsensical.
4744 * Our solution: ONLY bare $(trap) or `trap` is special.
4746 /* Save trap handler strings for trap builtin to print */
4747 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4748 /* Fall through into clearing traps */
4752 /* do job control only in root shell */
4754 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4757 if (jp->nprocs == 0)
4760 pgrp = jp->ps[0].ps_pid;
4761 /* this can fail because we are doing it in the parent also */
4763 if (mode == FORK_FG)
4764 xtcsetpgrp(ttyfd, pgrp);
4769 if (mode == FORK_BG) {
4770 /* man bash: "When job control is not in effect,
4771 * asynchronous commands ignore SIGINT and SIGQUIT" */
4774 if (jp->nprocs == 0) {
4776 if (open(bb_dev_null, O_RDONLY) != 0)
4777 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4781 if (iflag) { /* why if iflag only? */
4786 * "In all cases, bash ignores SIGQUIT. Non-builtin
4787 * commands run by bash have signal handlers
4788 * set to the values inherited by the shell
4790 * Take care of the second rule: */
4794 if (n && n->type == NCMD
4795 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4797 TRACE(("Job hack\n"));
4798 /* "jobs": we do not want to clear job list for it,
4799 * instead we remove only _its_ own_ job from job list.
4800 * This makes "jobs .... | cat" more useful.
4806 for (jp = curjob; jp; jp = jp->prev_job)
4811 /* Called after fork(), in parent */
4813 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4816 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4818 TRACE(("In parent shell: child = %d\n", pid));
4820 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4826 if (mode != FORK_NOJOB && jp->jobctl) {
4829 if (jp->nprocs == 0)
4832 pgrp = jp->ps[0].ps_pid;
4833 /* This can fail because we are doing it in the child also */
4837 if (mode == FORK_BG) {
4838 backgndpid = pid; /* set $! */
4839 set_curjob(jp, CUR_RUNNING);
4842 struct procstat *ps = &jp->ps[jp->nprocs++];
4845 ps->ps_cmd = nullstr;
4847 if (doing_jobctl && n)
4848 ps->ps_cmd = commandtext(n);
4854 forkshell(struct job *jp, union node *n, int mode)
4858 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4861 TRACE(("Fork failed, errno=%d", errno));
4864 ash_msg_and_raise_error("can't fork");
4867 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4868 forkchild(jp, n, mode);
4870 forkparent(jp, n, mode, pid);
4876 * Wait for job to finish.
4878 * Under job control we have the problem that while a child process
4879 * is running interrupts generated by the user are sent to the child
4880 * but not to the shell. This means that an infinite loop started by
4881 * an interactive user may be hard to kill. With job control turned off,
4882 * an interactive user may place an interactive program inside a loop.
4883 * If the interactive program catches interrupts, the user doesn't want
4884 * these interrupts to also abort the loop. The approach we take here
4885 * is to have the shell ignore interrupt signals while waiting for a
4886 * foreground process to terminate, and then send itself an interrupt
4887 * signal if the child process was terminated by an interrupt signal.
4888 * Unfortunately, some programs want to do a bit of cleanup and then
4889 * exit on interrupt; unless these processes terminate themselves by
4890 * sending a signal to themselves (instead of calling exit) they will
4891 * confuse this approach.
4893 * Called with interrupts off.
4896 waitforjob(struct job *jp)
4900 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4903 while (jp->state == JOBRUNNING) {
4904 /* In non-interactive shells, we _can_ get
4905 * a keyboard signal here and be EINTRed,
4906 * but we just loop back, waiting for command to complete.
4909 * "If bash is waiting for a command to complete and receives
4910 * a signal for which a trap has been set, the trap
4911 * will not be executed until the command completes."
4913 * Reality is that even if trap is not set, bash
4914 * will not act on the signal until command completes.
4915 * Try this. sleep5intoff.c:
4916 * #include <signal.h>
4917 * #include <unistd.h>
4920 * sigemptyset(&set);
4921 * sigaddset(&set, SIGINT);
4922 * sigaddset(&set, SIGQUIT);
4923 * sigprocmask(SIG_BLOCK, &set, NULL);
4927 * $ bash -c './sleep5intoff; echo hi'
4928 * ^C^C^C^C <--- pressing ^C once a second
4930 * $ bash -c './sleep5intoff; echo hi'
4931 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4934 dowait(DOWAIT_BLOCK, jp);
4941 xtcsetpgrp(ttyfd, rootpid);
4943 * This is truly gross.
4944 * If we're doing job control, then we did a TIOCSPGRP which
4945 * caused us (the shell) to no longer be in the controlling
4946 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4947 * intuit from the subprocess exit status whether a SIGINT
4948 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4950 if (jp->sigint) /* TODO: do the same with all signals */
4951 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4953 if (jp->state == JOBDONE)
4960 * return 1 if there are stopped jobs, otherwise 0
4972 if (jp && jp->state == JOBSTOPPED) {
4973 out2str("You have stopped jobs.\n");
4982 /* ============ redir.c
4984 * Code for dealing with input/output redirection.
4989 #define EMPTY -2 /* marks an unused slot in redirtab */
4990 #define CLOSED -3 /* marks a slot of previously-closed fd */
4993 * Open a file in noclobber mode.
4994 * The code was copied from bash.
4997 noclobberopen(const char *fname)
5000 struct stat finfo, finfo2;
5003 * If the file exists and is a regular file, return an error
5006 r = stat(fname, &finfo);
5007 if (r == 0 && S_ISREG(finfo.st_mode)) {
5013 * If the file was not present (r != 0), make sure we open it
5014 * exclusively so that if it is created before we open it, our open
5015 * will fail. Make sure that we do not truncate an existing file.
5016 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5017 * file was not a regular file, we leave O_EXCL off.
5020 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5021 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5023 /* If the open failed, return the file descriptor right away. */
5028 * OK, the open succeeded, but the file may have been changed from a
5029 * non-regular file to a regular file between the stat and the open.
5030 * We are assuming that the O_EXCL open handles the case where FILENAME
5031 * did not exist and is symlinked to an existing file between the stat
5036 * If we can open it and fstat the file descriptor, and neither check
5037 * revealed that it was a regular file, and the file has not been
5038 * replaced, return the file descriptor.
5040 if (fstat(fd, &finfo2) == 0
5041 && !S_ISREG(finfo2.st_mode)
5042 && finfo.st_dev == finfo2.st_dev
5043 && finfo.st_ino == finfo2.st_ino
5048 /* The file has been replaced. badness. */
5055 * Handle here documents. Normally we fork off a process to write the
5056 * data to a pipe. If the document is short, we can stuff the data in
5057 * the pipe without forking.
5059 /* openhere needs this forward reference */
5060 static void expandhere(union node *arg, int fd);
5062 openhere(union node *redir)
5068 ash_msg_and_raise_error("pipe call failed");
5069 if (redir->type == NHERE) {
5070 len = strlen(redir->nhere.doc->narg.text);
5071 if (len <= PIPE_BUF) {
5072 full_write(pip[1], redir->nhere.doc->narg.text, len);
5076 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5079 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5080 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5081 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5082 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5083 signal(SIGPIPE, SIG_DFL);
5084 if (redir->type == NHERE)
5085 full_write(pip[1], redir->nhere.doc->narg.text, len);
5087 expandhere(redir->nhere.doc, pip[1]);
5088 _exit(EXIT_SUCCESS);
5096 openredirect(union node *redir)
5101 switch (redir->nfile.type) {
5103 fname = redir->nfile.expfname;
5104 f = open(fname, O_RDONLY);
5109 fname = redir->nfile.expfname;
5110 f = open(fname, O_RDWR|O_CREAT, 0666);
5115 #if ENABLE_ASH_BASH_COMPAT
5118 /* Take care of noclobber mode. */
5120 fname = redir->nfile.expfname;
5121 f = noclobberopen(fname);
5128 fname = redir->nfile.expfname;
5129 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5134 fname = redir->nfile.expfname;
5135 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5143 /* Fall through to eliminate warning. */
5144 /* Our single caller does this itself */
5151 f = openhere(redir);
5157 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5159 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5163 * Copy a file descriptor to be >= to. Returns -1
5164 * if the source file descriptor is closed, EMPTY if there are no unused
5165 * file descriptors left.
5167 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5168 * old code was doing close(to) prior to copyfd() to achieve the same */
5170 COPYFD_EXACT = (int)~(INT_MAX),
5171 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5174 copyfd(int from, int to)
5178 if (to & COPYFD_EXACT) {
5179 to &= ~COPYFD_EXACT;
5181 newfd = dup2(from, to);
5183 newfd = fcntl(from, F_DUPFD, to);
5186 if (errno == EMFILE)
5188 /* Happens when source fd is not open: try "echo >&99" */
5189 ash_msg_and_raise_error("%d: %m", from);
5194 /* Struct def and variable are moved down to the first usage site */
5199 struct redirtab *next;
5202 struct two_fd_t two_fd[];
5204 #define redirlist (G_var.redirlist)
5206 static int need_to_remember(struct redirtab *rp, int fd)
5210 if (!rp) /* remembering was not requested */
5213 for (i = 0; i < rp->pair_count; i++) {
5214 if (rp->two_fd[i].orig == fd) {
5215 /* already remembered */
5222 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5223 static int is_hidden_fd(struct redirtab *rp, int fd)
5226 struct parsefile *pf;
5230 /* Check open scripts' fds */
5233 /* We skip pf_fd == 0 case because of the following case:
5234 * $ ash # running ash interactively
5236 * and in script.sh: "exec 9>&0".
5237 * Even though top-level pf_fd _is_ 0,
5238 * it's still ok to use it: "read" builtin uses it,
5239 * why should we cripple "exec" builtin?
5241 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5249 /* Check saved fds of redirects */
5250 fd |= COPYFD_RESTORE;
5251 for (i = 0; i < rp->pair_count; i++) {
5252 if (rp->two_fd[i].copy == fd) {
5260 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5261 * old file descriptors are stashed away so that the redirection can be
5262 * undone by calling popredir.
5264 /* flags passed to redirect */
5265 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5266 #define REDIR_SAVEFD2 03 /* set preverrout */
5268 redirect(union node *redir, int flags)
5270 struct redirtab *sv;
5275 int copied_fd2 = -1;
5285 if (flags & REDIR_PUSH) {
5286 union node *tmp = redir;
5289 #if ENABLE_ASH_BASH_COMPAT
5290 if (tmp->nfile.type == NTO2)
5293 tmp = tmp->nfile.next;
5295 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5296 sv->next = redirlist;
5297 sv->pair_count = sv_pos;
5299 sv->nullredirs = g_nullredirs - 1;
5301 while (sv_pos > 0) {
5303 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5309 fd = redir->nfile.fd;
5310 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5311 right_fd = redir->ndup.dupfd;
5312 //bb_error_msg("doing %d > %d", fd, right_fd);
5313 /* redirect from/to same file descriptor? */
5316 /* "echo >&10" and 10 is a fd opened to a sh script? */
5317 if (is_hidden_fd(sv, right_fd)) {
5318 errno = EBADF; /* as if it is closed */
5319 ash_msg_and_raise_error("%d: %m", right_fd);
5323 newfd = openredirect(redir); /* always >= 0 */
5325 /* Descriptor wasn't open before redirect.
5326 * Mark it for close in the future */
5327 if (need_to_remember(sv, fd)) {
5328 goto remember_to_close;
5333 #if ENABLE_ASH_BASH_COMPAT
5336 if (need_to_remember(sv, fd)) {
5337 /* Copy old descriptor */
5338 /* Careful to not accidentally "save"
5339 * to the same fd as right side fd in N>&M */
5340 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5341 i = fcntl(fd, F_DUPFD, minfd);
5342 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5343 * are closed in popredir() in the child, preventing them from leaking
5344 * into child. (popredir() also cleans up the mess in case of failures)
5349 /* Strange error (e.g. "too many files" EMFILE?) */
5353 ash_msg_and_raise_error("%d: %m", fd);
5356 /* EBADF: it is not open - good, remember to close it */
5359 } else { /* fd is open, save its copy */
5360 /* "exec fd>&-" should not close fds
5361 * which point to script file(s).
5362 * Force them to be restored afterwards */
5363 if (is_hidden_fd(sv, fd))
5364 i |= COPYFD_RESTORE;
5368 sv->two_fd[sv_pos].orig = fd;
5369 sv->two_fd[sv_pos].copy = i;
5373 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5374 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5375 /* Don't want to trigger debugging */
5379 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5381 } else if (fd != newfd) { /* move newfd to fd */
5382 copyfd(newfd, fd | COPYFD_EXACT);
5383 #if ENABLE_ASH_BASH_COMPAT
5384 if (!(redir->nfile.type == NTO2 && fd == 2))
5388 #if ENABLE_ASH_BASH_COMPAT
5389 if (redir->nfile.type == NTO2 && fd == 1) {
5390 /* We already redirected it to fd 1, now copy it to 2 */
5396 } while ((redir = redir->nfile.next) != NULL);
5399 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5400 preverrout_fd = copied_fd2;
5404 * Undo the effects of the last redirection.
5407 popredir(int drop, int restore)
5409 struct redirtab *rp;
5412 if (--g_nullredirs >= 0)
5416 for (i = 0; i < rp->pair_count; i++) {
5417 int fd = rp->two_fd[i].orig;
5418 int copy = rp->two_fd[i].copy;
5419 if (copy == CLOSED) {
5424 if (copy != EMPTY) {
5425 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5426 copy &= ~COPYFD_RESTORE;
5428 copyfd(copy, fd | COPYFD_EXACT);
5430 close(copy & ~COPYFD_RESTORE);
5433 redirlist = rp->next;
5434 g_nullredirs = rp->nullredirs;
5440 * Undo all redirections. Called on error or interrupt.
5444 * Discard all saved file descriptors.
5447 clearredir(int drop)
5453 popredir(drop, /*restore:*/ 0);
5458 redirectsafe(union node *redir, int flags)
5461 volatile int saveint;
5462 struct jmploc *volatile savehandler = exception_handler;
5463 struct jmploc jmploc;
5466 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5467 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5469 exception_handler = &jmploc;
5470 redirect(redir, flags);
5472 exception_handler = savehandler;
5473 if (err && exception_type != EXERROR)
5474 longjmp(exception_handler->loc, 1);
5475 RESTORE_INT(saveint);
5480 /* ============ Routines to expand arguments to commands
5482 * We have to deal with backquotes, shell variables, and file metacharacters.
5485 #if ENABLE_SH_MATH_SUPPORT
5487 ash_arith(const char *s)
5489 arith_state_t math_state;
5492 math_state.lookupvar = lookupvar;
5493 math_state.setvar = setvar2;
5494 //math_state.endofname = endofname;
5497 result = arith(&math_state, s);
5498 if (math_state.errmsg)
5499 ash_msg_and_raise_error(math_state.errmsg);
5509 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5510 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5511 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5512 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5513 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5514 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5515 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5516 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5517 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5521 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5522 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5523 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5524 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5525 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5528 * Structure specifying which parts of the string should be searched
5529 * for IFS characters.
5532 struct ifsregion *next; /* next region in list */
5533 int begoff; /* offset of start of region */
5534 int endoff; /* offset of end of region */
5535 int nulonly; /* search for nul bytes only */
5539 struct strlist *list;
5540 struct strlist **lastp;
5543 /* output of current string */
5544 static char *expdest;
5545 /* list of back quote expressions */
5546 static struct nodelist *argbackq;
5547 /* first struct in list of ifs regions */
5548 static struct ifsregion ifsfirst;
5549 /* last struct in list */
5550 static struct ifsregion *ifslastp;
5551 /* holds expanded arg list */
5552 static struct arglist exparg;
5557 #if !ENABLE_SH_MATH_SUPPORT
5558 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5559 typedef long arith_t;
5560 # define ARITH_FMT "%ld"
5567 expdest = makestrspace(32, expdest);
5568 len = fmtstr(expdest, 32, ARITH_FMT, num);
5569 STADJUST(len, expdest);
5574 esclen(const char *start, const char *p)
5578 while (p > start && (unsigned char)*--p == CTLESC) {
5585 * Remove any CTLESC characters from a string.
5588 rmescapes(char *str, int flag)
5590 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5594 unsigned protect_against_glob;
5597 p = strpbrk(str, qchars);
5603 if (flag & RMESCAPE_ALLOC) {
5604 size_t len = p - str;
5605 size_t fulllen = len + strlen(p) + 1;
5607 if (flag & RMESCAPE_GROW) {
5608 int strloc = str - (char *)stackblock();
5609 r = makestrspace(fulllen, expdest);
5610 /* p and str may be invalidated by makestrspace */
5611 str = (char *)stackblock() + strloc;
5613 } else if (flag & RMESCAPE_HEAP) {
5614 r = ckmalloc(fulllen);
5616 r = stalloc(fulllen);
5620 q = (char *)memcpy(q, str, len) + len;
5624 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5625 globbing = flag & RMESCAPE_GLOB;
5626 protect_against_glob = globbing;
5628 if ((unsigned char)*p == CTLQUOTEMARK) {
5629 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5630 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5631 // Note: both inquotes and protect_against_glob only affect whether
5632 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5633 inquotes = ~inquotes;
5635 protect_against_glob = globbing;
5639 /* naked back slash */
5640 protect_against_glob = 0;
5643 if ((unsigned char)*p == CTLESC) {
5645 if (protect_against_glob && inquotes && *p != '/') {
5649 protect_against_glob = globbing;
5654 if (flag & RMESCAPE_GROW) {
5656 STADJUST(q - r + 1, expdest);
5660 #define pmatch(a, b) !fnmatch((a), (b), 0)
5663 * Prepare a pattern for a expmeta (internal glob(3)) call.
5665 * Returns an stalloced string.
5668 preglob(const char *pattern, int quoted, int flag)
5670 flag |= RMESCAPE_GLOB;
5672 flag |= RMESCAPE_QUOTED;
5674 return rmescapes((char *)pattern, flag);
5678 * Put a string on the stack.
5681 memtodest(const char *p, size_t len, int syntax, int quotes)
5685 q = makestrspace(quotes ? len * 2 : len, q);
5688 unsigned char c = *p++;
5692 int n = SIT(c, syntax);
5693 if (n == CCTL || n == CBACK)
5703 strtodest(const char *p, int syntax, int quotes)
5705 memtodest(p, strlen(p), syntax, quotes);
5709 * Record the fact that we have to scan this region of the
5710 * string for IFS characters.
5713 recordregion(int start, int end, int nulonly)
5715 struct ifsregion *ifsp;
5717 if (ifslastp == NULL) {
5721 ifsp = ckzalloc(sizeof(*ifsp));
5722 /*ifsp->next = NULL; - ckzalloc did it */
5723 ifslastp->next = ifsp;
5727 ifslastp->begoff = start;
5728 ifslastp->endoff = end;
5729 ifslastp->nulonly = nulonly;
5733 removerecordregions(int endoff)
5735 if (ifslastp == NULL)
5738 if (ifsfirst.endoff > endoff) {
5739 while (ifsfirst.next) {
5740 struct ifsregion *ifsp;
5742 ifsp = ifsfirst.next->next;
5743 free(ifsfirst.next);
5744 ifsfirst.next = ifsp;
5747 if (ifsfirst.begoff > endoff) {
5750 ifslastp = &ifsfirst;
5751 ifsfirst.endoff = endoff;
5756 ifslastp = &ifsfirst;
5757 while (ifslastp->next && ifslastp->next->begoff < endoff)
5758 ifslastp = ifslastp->next;
5759 while (ifslastp->next) {
5760 struct ifsregion *ifsp;
5762 ifsp = ifslastp->next->next;
5763 free(ifslastp->next);
5764 ifslastp->next = ifsp;
5767 if (ifslastp->endoff > endoff)
5768 ifslastp->endoff = endoff;
5772 exptilde(char *startp, char *p, int flags)
5778 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5783 while ((c = *++p) != '\0') {
5790 if (flags & EXP_VARTILDE)
5800 if (*name == '\0') {
5801 home = lookupvar("HOME");
5803 pw = getpwnam(name);
5808 if (!home || !*home)
5811 startloc = expdest - (char *)stackblock();
5812 strtodest(home, SQSYNTAX, quotes);
5813 recordregion(startloc, expdest - (char *)stackblock(), 0);
5821 * Execute a command inside back quotes. If it's a builtin command, we
5822 * want to save its output in a block obtained from malloc. Otherwise
5823 * we fork off a subprocess and get the output of the command via a pipe.
5824 * Should be called with interrupts off.
5826 struct backcmd { /* result of evalbackcmd */
5827 int fd; /* file descriptor to read from */
5828 int nleft; /* number of chars in buffer */
5829 char *buf; /* buffer */
5830 struct job *jp; /* job structure for command */
5833 /* These forward decls are needed to use "eval" code for backticks handling: */
5834 static uint8_t back_exitstatus; /* exit status of backquoted command */
5835 #define EV_EXIT 01 /* exit after evaluating tree */
5836 static void evaltree(union node *, int);
5838 static void FAST_FUNC
5839 evalbackcmd(union node *n, struct backcmd *result)
5850 saveherefd = herefd;
5858 ash_msg_and_raise_error("pipe call failed");
5859 jp = makejob(/*n,*/ 1);
5860 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5865 copyfd(pip[1], 1 | COPYFD_EXACT);
5869 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5873 result->fd = pip[0];
5876 herefd = saveherefd;
5878 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5879 result->fd, result->buf, result->nleft, result->jp));
5883 * Expand stuff in backwards quotes.
5886 expbackq(union node *cmd, int quoted, int quotes)
5894 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5895 struct stackmark smark;
5898 setstackmark(&smark);
5900 startloc = dest - (char *)stackblock();
5902 evalbackcmd(cmd, &in);
5903 popstackmark(&smark);
5910 memtodest(p, i, syntax, quotes);
5914 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5915 TRACE(("expbackq: read returns %d\n", i));
5924 back_exitstatus = waitforjob(in.jp);
5928 /* Eat all trailing newlines */
5930 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5935 recordregion(startloc, dest - (char *)stackblock(), 0);
5936 TRACE(("evalbackq: size:%d:'%.*s'\n",
5937 (int)((dest - (char *)stackblock()) - startloc),
5938 (int)((dest - (char *)stackblock()) - startloc),
5939 stackblock() + startloc));
5942 #if ENABLE_SH_MATH_SUPPORT
5944 * Expand arithmetic expression. Backup to start of expression,
5945 * evaluate, place result in (backed up) result, adjust string position.
5958 * This routine is slightly over-complicated for
5959 * efficiency. Next we scan backwards looking for the
5960 * start of arithmetic.
5962 start = stackblock();
5969 while ((unsigned char)*p != CTLARI) {
5973 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5978 esc = esclen(start, p);
5988 removerecordregions(begoff);
5995 rmescapes(p + 2, 0);
5997 len = cvtnum(ash_arith(p + 2));
6000 recordregion(begoff, begoff + len, 0);
6004 /* argstr needs it */
6005 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6008 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6009 * characters to allow for further processing. Otherwise treat
6010 * $@ like $* since no splitting will be performed.
6012 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6013 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6014 * for correct expansion of "B=$A" word.
6017 argstr(char *p, int flags, struct strlist *var_str_list)
6019 static const char spclchars[] ALIGN1 = {
6027 CTLBACKQ | CTLQUOTE,
6028 #if ENABLE_SH_MATH_SUPPORT
6033 const char *reject = spclchars;
6034 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
6035 int breakall = flags & EXP_WORD;
6040 if (!(flags & EXP_VARTILDE)) {
6042 } else if (flags & EXP_VARTILDE2) {
6047 if (flags & EXP_TILDE) {
6050 flags &= ~EXP_TILDE;
6053 if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
6056 p = exptilde(p, q, flags);
6059 startloc = expdest - (char *)stackblock();
6063 length += strcspn(p + length, reject);
6067 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6069 /* c == '=' || c == ':' || c == CTLENDARI */
6075 expdest = stack_nputstr(p, length, expdest);
6076 newloc = expdest - (char *)stackblock();
6077 if (breakall && !inquotes && newloc > startloc) {
6078 recordregion(startloc, newloc, 0);
6089 if (flags & EXP_VARTILDE2) {
6093 flags |= EXP_VARTILDE2;
6098 * sort of a hack - expand tildes in variable
6099 * assignments (after the first '=' and after ':'s).
6108 case CTLENDVAR: /* ??? */
6111 /* "$@" syntax adherence hack */
6113 && memcmp(p, dolatstr, 4) == 0
6114 && ( p[4] == (char)CTLQUOTEMARK
6115 || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
6118 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6121 inquotes = !inquotes;
6134 p = evalvar(p, flags, var_str_list);
6138 case CTLBACKQ|CTLQUOTE:
6139 expbackq(argbackq->n, c, quotes);
6140 argbackq = argbackq->next;
6142 #if ENABLE_SH_MATH_SUPPORT
6154 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6155 char *pattern, int quotes, int zero)
6164 const char *s = loc2;
6171 match = pmatch(pattern, s);
6176 if (quotes && (unsigned char)*loc == CTLESC)
6185 scanright(char *startp, char *rmesc, char *rmescend,
6186 char *pattern, int quotes, int match_at_start)
6188 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6189 int try2optimize = match_at_start;
6195 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6196 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6197 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6199 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6200 * and on each iteration they go back two/one char until they reach the beginning.
6201 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6203 /* TODO: document in what other circumstances we are called. */
6205 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6208 const char *s = loc2;
6209 if (match_at_start) {
6213 match = pmatch(pattern, s);
6214 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6218 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6220 /* Maybe we can optimize this:
6221 * if pattern ends with unescaped *, we can avoid checking
6222 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6223 * it wont match truncated "raw_value_of_" strings too.
6225 unsigned plen = strlen(pattern);
6226 /* Does it end with "*"? */
6227 if (plen != 0 && pattern[--plen] == '*') {
6228 /* "xxxx*" is not escaped */
6229 /* "xxx\*" is escaped */
6230 /* "xx\\*" is not escaped */
6231 /* "x\\\*" is escaped */
6233 while (plen != 0 && pattern[--plen] == '\\')
6236 break; /* ends with unescaped "*" */
6244 esc = esclen(startp, loc);
6255 static void varunset(const char *, const char *, const char *, int) NORETURN;
6257 varunset(const char *end, const char *var, const char *umsg, int varflags)
6263 msg = "parameter not set";
6265 if ((unsigned char)*end == CTLENDVAR) {
6266 if (varflags & VSNUL)
6272 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6275 #if ENABLE_ASH_BASH_COMPAT
6277 parse_sub_pattern(char *arg, int varflags)
6279 char *idx, *repl = NULL;
6282 //char *org_arg = arg;
6283 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6290 /* Only the first '/' seen is our separator */
6299 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6300 * The result is a_\_z_c (not a\_\_z_c)!
6302 * Enable debug prints in this function and you'll see:
6303 * ash: arg:'\\b/_\\_z_' varflags:d
6304 * ash: pattern:'\\b' repl:'_\_z_'
6305 * That is, \\b is interpreted as \\b, but \\_ as \_!
6306 * IOW: search pattern and replace string treat backslashes
6307 * differently! That is the reason why we check repl below:
6309 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6310 arg++; /* skip both '\', not just first one */
6313 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6317 #endif /* ENABLE_ASH_BASH_COMPAT */
6320 subevalvar(char *p, char *varname, int strloc, int subtype,
6321 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6323 struct nodelist *saveargbackq = argbackq;
6326 char *rmesc, *rmescend;
6328 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6329 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6330 int saveherefd = herefd;
6331 int amount, workloc, resetloc;
6333 char *(*scan)(char*, char*, char*, char*, int, int);
6335 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6336 // p, varname, strloc, subtype, startloc, varflags, quotes);
6339 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6341 STPUTC('\0', expdest);
6342 herefd = saveherefd;
6343 argbackq = saveargbackq;
6344 startp = (char *)stackblock() + startloc;
6348 setvar(varname, startp, 0);
6349 amount = startp - expdest;
6350 STADJUST(amount, expdest);
6354 varunset(p, varname, startp, varflags);
6357 #if ENABLE_ASH_BASH_COMPAT
6359 loc = str = stackblock() + strloc;
6360 /* Read POS in ${var:POS:LEN} */
6361 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6362 len = str - startp - 1;
6364 /* *loc != '\0', guaranteed by parser */
6368 /* Adjust the length by the number of escapes */
6369 for (ptr = startp; ptr < (str - 1); ptr++) {
6370 if ((unsigned char)*ptr == CTLESC) {
6378 if (*loc++ == ':') {
6382 /* Skip POS in ${var:POS:LEN} */
6384 while (*loc && *loc != ':') {
6386 * bash complains on: var=qwe; echo ${var:1a:123}
6388 ash_msg_and_raise_error(msg_illnum, str);
6392 if (*loc++ == ':') {
6396 if (pos >= orig_len) {
6400 if (len > (orig_len - pos))
6401 len = orig_len - pos;
6403 for (str = startp; pos; str++, pos--) {
6404 if (quotes && (unsigned char)*str == CTLESC)
6407 for (loc = startp; len; len--) {
6408 if (quotes && (unsigned char)*str == CTLESC)
6413 amount = loc - expdest;
6414 STADJUST(amount, expdest);
6419 resetloc = expdest - (char *)stackblock();
6421 /* We'll comeback here if we grow the stack while handling
6422 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6423 * stack will need rebasing, and we'll need to remove our work
6426 IF_ASH_BASH_COMPAT(restart:)
6428 amount = expdest - ((char *)stackblock() + resetloc);
6429 STADJUST(-amount, expdest);
6430 startp = (char *)stackblock() + startloc;
6433 rmescend = (char *)stackblock() + strloc;
6435 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6436 if (rmesc != startp) {
6438 startp = (char *)stackblock() + startloc;
6442 str = (char *)stackblock() + strloc;
6443 preglob(str, varflags & VSQUOTE, 0);
6444 workloc = expdest - (char *)stackblock();
6446 #if ENABLE_ASH_BASH_COMPAT
6447 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6451 repl = parse_sub_pattern(str, varflags);
6452 //bb_error_msg("repl:'%s'", repl);
6457 /* If there's no pattern to match, return the expansion unmolested */
6466 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6467 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6469 /* No match, advance */
6470 char *restart_detect = stackblock();
6472 STPUTC(*idx, expdest);
6473 if (quotes && (unsigned char)*idx == CTLESC) {
6476 STPUTC(*idx, expdest);
6478 if (stackblock() != restart_detect)
6483 /* continue; - prone to quadratic behavior, smarter code: */
6486 if (str[0] == '*') {
6487 /* Pattern is "*foo". If "*foo" does not match "long_string",
6488 * it would never match "ong_string" etc, no point in trying.
6495 if (subtype == VSREPLACEALL) {
6497 if (quotes && (unsigned char)*idx == CTLESC)
6506 //bb_error_msg("repl:'%s'", repl);
6507 for (loc = (char*)repl; *loc; loc++) {
6508 char *restart_detect = stackblock();
6509 if (quotes && *loc == '\\') {
6510 STPUTC(CTLESC, expdest);
6513 STPUTC(*loc, expdest);
6514 if (stackblock() != restart_detect)
6519 if (subtype == VSREPLACE) {
6520 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6522 char *restart_detect = stackblock();
6523 STPUTC(*idx, expdest);
6524 if (stackblock() != restart_detect)
6533 /* We've put the replaced text into a buffer at workloc, now
6534 * move it to the right place and adjust the stack.
6536 STPUTC('\0', expdest);
6537 startp = (char *)stackblock() + startloc;
6538 memmove(startp, (char *)stackblock() + workloc, len + 1);
6539 //bb_error_msg("startp:'%s'", startp);
6540 amount = expdest - (startp + len);
6541 STADJUST(-amount, expdest);
6544 #endif /* ENABLE_ASH_BASH_COMPAT */
6546 subtype -= VSTRIMRIGHT;
6548 if (subtype < 0 || subtype > 7)
6551 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6552 zero = subtype >> 1;
6553 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6554 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6556 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6559 memmove(startp, loc, str - loc);
6560 loc = startp + (str - loc) - 1;
6563 amount = loc - expdest;
6564 STADJUST(amount, expdest);
6570 * Add the value of a specialized variable to the stack string.
6571 * name parameter (examples):
6572 * ash -c 'echo $1' name:'1='
6573 * ash -c 'echo $qwe' name:'qwe='
6574 * ash -c 'echo $$' name:'$='
6575 * ash -c 'echo ${$}' name:'$='
6576 * ash -c 'echo ${$##q}' name:'$=q'
6577 * ash -c 'echo ${#$}' name:'$='
6578 * note: examples with bad shell syntax:
6579 * ash -c 'echo ${#$1}' name:'$=1'
6580 * ash -c 'echo ${#1#}' name:'1=#'
6582 static NOINLINE ssize_t
6583 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6590 int subtype = varflags & VSTYPE;
6591 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6592 int quoted = varflags & VSQUOTE;
6593 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6603 num = shellparam.nparam;
6611 goto check_1char_name;
6613 expdest = makestrspace(NOPTS, expdest);
6614 for (i = NOPTS - 1; i >= 0; i--) {
6616 USTPUTC(optletters(i), expdest);
6622 /* handles cases similar to ${#$1} */
6623 if (name[2] != '\0')
6624 raise_error_syntax("bad substitution");
6631 if (quoted && (flags & EXP_FULL)) {
6632 /* note: this is not meant as PEOF value */
6633 sep = 1 << CHAR_BIT;
6638 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6639 i = SIT(sep, syntax);
6640 if (quotes && (i == CCTL || i == CBACK))
6646 while ((p = *ap++) != NULL) {
6649 partlen = strlen(p);
6652 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6653 memtodest(p, partlen, syntax, quotes);
6659 if (subtype == VSPLUS || subtype == VSLENGTH) {
6665 /* note: may put NUL despite sep != 0
6666 * (see sep = 1 << CHAR_BIT above) */
6672 } /* case '@' and '*' */
6683 num = atoi(name); /* number(name) fails on ${N#str} etc */
6684 if (num < 0 || num > shellparam.nparam)
6686 p = num ? shellparam.p[num - 1] : arg0;
6689 /* NB: name has form "VAR=..." */
6691 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6692 * which should be considered before we check variables. */
6694 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6698 str = var_str_list->text;
6699 eq = strchr(str, '=');
6700 if (!eq) /* stop at first non-assignment */
6703 if (name_len == (unsigned)(eq - str)
6704 && strncmp(str, name, name_len) == 0
6707 /* goto value; - WRONG! */
6708 /* think "A=1 A=2 B=$A" */
6710 var_str_list = var_str_list->next;
6711 } while (var_str_list);
6715 p = lookupvar(name);
6721 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6722 memtodest(p, len, syntax, quotes);
6726 if (subtype == VSPLUS || subtype == VSLENGTH)
6727 STADJUST(-len, expdest);
6732 * Expand a variable, and return a pointer to the next character in the
6736 evalvar(char *p, int flags, struct strlist *var_str_list)
6747 varflags = (unsigned char) *p++;
6748 subtype = varflags & VSTYPE;
6749 quoted = varflags & VSQUOTE;
6751 easy = (!quoted || (*var == '@' && shellparam.nparam));
6752 startloc = expdest - (char *)stackblock();
6753 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6756 varlen = varvalue(var, varflags, flags, var_str_list);
6757 if (varflags & VSNUL)
6760 if (subtype == VSPLUS) {
6761 varlen = -1 - varlen;
6765 if (subtype == VSMINUS) {
6770 flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
6780 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6782 if (subevalvar(p, var, /* strloc: */ 0,
6783 subtype, startloc, varflags,
6789 * Remove any recorded regions beyond
6792 removerecordregions(startloc);
6802 if (varlen < 0 && uflag)
6803 varunset(p, var, 0, 0);
6805 if (subtype == VSLENGTH) {
6806 cvtnum(varlen > 0 ? varlen : 0);
6810 if (subtype == VSNORMAL) {
6821 case VSTRIMRIGHTMAX:
6822 #if ENABLE_ASH_BASH_COMPAT
6835 * Terminate the string and start recording the pattern
6838 STPUTC('\0', expdest);
6839 patloc = expdest - (char *)stackblock();
6840 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6842 //TODO: | EXP_REDIR too? All other such places do it too
6843 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6846 int amount = expdest - (
6847 (char *)stackblock() + patloc - 1
6849 STADJUST(-amount, expdest);
6851 /* Remove any recorded regions beyond start of variable */
6852 removerecordregions(startloc);
6854 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6858 if (subtype != VSNORMAL) { /* skip to end of alternative */
6861 unsigned char c = *p++;
6864 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6866 argbackq = argbackq->next;
6867 } else if (c == CTLVAR) {
6868 if ((*p++ & VSTYPE) != VSNORMAL)
6870 } else if (c == CTLENDVAR) {
6880 * Break the argument string into pieces based upon IFS and add the
6881 * strings to the argument list. The regions of the string to be
6882 * searched for IFS characters have been stored by recordregion.
6885 ifsbreakup(char *string, struct arglist *arglist)
6887 struct ifsregion *ifsp;
6892 const char *ifs, *realifs;
6897 if (ifslastp != NULL) {
6900 realifs = ifsset() ? ifsval() : defifs;
6903 p = string + ifsp->begoff;
6904 nulonly = ifsp->nulonly;
6905 ifs = nulonly ? nullstr : realifs;
6907 while (p < string + ifsp->endoff) {
6909 if ((unsigned char)*p == CTLESC)
6911 if (!strchr(ifs, *p)) {
6916 ifsspc = (strchr(defifs, *p) != NULL);
6917 /* Ignore IFS whitespace at start */
6918 if (q == start && ifsspc) {
6924 sp = stzalloc(sizeof(*sp));
6926 *arglist->lastp = sp;
6927 arglist->lastp = &sp->next;
6931 if (p >= string + ifsp->endoff) {
6935 if ((unsigned char)*p == CTLESC)
6937 if (strchr(ifs, *p) == NULL) {
6941 if (strchr(defifs, *p) == NULL) {
6956 } while (ifsp != NULL);
6965 sp = stzalloc(sizeof(*sp));
6967 *arglist->lastp = sp;
6968 arglist->lastp = &sp->next;
6974 struct ifsregion *p;
6979 struct ifsregion *ifsp;
6985 ifsfirst.next = NULL;
6990 * Add a file name to the list.
6993 addfname(const char *name)
6997 sp = stzalloc(sizeof(*sp));
6998 sp->text = ststrdup(name);
7000 exparg.lastp = &sp->next;
7004 * Do metacharacter (i.e. *, ?, [...]) expansion.
7007 expmeta(char *expdir, char *enddir, char *name)
7022 for (p = name; *p; p++) {
7023 if (*p == '*' || *p == '?')
7025 else if (*p == '[') {
7032 if (*q == '/' || *q == '\0')
7039 } else if (*p == '\\')
7041 else if (*p == '/') {
7048 if (metaflag == 0) { /* we've reached the end of the file name */
7049 if (enddir != expdir)
7057 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7068 } while (p < start);
7070 if (enddir == expdir) {
7072 } else if (enddir == expdir + 1 && *expdir == '/') {
7081 if (enddir != expdir)
7083 if (*endname == 0) {
7095 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7096 if (dp->d_name[0] == '.' && !matchdot)
7098 if (pmatch(start, dp->d_name)) {
7100 strcpy(enddir, dp->d_name);
7103 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7106 expmeta(expdir, p, endname);
7115 static struct strlist *
7116 msort(struct strlist *list, int len)
7118 struct strlist *p, *q = NULL;
7119 struct strlist **lpp;
7127 for (n = half; --n >= 0;) {
7131 q->next = NULL; /* terminate first half of list */
7132 q = msort(list, half); /* sort first half of list */
7133 p = msort(p, len - half); /* sort second half */
7136 #if ENABLE_LOCALE_SUPPORT
7137 if (strcoll(p->text, q->text) < 0)
7139 if (strcmp(p->text, q->text) < 0)
7163 * Sort the results of file name expansion. It calculates the number of
7164 * strings to sort and then calls msort (short for merge sort) to do the
7167 static struct strlist *
7168 expsort(struct strlist *str)
7174 for (sp = str; sp; sp = sp->next)
7176 return msort(str, len);
7180 expandmeta(struct strlist *str /*, int flag*/)
7182 static const char metachars[] ALIGN1 = {
7185 /* TODO - EXP_REDIR */
7189 struct strlist **savelastp;
7195 if (!strpbrk(str->text, metachars))
7197 savelastp = exparg.lastp;
7200 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7202 int i = strlen(str->text);
7203 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7205 expmeta(expdir, expdir, p);
7210 if (exparg.lastp == savelastp) {
7215 *exparg.lastp = str;
7216 rmescapes(str->text, 0);
7217 exparg.lastp = &str->next;
7219 *exparg.lastp = NULL;
7220 *savelastp = sp = expsort(*savelastp);
7221 while (sp->next != NULL)
7223 exparg.lastp = &sp->next;
7230 * Perform variable substitution and command substitution on an argument,
7231 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7232 * perform splitting and file name expansion. When arglist is NULL, perform
7233 * here document expansion.
7236 expandarg(union node *arg, struct arglist *arglist, int flag)
7241 argbackq = arg->narg.backquote;
7242 STARTSTACKSTR(expdest);
7243 ifsfirst.next = NULL;
7245 argstr(arg->narg.text, flag,
7246 /* var_str_list: */ arglist ? arglist->list : NULL);
7247 p = _STPUTC('\0', expdest);
7249 if (arglist == NULL) {
7250 return; /* here document expanded */
7252 p = grabstackstr(p);
7253 exparg.lastp = &exparg.list;
7257 if (flag & EXP_FULL) {
7258 ifsbreakup(p, &exparg);
7259 *exparg.lastp = NULL;
7260 exparg.lastp = &exparg.list;
7261 expandmeta(exparg.list /*, flag*/);
7263 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7265 sp = stzalloc(sizeof(*sp));
7268 exparg.lastp = &sp->next;
7272 *exparg.lastp = NULL;
7274 *arglist->lastp = exparg.list;
7275 arglist->lastp = exparg.lastp;
7280 * Expand shell variables and backquotes inside a here document.
7283 expandhere(union node *arg, int fd)
7286 expandarg(arg, (struct arglist *)NULL, 0);
7287 full_write(fd, stackblock(), expdest - (char *)stackblock());
7291 * Returns true if the pattern matches the string.
7294 patmatch(char *pattern, const char *string)
7296 return pmatch(preglob(pattern, 0, 0), string);
7300 * See if a pattern matches in a case statement.
7303 casematch(union node *pattern, char *val)
7305 struct stackmark smark;
7308 setstackmark(&smark);
7309 argbackq = pattern->narg.backquote;
7310 STARTSTACKSTR(expdest);
7312 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7313 /* var_str_list: */ NULL);
7314 STACKSTRNUL(expdest);
7315 result = patmatch(stackblock(), val);
7316 popstackmark(&smark);
7321 /* ============ find_command */
7325 int (*builtin)(int, char **) FAST_FUNC;
7326 /* unsigned flags; */
7328 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7329 /* "regular" builtins always take precedence over commands,
7330 * regardless of PATH=....%builtin... position */
7331 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7332 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7335 smallint cmdtype; /* CMDxxx */
7338 /* index >= 0 for commands without path (slashes) */
7339 /* (TODO: what exactly does the value mean? PATH position?) */
7340 /* index == -1 for commands with slashes */
7341 /* index == (-2 - applet_no) for NOFORK applets */
7342 const struct builtincmd *cmd;
7343 struct funcnode *func;
7346 /* values of cmdtype */
7347 #define CMDUNKNOWN -1 /* no entry in table for command */
7348 #define CMDNORMAL 0 /* command is an executable program */
7349 #define CMDFUNCTION 1 /* command is a shell function */
7350 #define CMDBUILTIN 2 /* command is a shell builtin */
7352 /* action to find_command() */
7353 #define DO_ERR 0x01 /* prints errors */
7354 #define DO_ABS 0x02 /* checks absolute paths */
7355 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7356 #define DO_ALTPATH 0x08 /* using alternate path */
7357 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7359 static void find_command(char *, struct cmdentry *, int, const char *);
7362 /* ============ Hashing commands */
7365 * When commands are first encountered, they are entered in a hash table.
7366 * This ensures that a full path search will not have to be done for them
7367 * on each invocation.
7369 * We should investigate converting to a linear search, even though that
7370 * would make the command name "hash" a misnomer.
7374 struct tblentry *next; /* next entry in hash chain */
7375 union param param; /* definition of builtin function */
7376 smallint cmdtype; /* CMDxxx */
7377 char rehash; /* if set, cd done since entry created */
7378 char cmdname[1]; /* name of command */
7381 static struct tblentry **cmdtable;
7382 #define INIT_G_cmdtable() do { \
7383 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7386 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7390 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7392 #if ENABLE_FEATURE_SH_STANDALONE
7393 if (applet_no >= 0) {
7394 if (APPLET_IS_NOEXEC(applet_no)) {
7398 run_applet_no_and_exit(applet_no, argv);
7400 /* re-exec ourselves with the new arguments */
7401 execve(bb_busybox_exec_path, argv, envp);
7402 /* If they called chroot or otherwise made the binary no longer
7403 * executable, fall through */
7410 execve(cmd, argv, envp);
7411 } while (errno == EINTR);
7413 execve(cmd, argv, envp);
7415 if (cmd == (char*) bb_busybox_exec_path) {
7416 /* We already visited ENOEXEC branch below, don't do it again */
7417 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7421 if (errno == ENOEXEC) {
7422 /* Run "cmd" as a shell script:
7423 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7424 * "If the execve() function fails with ENOEXEC, the shell
7425 * shall execute a command equivalent to having a shell invoked
7426 * with the command name as its first operand,
7427 * with any remaining arguments passed to the new shell"
7429 * That is, do not use $SHELL, user's shell, or /bin/sh;
7430 * just call ourselves.
7435 for (ap = argv; *ap; ap++)
7437 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7438 new[0] = (char*) "ash";
7441 while ((*ap++ = *++argv) != NULL)
7443 cmd = (char*) bb_busybox_exec_path;
7450 * Exec a program. Never returns. If you change this routine, you may
7451 * have to change the find_command routine as well.
7453 static void shellexec(char **, const char *, int) NORETURN;
7455 shellexec(char **argv, const char *path, int idx)
7461 #if ENABLE_FEATURE_SH_STANDALONE
7465 clearredir(/*drop:*/ 1);
7466 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7467 if (strchr(argv[0], '/') != NULL
7468 #if ENABLE_FEATURE_SH_STANDALONE
7469 || (applet_no = find_applet_by_name(argv[0])) >= 0
7472 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7476 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7477 if (--idx < 0 && pathopt == NULL) {
7478 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7479 if (errno != ENOENT && errno != ENOTDIR)
7486 /* Map to POSIX errors */
7498 exitstatus = exerrno;
7499 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7500 argv[0], e, suppress_int));
7501 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7506 printentry(struct tblentry *cmdp)
7512 idx = cmdp->param.index;
7515 name = path_advance(&path, cmdp->cmdname);
7517 } while (--idx >= 0);
7518 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7522 * Clear out command entries. The argument specifies the first entry in
7523 * PATH which has changed.
7526 clearcmdentry(int firstchange)
7528 struct tblentry **tblp;
7529 struct tblentry **pp;
7530 struct tblentry *cmdp;
7533 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7535 while ((cmdp = *pp) != NULL) {
7536 if ((cmdp->cmdtype == CMDNORMAL &&
7537 cmdp->param.index >= firstchange)
7538 || (cmdp->cmdtype == CMDBUILTIN &&
7539 builtinloc >= firstchange)
7552 * Locate a command in the command hash table. If "add" is nonzero,
7553 * add the command to the table if it is not already present. The
7554 * variable "lastcmdentry" is set to point to the address of the link
7555 * pointing to the entry, so that delete_cmd_entry can delete the
7558 * Interrupts must be off if called with add != 0.
7560 static struct tblentry **lastcmdentry;
7562 static struct tblentry *
7563 cmdlookup(const char *name, int add)
7565 unsigned int hashval;
7567 struct tblentry *cmdp;
7568 struct tblentry **pp;
7571 hashval = (unsigned char)*p << 4;
7573 hashval += (unsigned char)*p++;
7575 pp = &cmdtable[hashval % CMDTABLESIZE];
7576 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7577 if (strcmp(cmdp->cmdname, name) == 0)
7581 if (add && cmdp == NULL) {
7582 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7584 /* + 1 - already done because
7585 * tblentry::cmdname is char[1] */);
7586 /*cmdp->next = NULL; - ckzalloc did it */
7587 cmdp->cmdtype = CMDUNKNOWN;
7588 strcpy(cmdp->cmdname, name);
7595 * Delete the command entry returned on the last lookup.
7598 delete_cmd_entry(void)
7600 struct tblentry *cmdp;
7603 cmdp = *lastcmdentry;
7604 *lastcmdentry = cmdp->next;
7605 if (cmdp->cmdtype == CMDFUNCTION)
7606 freefunc(cmdp->param.func);
7612 * Add a new command entry, replacing any existing command entry for
7613 * the same name - except special builtins.
7616 addcmdentry(char *name, struct cmdentry *entry)
7618 struct tblentry *cmdp;
7620 cmdp = cmdlookup(name, 1);
7621 if (cmdp->cmdtype == CMDFUNCTION) {
7622 freefunc(cmdp->param.func);
7624 cmdp->cmdtype = entry->cmdtype;
7625 cmdp->param = entry->u;
7629 static int FAST_FUNC
7630 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7632 struct tblentry **pp;
7633 struct tblentry *cmdp;
7635 struct cmdentry entry;
7638 if (nextopt("r") != '\0') {
7643 if (*argptr == NULL) {
7644 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7645 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7646 if (cmdp->cmdtype == CMDNORMAL)
7654 while ((name = *argptr) != NULL) {
7655 cmdp = cmdlookup(name, 0);
7657 && (cmdp->cmdtype == CMDNORMAL
7658 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7662 find_command(name, &entry, DO_ERR, pathval());
7663 if (entry.cmdtype == CMDUNKNOWN)
7671 * Called when a cd is done. Marks all commands so the next time they
7672 * are executed they will be rehashed.
7677 struct tblentry **pp;
7678 struct tblentry *cmdp;
7680 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7681 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7682 if (cmdp->cmdtype == CMDNORMAL
7683 || (cmdp->cmdtype == CMDBUILTIN
7684 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7694 * Fix command hash table when PATH changed.
7695 * Called before PATH is changed. The argument is the new value of PATH;
7696 * pathval() still returns the old value at this point.
7697 * Called with interrupts off.
7699 static void FAST_FUNC
7700 changepath(const char *new)
7708 firstchange = 9999; /* assume no change */
7714 if ((*old == '\0' && *new == ':')
7715 || (*old == ':' && *new == '\0')
7719 old = new; /* ignore subsequent differences */
7723 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7730 if (builtinloc < 0 && idx_bltin >= 0)
7731 builtinloc = idx_bltin; /* zap builtins */
7732 if (builtinloc >= 0 && idx_bltin < 0)
7734 clearcmdentry(firstchange);
7735 builtinloc = idx_bltin;
7750 #define TENDBQUOTE 12
7767 typedef smallint token_id_t;
7769 /* first char is indicating which tokens mark the end of a list */
7770 static const char *const tokname_array[] = {
7784 #define KWDOFFSET 13
7785 /* the following are keywords */
7804 /* Wrapper around strcmp for qsort/bsearch/... */
7806 pstrcmp(const void *a, const void *b)
7808 return strcmp((char*) a, (*(char**) b) + 1);
7811 static const char *const *
7812 findkwd(const char *s)
7814 return bsearch(s, tokname_array + KWDOFFSET,
7815 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7816 sizeof(tokname_array[0]), pstrcmp);
7820 * Locate and print what a word is...
7823 describe_command(char *command, int describe_command_verbose)
7825 struct cmdentry entry;
7826 struct tblentry *cmdp;
7827 #if ENABLE_ASH_ALIAS
7828 const struct alias *ap;
7830 const char *path = pathval();
7832 if (describe_command_verbose) {
7836 /* First look at the keywords */
7837 if (findkwd(command)) {
7838 out1str(describe_command_verbose ? " is a shell keyword" : command);
7842 #if ENABLE_ASH_ALIAS
7843 /* Then look at the aliases */
7844 ap = lookupalias(command, 0);
7846 if (!describe_command_verbose) {
7851 out1fmt(" is an alias for %s", ap->val);
7855 /* Then check if it is a tracked alias */
7856 cmdp = cmdlookup(command, 0);
7858 entry.cmdtype = cmdp->cmdtype;
7859 entry.u = cmdp->param;
7861 /* Finally use brute force */
7862 find_command(command, &entry, DO_ABS, path);
7865 switch (entry.cmdtype) {
7867 int j = entry.u.index;
7873 p = path_advance(&path, command);
7877 if (describe_command_verbose) {
7879 (cmdp ? " a tracked alias for" : nullstr), p
7888 if (describe_command_verbose) {
7889 out1str(" is a shell function");
7896 if (describe_command_verbose) {
7897 out1fmt(" is a %sshell builtin",
7898 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7899 "special " : nullstr
7907 if (describe_command_verbose) {
7908 out1str(": not found\n");
7917 static int FAST_FUNC
7918 typecmd(int argc UNUSED_PARAM, char **argv)
7924 /* type -p ... ? (we don't bother checking for 'p') */
7925 if (argv[1] && argv[1][0] == '-') {
7930 err |= describe_command(argv[i++], verbose);
7935 #if ENABLE_ASH_CMDCMD
7936 static int FAST_FUNC
7937 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7945 while ((c = nextopt("pvV")) != '\0')
7947 verify |= VERIFY_VERBOSE;
7949 verify |= VERIFY_BRIEF;
7954 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7955 if (verify && (*argptr != NULL)) {
7956 return describe_command(*argptr, verify - VERIFY_BRIEF);
7964 /* ============ eval.c */
7966 static int funcblocksize; /* size of structures in function */
7967 static int funcstringsize; /* size of strings in node */
7968 static void *funcblock; /* block to allocate function from */
7969 static char *funcstring; /* block to allocate strings from */
7971 /* flags in argument to evaltree */
7972 #define EV_EXIT 01 /* exit after evaluating tree */
7973 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7974 #define EV_BACKCMD 04 /* command executing within back quotes */
7976 static const uint8_t nodesize[N_NUMBER] = {
7977 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7978 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7979 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7980 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7981 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7982 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7983 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7984 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7985 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7986 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7987 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7988 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7989 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7990 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7991 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7992 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7993 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7994 #if ENABLE_ASH_BASH_COMPAT
7995 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7997 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7998 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7999 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8000 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8001 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8002 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8003 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8004 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8005 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8008 static void calcsize(union node *n);
8011 sizenodelist(struct nodelist *lp)
8014 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8021 calcsize(union node *n)
8025 funcblocksize += nodesize[n->type];
8028 calcsize(n->ncmd.redirect);
8029 calcsize(n->ncmd.args);
8030 calcsize(n->ncmd.assign);
8033 sizenodelist(n->npipe.cmdlist);
8038 calcsize(n->nredir.redirect);
8039 calcsize(n->nredir.n);
8046 calcsize(n->nbinary.ch2);
8047 calcsize(n->nbinary.ch1);
8050 calcsize(n->nif.elsepart);
8051 calcsize(n->nif.ifpart);
8052 calcsize(n->nif.test);
8055 funcstringsize += strlen(n->nfor.var) + 1;
8056 calcsize(n->nfor.body);
8057 calcsize(n->nfor.args);
8060 calcsize(n->ncase.cases);
8061 calcsize(n->ncase.expr);
8064 calcsize(n->nclist.body);
8065 calcsize(n->nclist.pattern);
8066 calcsize(n->nclist.next);
8070 sizenodelist(n->narg.backquote);
8071 funcstringsize += strlen(n->narg.text) + 1;
8072 calcsize(n->narg.next);
8075 #if ENABLE_ASH_BASH_COMPAT
8082 calcsize(n->nfile.fname);
8083 calcsize(n->nfile.next);
8087 calcsize(n->ndup.vname);
8088 calcsize(n->ndup.next);
8092 calcsize(n->nhere.doc);
8093 calcsize(n->nhere.next);
8096 calcsize(n->nnot.com);
8102 nodeckstrdup(char *s)
8104 char *rtn = funcstring;
8106 strcpy(funcstring, s);
8107 funcstring += strlen(s) + 1;
8111 static union node *copynode(union node *);
8113 static struct nodelist *
8114 copynodelist(struct nodelist *lp)
8116 struct nodelist *start;
8117 struct nodelist **lpp;
8122 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8123 (*lpp)->n = copynode(lp->n);
8125 lpp = &(*lpp)->next;
8132 copynode(union node *n)
8139 funcblock = (char *) funcblock + nodesize[n->type];
8143 new->ncmd.redirect = copynode(n->ncmd.redirect);
8144 new->ncmd.args = copynode(n->ncmd.args);
8145 new->ncmd.assign = copynode(n->ncmd.assign);
8148 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8149 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8154 new->nredir.redirect = copynode(n->nredir.redirect);
8155 new->nredir.n = copynode(n->nredir.n);
8162 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8163 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8166 new->nif.elsepart = copynode(n->nif.elsepart);
8167 new->nif.ifpart = copynode(n->nif.ifpart);
8168 new->nif.test = copynode(n->nif.test);
8171 new->nfor.var = nodeckstrdup(n->nfor.var);
8172 new->nfor.body = copynode(n->nfor.body);
8173 new->nfor.args = copynode(n->nfor.args);
8176 new->ncase.cases = copynode(n->ncase.cases);
8177 new->ncase.expr = copynode(n->ncase.expr);
8180 new->nclist.body = copynode(n->nclist.body);
8181 new->nclist.pattern = copynode(n->nclist.pattern);
8182 new->nclist.next = copynode(n->nclist.next);
8186 new->narg.backquote = copynodelist(n->narg.backquote);
8187 new->narg.text = nodeckstrdup(n->narg.text);
8188 new->narg.next = copynode(n->narg.next);
8191 #if ENABLE_ASH_BASH_COMPAT
8198 new->nfile.fname = copynode(n->nfile.fname);
8199 new->nfile.fd = n->nfile.fd;
8200 new->nfile.next = copynode(n->nfile.next);
8204 new->ndup.vname = copynode(n->ndup.vname);
8205 new->ndup.dupfd = n->ndup.dupfd;
8206 new->ndup.fd = n->ndup.fd;
8207 new->ndup.next = copynode(n->ndup.next);
8211 new->nhere.doc = copynode(n->nhere.doc);
8212 new->nhere.fd = n->nhere.fd;
8213 new->nhere.next = copynode(n->nhere.next);
8216 new->nnot.com = copynode(n->nnot.com);
8219 new->type = n->type;
8224 * Make a copy of a parse tree.
8226 static struct funcnode *
8227 copyfunc(union node *n)
8232 funcblocksize = offsetof(struct funcnode, n);
8235 blocksize = funcblocksize;
8236 f = ckmalloc(blocksize + funcstringsize);
8237 funcblock = (char *) f + offsetof(struct funcnode, n);
8238 funcstring = (char *) f + blocksize;
8245 * Define a shell function.
8248 defun(char *name, union node *func)
8250 struct cmdentry entry;
8253 entry.cmdtype = CMDFUNCTION;
8254 entry.u.func = copyfunc(func);
8255 addcmdentry(name, &entry);
8259 /* Reasons for skipping commands (see comment on breakcmd routine) */
8260 #define SKIPBREAK (1 << 0)
8261 #define SKIPCONT (1 << 1)
8262 #define SKIPFUNC (1 << 2)
8263 #define SKIPFILE (1 << 3)
8264 #define SKIPEVAL (1 << 4)
8265 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8266 static int skipcount; /* number of levels to skip */
8267 static int funcnest; /* depth of function calls */
8268 static int loopnest; /* current loop nesting level */
8270 /* Forward decl way out to parsing code - dotrap needs it */
8271 static int evalstring(char *s, int mask);
8273 /* Called to execute a trap.
8274 * Single callsite - at the end of evaltree().
8275 * If we return non-zero, evaltree raises EXEXIT exception.
8277 * Perhaps we should avoid entering new trap handlers
8278 * while we are executing a trap handler. [is it a TODO?]
8287 savestatus = exitstatus;
8291 TRACE(("dotrap entered\n"));
8292 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8299 /* non-trapped SIGINT is handled separately by raise_interrupt,
8300 * don't upset it by resetting gotsig[SIGINT-1] */
8301 if (sig == SIGINT && !t)
8304 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8308 want_exexit = evalstring(t, SKIPEVAL);
8309 exitstatus = savestatus;
8311 TRACE(("dotrap returns %d\n", want_exexit));
8316 TRACE(("dotrap returns 0\n"));
8320 /* forward declarations - evaluation is fairly recursive business... */
8321 static void evalloop(union node *, int);
8322 static void evalfor(union node *, int);
8323 static void evalcase(union node *, int);
8324 static void evalsubshell(union node *, int);
8325 static void expredir(union node *);
8326 static void evalpipe(union node *, int);
8327 static void evalcommand(union node *, int);
8328 static int evalbltin(const struct builtincmd *, int, char **);
8329 static void prehash(union node *);
8332 * Evaluate a parse tree. The value is left in the global variable
8336 evaltree(union node *n, int flags)
8338 struct jmploc *volatile savehandler = exception_handler;
8339 struct jmploc jmploc;
8341 void (*evalfn)(union node *, int);
8345 SAVE_INT(int_level);
8348 TRACE(("evaltree(NULL) called\n"));
8351 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8353 exception_handler = &jmploc;
8355 int err = setjmp(jmploc.loc);
8357 /* if it was a signal, check for trap handlers */
8358 if (exception_type == EXSIG) {
8359 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8360 exception_type, err));
8363 /* continue on the way out */
8364 TRACE(("exception %d in evaltree, propagating err=%d\n",
8365 exception_type, err));
8366 exception_handler = savehandler;
8367 longjmp(exception_handler->loc, err);
8374 out1fmt("Node type = %d\n", n->type);
8379 evaltree(n->nnot.com, EV_TESTED);
8380 status = !exitstatus;
8383 expredir(n->nredir.redirect);
8384 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8386 evaltree(n->nredir.n, flags & EV_TESTED);
8387 status = exitstatus;
8389 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8392 evalfn = evalcommand;
8394 if (eflag && !(flags & EV_TESTED))
8406 evalfn = evalsubshell;
8419 #error NAND + 1 != NOR
8421 #if NOR + 1 != NSEMI
8422 #error NOR + 1 != NSEMI
8424 unsigned is_or = n->type - NAND;
8427 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8429 if (!exitstatus == is_or)
8442 evaltree(n->nif.test, EV_TESTED);
8445 if (exitstatus == 0) {
8449 if (n->nif.elsepart) {
8450 n = n->nif.elsepart;
8455 defun(n->narg.text, n->narg.next);
8459 exitstatus = status;
8464 exception_handler = savehandler;
8467 /* Order of checks below is important:
8468 * signal handlers trigger before exit caused by "set -e".
8470 if (pending_sig && dotrap())
8472 if (checkexit & exitstatus)
8473 evalskip |= SKIPEVAL;
8475 if (flags & EV_EXIT) {
8477 raise_exception(EXEXIT);
8480 RESTORE_INT(int_level);
8481 TRACE(("leaving evaltree (no interrupts)\n"));
8484 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8487 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8490 evalloop(union node *n, int flags)
8500 evaltree(n->nbinary.ch1, EV_TESTED);
8503 if (evalskip == SKIPCONT && --skipcount <= 0) {
8507 if (evalskip == SKIPBREAK && --skipcount <= 0)
8512 if (n->type != NWHILE)
8516 evaltree(n->nbinary.ch2, flags);
8517 status = exitstatus;
8522 exitstatus = status;
8526 evalfor(union node *n, int flags)
8528 struct arglist arglist;
8531 struct stackmark smark;
8533 setstackmark(&smark);
8534 arglist.list = NULL;
8535 arglist.lastp = &arglist.list;
8536 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8537 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8542 *arglist.lastp = NULL;
8547 for (sp = arglist.list; sp; sp = sp->next) {
8548 setvar(n->nfor.var, sp->text, 0);
8549 evaltree(n->nfor.body, flags);
8551 if (evalskip == SKIPCONT && --skipcount <= 0) {
8555 if (evalskip == SKIPBREAK && --skipcount <= 0)
8562 popstackmark(&smark);
8566 evalcase(union node *n, int flags)
8570 struct arglist arglist;
8571 struct stackmark smark;
8573 setstackmark(&smark);
8574 arglist.list = NULL;
8575 arglist.lastp = &arglist.list;
8576 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8578 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8579 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8580 if (casematch(patp, arglist.list->text)) {
8581 if (evalskip == 0) {
8582 evaltree(cp->nclist.body, flags);
8589 popstackmark(&smark);
8593 * Kick off a subshell to evaluate a tree.
8596 evalsubshell(union node *n, int flags)
8599 int backgnd = (n->type == NBACKGND);
8602 expredir(n->nredir.redirect);
8603 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8606 jp = makejob(/*n,*/ 1);
8607 if (forkshell(jp, n, backgnd) == 0) {
8612 flags &= ~EV_TESTED;
8614 redirect(n->nredir.redirect, 0);
8615 evaltreenr(n->nredir.n, flags);
8620 status = waitforjob(jp);
8621 exitstatus = status;
8626 * Compute the names of the files in a redirection list.
8628 static void fixredir(union node *, const char *, int);
8630 expredir(union node *n)
8634 for (redir = n; redir; redir = redir->nfile.next) {
8638 fn.lastp = &fn.list;
8639 switch (redir->type) {
8643 #if ENABLE_ASH_BASH_COMPAT
8648 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8649 #if ENABLE_ASH_BASH_COMPAT
8652 redir->nfile.expfname = fn.list->text;
8655 case NTOFD: /* >& */
8656 if (redir->ndup.vname) {
8657 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8658 if (fn.list == NULL)
8659 ash_msg_and_raise_error("redir error");
8660 #if ENABLE_ASH_BASH_COMPAT
8661 //FIXME: we used expandarg with different args!
8662 if (!isdigit_str9(fn.list->text)) {
8663 /* >&file, not >&fd */
8664 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8665 ash_msg_and_raise_error("redir error");
8667 goto store_expfname;
8670 fixredir(redir, fn.list->text, 1);
8678 * Evaluate a pipeline. All the processes in the pipeline are children
8679 * of the process creating the pipeline. (This differs from some versions
8680 * of the shell, which make the last process in a pipeline the parent
8684 evalpipe(union node *n, int flags)
8687 struct nodelist *lp;
8692 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8694 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8698 jp = makejob(/*n,*/ pipelen);
8700 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8704 if (pipe(pip) < 0) {
8706 ash_msg_and_raise_error("pipe call failed");
8709 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8722 evaltreenr(lp->n, flags);
8728 /* Don't want to trigger debugging */
8732 if (n->npipe.pipe_backgnd == 0) {
8733 exitstatus = waitforjob(jp);
8734 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8740 * Controls whether the shell is interactive or not.
8743 setinteractive(int on)
8745 static smallint is_interactive;
8747 if (++on == is_interactive)
8749 is_interactive = on;
8753 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8754 if (is_interactive > 1) {
8755 /* Looks like they want an interactive shell */
8756 static smallint did_banner;
8759 /* note: ash and hush share this string */
8760 out1fmt("\n\n%s %s\n"
8761 "Enter 'help' for a list of built-in commands."
8764 "built-in shell (ash)"
8778 setinteractive(iflag);
8780 #if ENABLE_FEATURE_EDITING_VI
8782 line_input_state->flags |= VI_MODE;
8784 line_input_state->flags &= ~VI_MODE;
8786 viflag = 0; /* forcibly keep the option off */
8790 static struct localvar *localvars;
8793 * Called after a function returns.
8794 * Interrupts must be off.
8799 struct localvar *lvp;
8802 while ((lvp = localvars) != NULL) {
8803 localvars = lvp->next;
8805 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8806 if (vp == NULL) { /* $- saved */
8807 memcpy(optlist, lvp->text, sizeof(optlist));
8808 free((char*)lvp->text);
8810 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8811 unsetvar(vp->var_text);
8814 vp->var_func(var_end(lvp->text));
8815 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8816 free((char*)vp->var_text);
8817 vp->flags = lvp->flags;
8818 vp->var_text = lvp->text;
8825 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8827 volatile struct shparam saveparam;
8828 struct localvar *volatile savelocalvars;
8829 struct jmploc *volatile savehandler;
8830 struct jmploc jmploc;
8833 saveparam = shellparam;
8834 savelocalvars = localvars;
8835 e = setjmp(jmploc.loc);
8840 savehandler = exception_handler;
8841 exception_handler = &jmploc;
8843 shellparam.malloced = 0;
8847 shellparam.nparam = argc - 1;
8848 shellparam.p = argv + 1;
8849 #if ENABLE_ASH_GETOPTS
8850 shellparam.optind = 1;
8851 shellparam.optoff = -1;
8853 evaltree(&func->n, flags & EV_TESTED);
8859 localvars = savelocalvars;
8860 freeparam(&shellparam);
8861 shellparam = saveparam;
8862 exception_handler = savehandler;
8864 evalskip &= ~SKIPFUNC;
8868 #if ENABLE_ASH_CMDCMD
8870 parse_command_args(char **argv, const char **path)
8883 if (c == '-' && !*cp) {
8890 *path = bb_default_path;
8893 /* run 'typecmd' for other options */
8904 * Make a variable a local variable. When a variable is made local, it's
8905 * value and flags are saved in a localvar structure. The saved values
8906 * will be restored when the shell function returns. We handle the name
8907 * "-" as a special case.
8912 struct localvar *lvp;
8917 lvp = ckzalloc(sizeof(struct localvar));
8918 if (LONE_DASH(name)) {
8920 p = ckmalloc(sizeof(optlist));
8921 lvp->text = memcpy(p, optlist, sizeof(optlist));
8926 vpp = hashvar(name);
8927 vp = *findvar(vpp, name);
8928 eq = strchr(name, '=');
8931 setvareq(name, VSTRFIXED);
8933 setvar(name, NULL, VSTRFIXED);
8934 vp = *vpp; /* the new variable */
8935 lvp->flags = VUNSET;
8937 lvp->text = vp->var_text;
8938 lvp->flags = vp->flags;
8939 vp->flags |= VSTRFIXED|VTEXTFIXED;
8945 lvp->next = localvars;
8951 * The "local" command.
8953 static int FAST_FUNC
8954 localcmd(int argc UNUSED_PARAM, char **argv)
8959 while ((name = *argv++) != NULL) {
8965 static int FAST_FUNC
8966 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8971 static int FAST_FUNC
8972 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8977 static int FAST_FUNC
8978 execcmd(int argc UNUSED_PARAM, char **argv)
8981 iflag = 0; /* exit on error */
8984 shellexec(argv + 1, pathval(), 0);
8990 * The return command.
8992 static int FAST_FUNC
8993 returncmd(int argc UNUSED_PARAM, char **argv)
8996 * If called outside a function, do what ksh does;
8997 * skip the rest of the file.
8999 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
9000 return argv[1] ? number(argv[1]) : exitstatus;
9003 /* Forward declarations for builtintab[] */
9004 static int breakcmd(int, char **) FAST_FUNC;
9005 static int dotcmd(int, char **) FAST_FUNC;
9006 static int evalcmd(int, char **) FAST_FUNC;
9007 static int exitcmd(int, char **) FAST_FUNC;
9008 static int exportcmd(int, char **) FAST_FUNC;
9009 #if ENABLE_ASH_GETOPTS
9010 static int getoptscmd(int, char **) FAST_FUNC;
9012 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9013 static int helpcmd(int, char **) FAST_FUNC;
9015 #if ENABLE_SH_MATH_SUPPORT
9016 static int letcmd(int, char **) FAST_FUNC;
9018 static int readcmd(int, char **) FAST_FUNC;
9019 static int setcmd(int, char **) FAST_FUNC;
9020 static int shiftcmd(int, char **) FAST_FUNC;
9021 static int timescmd(int, char **) FAST_FUNC;
9022 static int trapcmd(int, char **) FAST_FUNC;
9023 static int umaskcmd(int, char **) FAST_FUNC;
9024 static int unsetcmd(int, char **) FAST_FUNC;
9025 static int ulimitcmd(int, char **) FAST_FUNC;
9027 #define BUILTIN_NOSPEC "0"
9028 #define BUILTIN_SPECIAL "1"
9029 #define BUILTIN_REGULAR "2"
9030 #define BUILTIN_SPEC_REG "3"
9031 #define BUILTIN_ASSIGN "4"
9032 #define BUILTIN_SPEC_ASSG "5"
9033 #define BUILTIN_REG_ASSG "6"
9034 #define BUILTIN_SPEC_REG_ASSG "7"
9036 /* Stubs for calling non-FAST_FUNC's */
9037 #if ENABLE_ASH_BUILTIN_ECHO
9038 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9040 #if ENABLE_ASH_BUILTIN_PRINTF
9041 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9043 #if ENABLE_ASH_BUILTIN_TEST
9044 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9047 /* Keep these in proper order since it is searched via bsearch() */
9048 static const struct builtincmd builtintab[] = {
9049 { BUILTIN_SPEC_REG "." , dotcmd },
9050 { BUILTIN_SPEC_REG ":" , truecmd },
9051 #if ENABLE_ASH_BUILTIN_TEST
9052 { BUILTIN_REGULAR "[" , testcmd },
9053 #if ENABLE_ASH_BASH_COMPAT
9054 { BUILTIN_REGULAR "[[" , testcmd },
9057 #if ENABLE_ASH_ALIAS
9058 { BUILTIN_REG_ASSG "alias" , aliascmd },
9061 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9063 { BUILTIN_SPEC_REG "break" , breakcmd },
9064 { BUILTIN_REGULAR "cd" , cdcmd },
9065 { BUILTIN_NOSPEC "chdir" , cdcmd },
9066 #if ENABLE_ASH_CMDCMD
9067 { BUILTIN_REGULAR "command" , commandcmd },
9069 { BUILTIN_SPEC_REG "continue", breakcmd },
9070 #if ENABLE_ASH_BUILTIN_ECHO
9071 { BUILTIN_REGULAR "echo" , echocmd },
9073 { BUILTIN_SPEC_REG "eval" , evalcmd },
9074 { BUILTIN_SPEC_REG "exec" , execcmd },
9075 { BUILTIN_SPEC_REG "exit" , exitcmd },
9076 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9077 { BUILTIN_REGULAR "false" , falsecmd },
9079 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9081 #if ENABLE_ASH_GETOPTS
9082 { BUILTIN_REGULAR "getopts" , getoptscmd },
9084 { BUILTIN_NOSPEC "hash" , hashcmd },
9085 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9086 { BUILTIN_NOSPEC "help" , helpcmd },
9089 { BUILTIN_REGULAR "jobs" , jobscmd },
9090 { BUILTIN_REGULAR "kill" , killcmd },
9092 #if ENABLE_SH_MATH_SUPPORT
9093 { BUILTIN_NOSPEC "let" , letcmd },
9095 { BUILTIN_ASSIGN "local" , localcmd },
9096 #if ENABLE_ASH_BUILTIN_PRINTF
9097 { BUILTIN_REGULAR "printf" , printfcmd },
9099 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9100 { BUILTIN_REGULAR "read" , readcmd },
9101 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9102 { BUILTIN_SPEC_REG "return" , returncmd },
9103 { BUILTIN_SPEC_REG "set" , setcmd },
9104 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9105 #if ENABLE_ASH_BASH_COMPAT
9106 { BUILTIN_SPEC_REG "source" , dotcmd },
9108 #if ENABLE_ASH_BUILTIN_TEST
9109 { BUILTIN_REGULAR "test" , testcmd },
9111 { BUILTIN_SPEC_REG "times" , timescmd },
9112 { BUILTIN_SPEC_REG "trap" , trapcmd },
9113 { BUILTIN_REGULAR "true" , truecmd },
9114 { BUILTIN_NOSPEC "type" , typecmd },
9115 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9116 { BUILTIN_REGULAR "umask" , umaskcmd },
9117 #if ENABLE_ASH_ALIAS
9118 { BUILTIN_REGULAR "unalias" , unaliascmd },
9120 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9121 { BUILTIN_REGULAR "wait" , waitcmd },
9124 /* Should match the above table! */
9125 #define COMMANDCMD (builtintab + \
9127 1 * ENABLE_ASH_BUILTIN_TEST + \
9128 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9129 1 * ENABLE_ASH_ALIAS + \
9130 1 * ENABLE_ASH_JOB_CONTROL + \
9132 #define EXECCMD (builtintab + \
9134 1 * ENABLE_ASH_BUILTIN_TEST + \
9135 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9136 1 * ENABLE_ASH_ALIAS + \
9137 1 * ENABLE_ASH_JOB_CONTROL + \
9139 1 * ENABLE_ASH_CMDCMD + \
9141 ENABLE_ASH_BUILTIN_ECHO + \
9145 * Search the table of builtin commands.
9147 static struct builtincmd *
9148 find_builtin(const char *name)
9150 struct builtincmd *bp;
9153 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9160 * Execute a simple command.
9163 isassignment(const char *p)
9165 const char *q = endofname(p);
9170 static int FAST_FUNC
9171 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9173 /* Preserve exitstatus of a previous possible redirection
9174 * as POSIX mandates */
9175 return back_exitstatus;
9178 evalcommand(union node *cmd, int flags)
9180 static const struct builtincmd null_bltin = {
9181 "\0\0", bltincmd /* why three NULs? */
9183 struct stackmark smark;
9185 struct arglist arglist;
9186 struct arglist varlist;
9189 const struct strlist *sp;
9190 struct cmdentry cmdentry;
9197 struct builtincmd *bcmd;
9198 smallint cmd_is_exec;
9199 smallint pseudovarflag = 0;
9201 /* First expand the arguments. */
9202 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9203 setstackmark(&smark);
9204 back_exitstatus = 0;
9206 cmdentry.cmdtype = CMDBUILTIN;
9207 cmdentry.u.cmd = &null_bltin;
9208 varlist.lastp = &varlist.list;
9209 *varlist.lastp = NULL;
9210 arglist.lastp = &arglist.list;
9211 *arglist.lastp = NULL;
9214 if (cmd->ncmd.args) {
9215 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9216 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9219 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9220 struct strlist **spp;
9222 spp = arglist.lastp;
9223 if (pseudovarflag && isassignment(argp->narg.text))
9224 expandarg(argp, &arglist, EXP_VARTILDE);
9226 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9228 for (sp = *spp; sp; sp = sp->next)
9232 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9233 for (sp = arglist.list; sp; sp = sp->next) {
9234 TRACE(("evalcommand arg: %s\n", sp->text));
9235 *nargv++ = sp->text;
9240 if (iflag && funcnest == 0 && argc > 0)
9241 lastarg = nargv[-1];
9244 expredir(cmd->ncmd.redirect);
9245 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9247 path = vpath.var_text;
9248 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9249 struct strlist **spp;
9252 spp = varlist.lastp;
9253 expandarg(argp, &varlist, EXP_VARTILDE);
9256 * Modify the command lookup path, if a PATH= assignment
9260 if (varcmp(p, path) == 0)
9264 /* Print the command if xflag is set. */
9267 const char *p = " %s" + 1;
9269 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9271 for (n = 0; n < 2; n++) {
9273 fdprintf(preverrout_fd, p, sp->text);
9279 safe_write(preverrout_fd, "\n", 1);
9285 /* Now locate the command. */
9287 const char *oldpath;
9288 int cmd_flag = DO_ERR;
9293 find_command(argv[0], &cmdentry, cmd_flag, path);
9294 if (cmdentry.cmdtype == CMDUNKNOWN) {
9295 flush_stdout_stderr();
9300 /* implement bltin and command here */
9301 if (cmdentry.cmdtype != CMDBUILTIN)
9304 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9305 if (cmdentry.u.cmd == EXECCMD)
9307 #if ENABLE_ASH_CMDCMD
9308 if (cmdentry.u.cmd == COMMANDCMD) {
9310 nargv = parse_command_args(argv, &path);
9313 argc -= nargv - argv;
9315 cmd_flag |= DO_NOFUNC;
9323 /* We have a redirection error. */
9325 raise_exception(EXERROR);
9327 exitstatus = status;
9331 /* Execute the command. */
9332 switch (cmdentry.cmdtype) {
9335 #if ENABLE_FEATURE_SH_NOFORK
9336 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9337 * around run_nofork_applet() call.
9338 * (2) Should this check also be done in forkshell()?
9339 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9341 /* find_command() encodes applet_no as (-2 - applet_no) */
9342 int applet_no = (- cmdentry.u.index - 2);
9343 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9344 listsetvar(varlist.list, VEXPORT|VSTACK);
9345 /* run <applet>_main() */
9346 exitstatus = run_nofork_applet(applet_no, argv);
9350 /* Can we avoid forking off? For example, very last command
9351 * in a script or a subshell does not need forking,
9352 * we can just exec it.
9354 if (!(flags & EV_EXIT) || may_have_traps) {
9355 /* No, forking off a child is necessary */
9357 jp = makejob(/*cmd,*/ 1);
9358 if (forkshell(jp, cmd, FORK_FG) != 0) {
9360 exitstatus = waitforjob(jp);
9362 TRACE(("forked child exited with %d\n", exitstatus));
9367 /* fall through to exec'ing external program */
9369 listsetvar(varlist.list, VEXPORT|VSTACK);
9370 shellexec(argv, path, cmdentry.u.index);
9374 cmdenviron = varlist.list;
9376 struct strlist *list = cmdenviron;
9378 if (spclbltin > 0 || argc == 0) {
9380 if (cmd_is_exec && argc > 1)
9383 listsetvar(list, i);
9385 /* Tight loop with builtins only:
9386 * "while kill -0 $child; do true; done"
9387 * will never exit even if $child died, unless we do this
9388 * to reap the zombie and make kill detect that it's gone: */
9389 dowait(DOWAIT_NONBLOCK, NULL);
9391 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9393 int i = exception_type;
9398 exit_status = 128 + SIGINT;
9400 exit_status = 128 + pending_sig;
9401 exitstatus = exit_status;
9402 if (i == EXINT || spclbltin > 0) {
9404 longjmp(exception_handler->loc, 1);
9411 listsetvar(varlist.list, 0);
9412 /* See above for the rationale */
9413 dowait(DOWAIT_NONBLOCK, NULL);
9414 if (evalfun(cmdentry.u.func, argc, argv, flags))
9421 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9423 /* dsl: I think this is intended to be used to support
9424 * '_' in 'vi' command mode during line editing...
9425 * However I implemented that within libedit itself.
9427 setvar("_", lastarg, 0);
9429 popstackmark(&smark);
9433 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9435 char *volatile savecmdname;
9436 struct jmploc *volatile savehandler;
9437 struct jmploc jmploc;
9440 savecmdname = commandname;
9441 i = setjmp(jmploc.loc);
9444 savehandler = exception_handler;
9445 exception_handler = &jmploc;
9446 commandname = argv[0];
9448 optptr = NULL; /* initialize nextopt */
9449 exitstatus = (*cmd->builtin)(argc, argv);
9450 flush_stdout_stderr();
9452 exitstatus |= ferror(stdout);
9454 commandname = savecmdname;
9455 exception_handler = savehandler;
9461 goodname(const char *p)
9463 return endofname(p)[0] == '\0';
9468 * Search for a command. This is called before we fork so that the
9469 * location of the command will be available in the parent as well as
9470 * the child. The check for "goodname" is an overly conservative
9471 * check that the name will not be subject to expansion.
9474 prehash(union node *n)
9476 struct cmdentry entry;
9478 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9479 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9483 /* ============ Builtin commands
9485 * Builtin commands whose functions are closely tied to evaluation
9486 * are implemented here.
9490 * Handle break and continue commands. Break, continue, and return are
9491 * all handled by setting the evalskip flag. The evaluation routines
9492 * above all check this flag, and if it is set they start skipping
9493 * commands rather than executing them. The variable skipcount is
9494 * the number of loops to break/continue, or the number of function
9495 * levels to return. (The latter is always 1.) It should probably
9496 * be an error to break out of more loops than exist, but it isn't
9497 * in the standard shell so we don't make it one here.
9499 static int FAST_FUNC
9500 breakcmd(int argc UNUSED_PARAM, char **argv)
9502 int n = argv[1] ? number(argv[1]) : 1;
9505 ash_msg_and_raise_error(msg_illnum, argv[1]);
9509 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9516 /* ============ input.c
9518 * This implements the input routines used by the parser.
9522 INPUT_PUSH_FILE = 1,
9523 INPUT_NOFILE_OK = 2,
9526 static smallint checkkwd;
9527 /* values of checkkwd variable */
9528 #define CHKALIAS 0x1
9533 * Push a string back onto the input at this current parsefile level.
9534 * We handle aliases this way.
9536 #if !ENABLE_ASH_ALIAS
9537 #define pushstring(s, ap) pushstring(s)
9540 pushstring(char *s, struct alias *ap)
9547 if (g_parsefile->strpush) {
9548 sp = ckzalloc(sizeof(*sp));
9549 sp->prev = g_parsefile->strpush;
9551 sp = &(g_parsefile->basestrpush);
9553 g_parsefile->strpush = sp;
9554 sp->prev_string = g_parsefile->next_to_pgetc;
9555 sp->prev_left_in_line = g_parsefile->left_in_line;
9556 #if ENABLE_ASH_ALIAS
9559 ap->flag |= ALIASINUSE;
9563 g_parsefile->next_to_pgetc = s;
9564 g_parsefile->left_in_line = len;
9571 struct strpush *sp = g_parsefile->strpush;
9574 #if ENABLE_ASH_ALIAS
9576 if (g_parsefile->next_to_pgetc[-1] == ' '
9577 || g_parsefile->next_to_pgetc[-1] == '\t'
9579 checkkwd |= CHKALIAS;
9581 if (sp->string != sp->ap->val) {
9584 sp->ap->flag &= ~ALIASINUSE;
9585 if (sp->ap->flag & ALIASDEAD) {
9586 unalias(sp->ap->name);
9590 g_parsefile->next_to_pgetc = sp->prev_string;
9591 g_parsefile->left_in_line = sp->prev_left_in_line;
9592 g_parsefile->strpush = sp->prev;
9593 if (sp != &(g_parsefile->basestrpush))
9598 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9599 //it peeks whether it is &>, and then pushes back both chars.
9600 //This function needs to save last *next_to_pgetc to buf[0]
9601 //to make two pungetc() reliable. Currently,
9602 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9607 char *buf = g_parsefile->buf;
9609 g_parsefile->next_to_pgetc = buf;
9610 #if ENABLE_FEATURE_EDITING
9612 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9613 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9616 # if ENABLE_ASH_IDLE_TIMEOUT
9618 const char *tmout_var = lookupvar("TMOUT");
9620 timeout = atoi(tmout_var) * 1000;
9626 # if ENABLE_FEATURE_TAB_COMPLETION
9627 line_input_state->path_lookup = pathval();
9629 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9631 /* Ctrl+C pressed */
9642 /* Ctrl+D pressed */
9645 # if ENABLE_ASH_IDLE_TIMEOUT
9646 else if (errno == EAGAIN && timeout > 0) {
9647 printf("\007timed out waiting for input: auto-logout\n");
9654 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9657 #if 0 /* disabled: nonblock_safe_read() handles this problem */
9659 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9660 int flags = fcntl(0, F_GETFL);
9661 if (flags >= 0 && (flags & O_NONBLOCK)) {
9662 flags &= ~O_NONBLOCK;
9663 if (fcntl(0, F_SETFL, flags) >= 0) {
9664 out2str("sh: turning off NDELAY mode\n");
9675 * Refill the input buffer and return the next input character:
9677 * 1) If a string was pushed back on the input, pop it;
9678 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9679 * or we are reading from a string so we can't refill the buffer,
9681 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9682 * 4) Process input up to the next newline, deleting nul characters.
9684 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9685 #define pgetc_debug(...) ((void)0)
9692 while (g_parsefile->strpush) {
9693 #if ENABLE_ASH_ALIAS
9694 if (g_parsefile->left_in_line == -1
9695 && g_parsefile->strpush->ap
9696 && g_parsefile->next_to_pgetc[-1] != ' '
9697 && g_parsefile->next_to_pgetc[-1] != '\t'
9699 pgetc_debug("preadbuffer PEOA");
9704 /* try "pgetc" now: */
9705 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9706 g_parsefile->left_in_line,
9707 g_parsefile->next_to_pgetc,
9708 g_parsefile->next_to_pgetc);
9709 if (--g_parsefile->left_in_line >= 0)
9710 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9712 /* on both branches above g_parsefile->left_in_line < 0.
9713 * "pgetc" needs refilling.
9716 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9717 * pungetc() may increment it a few times.
9718 * Assuming it won't increment it to less than -90.
9720 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9721 pgetc_debug("preadbuffer PEOF1");
9722 /* even in failure keep left_in_line and next_to_pgetc
9723 * in lock step, for correct multi-layer pungetc.
9724 * left_in_line was decremented before preadbuffer(),
9725 * must inc next_to_pgetc: */
9726 g_parsefile->next_to_pgetc++;
9730 more = g_parsefile->left_in_buffer;
9732 flush_stdout_stderr();
9736 /* don't try reading again */
9737 g_parsefile->left_in_line = -99;
9738 pgetc_debug("preadbuffer PEOF2");
9739 g_parsefile->next_to_pgetc++;
9744 /* Find out where's the end of line.
9745 * Set g_parsefile->left_in_line
9746 * and g_parsefile->left_in_buffer acordingly.
9747 * NUL chars are deleted.
9749 q = g_parsefile->next_to_pgetc;
9757 memmove(q, q + 1, more);
9761 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9767 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9768 if (g_parsefile->left_in_line < 0)
9773 g_parsefile->left_in_buffer = more;
9778 out2str(g_parsefile->next_to_pgetc);
9782 pgetc_debug("preadbuffer at %d:%p'%s'",
9783 g_parsefile->left_in_line,
9784 g_parsefile->next_to_pgetc,
9785 g_parsefile->next_to_pgetc);
9786 return (unsigned char)*g_parsefile->next_to_pgetc++;
9789 #define pgetc_as_macro() \
9790 (--g_parsefile->left_in_line >= 0 \
9791 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9798 pgetc_debug("pgetc_fast at %d:%p'%s'",
9799 g_parsefile->left_in_line,
9800 g_parsefile->next_to_pgetc,
9801 g_parsefile->next_to_pgetc);
9802 return pgetc_as_macro();
9805 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9806 # define pgetc_fast() pgetc()
9808 # define pgetc_fast() pgetc_as_macro()
9811 #if ENABLE_ASH_ALIAS
9813 pgetc_without_PEOA(void)
9817 pgetc_debug("pgetc_fast at %d:%p'%s'",
9818 g_parsefile->left_in_line,
9819 g_parsefile->next_to_pgetc,
9820 g_parsefile->next_to_pgetc);
9822 } while (c == PEOA);
9826 # define pgetc_without_PEOA() pgetc()
9830 * Read a line from the script.
9833 pfgets(char *line, int len)
9839 while (--nleft > 0) {
9840 c = pgetc_without_PEOA();
9855 * Undo the last call to pgetc. Only one character may be pushed back.
9856 * PEOF may be pushed back.
9861 g_parsefile->left_in_line++;
9862 g_parsefile->next_to_pgetc--;
9863 pgetc_debug("pushed back to %d:%p'%s'",
9864 g_parsefile->left_in_line,
9865 g_parsefile->next_to_pgetc,
9866 g_parsefile->next_to_pgetc);
9870 * To handle the "." command, a stack of input files is used. Pushfile
9871 * adds a new entry to the stack and popfile restores the previous level.
9876 struct parsefile *pf;
9878 pf = ckzalloc(sizeof(*pf));
9879 pf->prev = g_parsefile;
9881 /*pf->strpush = NULL; - ckzalloc did it */
9882 /*pf->basestrpush.prev = NULL;*/
9889 struct parsefile *pf = g_parsefile;
9897 g_parsefile = pf->prev;
9903 * Return to top level.
9908 while (g_parsefile != &basepf)
9913 * Close the file(s) that the shell is reading commands from. Called
9914 * after a fork is done.
9920 if (g_parsefile->pf_fd > 0) {
9921 close(g_parsefile->pf_fd);
9922 g_parsefile->pf_fd = 0;
9927 * Like setinputfile, but takes an open file descriptor. Call this with
9931 setinputfd(int fd, int push)
9933 close_on_exec_on(fd);
9936 g_parsefile->buf = NULL;
9938 g_parsefile->pf_fd = fd;
9939 if (g_parsefile->buf == NULL)
9940 g_parsefile->buf = ckmalloc(IBUFSIZ);
9941 g_parsefile->left_in_buffer = 0;
9942 g_parsefile->left_in_line = 0;
9943 g_parsefile->linno = 1;
9947 * Set the input to take input from a file. If push is set, push the
9948 * old input onto the stack first.
9951 setinputfile(const char *fname, int flags)
9957 fd = open(fname, O_RDONLY);
9959 if (flags & INPUT_NOFILE_OK)
9961 ash_msg_and_raise_error("can't open '%s'", fname);
9964 fd2 = copyfd(fd, 10);
9967 ash_msg_and_raise_error("out of file descriptors");
9970 setinputfd(fd, flags & INPUT_PUSH_FILE);
9977 * Like setinputfile, but takes input from a string.
9980 setinputstring(char *string)
9984 g_parsefile->next_to_pgetc = string;
9985 g_parsefile->left_in_line = strlen(string);
9986 g_parsefile->buf = NULL;
9987 g_parsefile->linno = 1;
9992 /* ============ mail.c
9994 * Routines to check for mail.
9999 #define MAXMBOXES 10
10001 /* times of mailboxes */
10002 static time_t mailtime[MAXMBOXES];
10003 /* Set if MAIL or MAILPATH is changed. */
10004 static smallint mail_var_path_changed;
10007 * Print appropriate message(s) if mail has arrived.
10008 * If mail_var_path_changed is set,
10009 * then the value of MAIL has mail_var_path_changed,
10010 * so we just update the values.
10019 struct stackmark smark;
10022 setstackmark(&smark);
10023 mpath = mpathset() ? mpathval() : mailval();
10024 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
10025 p = path_advance(&mpath, nullstr);
10030 for (q = p; *q; q++)
10036 q[-1] = '\0'; /* delete trailing '/' */
10037 if (stat(p, &statb) < 0) {
10041 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
10044 pathopt ? pathopt : "you have mail"
10047 *mtp = statb.st_mtime;
10049 mail_var_path_changed = 0;
10050 popstackmark(&smark);
10053 static void FAST_FUNC
10054 changemail(const char *val UNUSED_PARAM)
10056 mail_var_path_changed = 1;
10059 #endif /* ASH_MAIL */
10062 /* ============ ??? */
10065 * Set the shell parameters.
10068 setparam(char **argv)
10074 for (nparam = 0; argv[nparam]; nparam++)
10076 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10078 *ap++ = ckstrdup(*argv++);
10081 freeparam(&shellparam);
10082 shellparam.malloced = 1;
10083 shellparam.nparam = nparam;
10084 shellparam.p = newparam;
10085 #if ENABLE_ASH_GETOPTS
10086 shellparam.optind = 1;
10087 shellparam.optoff = -1;
10092 * Process shell options. The global variable argptr contains a pointer
10093 * to the argument list; we advance it past the options.
10095 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10096 * For a non-interactive shell, an error condition encountered
10097 * by a special built-in ... shall cause the shell to write a diagnostic message
10098 * to standard error and exit as shown in the following table:
10099 * Error Special Built-In
10101 * Utility syntax error (option or operand error) Shall exit
10103 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10104 * we see that bash does not do that (set "finishes" with error code 1 instead,
10105 * and shell continues), and people rely on this behavior!
10107 * set -o barfoo 2>/dev/null
10110 * Oh well. Let's mimic that.
10113 plus_minus_o(char *name, int val)
10118 for (i = 0; i < NOPTS; i++) {
10119 if (strcmp(name, optnames(i)) == 0) {
10124 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10127 for (i = 0; i < NOPTS; i++) {
10129 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10131 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10137 setoption(int flag, int val)
10141 for (i = 0; i < NOPTS; i++) {
10142 if (optletters(i) == flag) {
10147 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10151 options(int cmdline)
10159 while ((p = *argptr) != NULL) {
10161 if (c != '-' && c != '+')
10164 val = 0; /* val = 0 if c == '+' */
10167 if (p[0] == '\0' || LONE_DASH(p)) {
10169 /* "-" means turn off -x and -v */
10172 /* "--" means reset params */
10173 else if (*argptr == NULL)
10176 break; /* "-" or "--" terminates options */
10179 /* first char was + or - */
10180 while ((c = *p++) != '\0') {
10181 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10182 if (c == 'c' && cmdline) {
10183 minusc = p; /* command is after shell args */
10184 } else if (c == 'o') {
10185 if (plus_minus_o(*argptr, val)) {
10186 /* it already printed err message */
10187 return 1; /* error */
10191 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10193 /* bash does not accept +-login, we also won't */
10194 } else if (cmdline && val && (c == '-')) { /* long options */
10195 if (strcmp(p, "login") == 0)
10207 * The shift builtin command.
10209 static int FAST_FUNC
10210 shiftcmd(int argc UNUSED_PARAM, char **argv)
10217 n = number(argv[1]);
10218 if (n > shellparam.nparam)
10219 n = 0; /* bash compat, was = shellparam.nparam; */
10221 shellparam.nparam -= n;
10222 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10223 if (shellparam.malloced)
10226 ap2 = shellparam.p;
10227 while ((*ap2++ = *ap1++) != NULL)
10229 #if ENABLE_ASH_GETOPTS
10230 shellparam.optind = 1;
10231 shellparam.optoff = -1;
10238 * POSIX requires that 'set' (but not export or readonly) output the
10239 * variables in lexicographic order - by the locale's collating order (sigh).
10240 * Maybe we could keep them in an ordered balanced binary tree
10241 * instead of hashed lists.
10242 * For now just roll 'em through qsort for printing...
10245 showvars(const char *sep_prefix, int on, int off)
10248 char **ep, **epend;
10250 ep = listvars(on, off, &epend);
10251 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10253 sep = *sep_prefix ? " " : sep_prefix;
10255 for (; ep < epend; ep++) {
10259 p = strchrnul(*ep, '=');
10262 q = single_quote(++p);
10263 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10269 * The set command builtin.
10271 static int FAST_FUNC
10272 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10277 return showvars(nullstr, 0, VUNSET);
10280 retval = options(/*cmdline:*/ 0);
10281 if (retval == 0) { /* if no parse error... */
10283 if (*argptr != NULL) {
10291 #if ENABLE_ASH_RANDOM_SUPPORT
10292 static void FAST_FUNC
10293 change_random(const char *value)
10297 if (value == NULL) {
10298 /* "get", generate */
10299 t = next_random(&random_gen);
10300 /* set without recursion */
10301 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10302 vrandom.flags &= ~VNOFUNC;
10305 t = strtoul(value, NULL, 10);
10306 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10311 #if ENABLE_ASH_GETOPTS
10313 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10322 if (*param_optind < 1)
10324 optnext = optfirst + *param_optind - 1;
10326 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10329 p = optnext[-1] + *optoff;
10330 if (p == NULL || *p == '\0') {
10331 /* Current word is done, advance */
10333 if (p == NULL || *p != '-' || *++p == '\0') {
10340 if (LONE_DASH(p)) /* check for "--" */
10345 for (q = optstr; *q != c;) {
10347 if (optstr[0] == ':') {
10350 err |= setvarsafe("OPTARG", s, 0);
10352 fprintf(stderr, "Illegal option -%c\n", c);
10353 unsetvar("OPTARG");
10363 if (*p == '\0' && (p = *optnext) == NULL) {
10364 if (optstr[0] == ':') {
10367 err |= setvarsafe("OPTARG", s, 0);
10370 fprintf(stderr, "No arg for -%c option\n", c);
10371 unsetvar("OPTARG");
10379 err |= setvarsafe("OPTARG", p, 0);
10382 err |= setvarsafe("OPTARG", nullstr, 0);
10384 *optoff = p ? p - *(optnext - 1) : -1;
10385 *param_optind = optnext - optfirst + 1;
10386 fmtstr(s, sizeof(s), "%d", *param_optind);
10387 err |= setvarsafe("OPTIND", s, VNOFUNC);
10390 err |= setvarsafe(optvar, s, 0);
10394 flush_stdout_stderr();
10395 raise_exception(EXERROR);
10401 * The getopts builtin. Shellparam.optnext points to the next argument
10402 * to be processed. Shellparam.optptr points to the next character to
10403 * be processed in the current argument. If shellparam.optnext is NULL,
10404 * then it's the first time getopts has been called.
10406 static int FAST_FUNC
10407 getoptscmd(int argc, char **argv)
10412 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10414 optbase = shellparam.p;
10415 if (shellparam.optind > shellparam.nparam + 1) {
10416 shellparam.optind = 1;
10417 shellparam.optoff = -1;
10420 optbase = &argv[3];
10421 if (shellparam.optind > argc - 2) {
10422 shellparam.optind = 1;
10423 shellparam.optoff = -1;
10427 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10428 &shellparam.optoff);
10430 #endif /* ASH_GETOPTS */
10433 /* ============ Shell parser */
10436 struct heredoc *next; /* next here document in list */
10437 union node *here; /* redirection node */
10438 char *eofmark; /* string indicating end of input */
10439 smallint striptabs; /* if set, strip leading tabs */
10442 static smallint tokpushback; /* last token pushed back */
10443 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10444 static smallint quoteflag; /* set if (part of) last token was quoted */
10445 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10446 static struct heredoc *heredoclist; /* list of here documents to read */
10447 static char *wordtext; /* text of last word returned by readtoken */
10448 static struct nodelist *backquotelist;
10449 static union node *redirnode;
10450 static struct heredoc *heredoc;
10452 static const char *
10453 tokname(char *buf, int tok)
10456 return tokname_array[tok] + 1;
10457 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10461 /* raise_error_unexpected_syntax:
10462 * Called when an unexpected token is read during the parse. The argument
10463 * is the token that is expected, or -1 if more than one type of token can
10464 * occur at this point.
10466 static void raise_error_unexpected_syntax(int) NORETURN;
10468 raise_error_unexpected_syntax(int token)
10474 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10476 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10477 raise_error_syntax(msg);
10481 #define EOFMARKLEN 79
10483 /* parsing is heavily cross-recursive, need these forward decls */
10484 static union node *andor(void);
10485 static union node *pipeline(void);
10486 static union node *parse_command(void);
10487 static void parseheredoc(void);
10488 static char peektoken(void);
10489 static int readtoken(void);
10491 static union node *
10494 union node *n1, *n2, *n3;
10497 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10498 if (nlflag == 2 && peektoken())
10504 if (tok == TBACKGND) {
10505 if (n2->type == NPIPE) {
10506 n2->npipe.pipe_backgnd = 1;
10508 if (n2->type != NREDIR) {
10509 n3 = stzalloc(sizeof(struct nredir));
10511 /*n3->nredir.redirect = NULL; - stzalloc did it */
10514 n2->type = NBACKGND;
10520 n3 = stzalloc(sizeof(struct nbinary));
10522 n3->nbinary.ch1 = n1;
10523 n3->nbinary.ch2 = n2;
10539 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10547 pungetc(); /* push back EOF on input */
10551 raise_error_unexpected_syntax(-1);
10558 static union node *
10561 union node *n1, *n2, *n3;
10569 } else if (t == TOR) {
10575 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10577 n3 = stzalloc(sizeof(struct nbinary));
10579 n3->nbinary.ch1 = n1;
10580 n3->nbinary.ch2 = n2;
10585 static union node *
10588 union node *n1, *n2, *pipenode;
10589 struct nodelist *lp, *prev;
10593 TRACE(("pipeline: entered\n"));
10594 if (readtoken() == TNOT) {
10596 checkkwd = CHKKWD | CHKALIAS;
10599 n1 = parse_command();
10600 if (readtoken() == TPIPE) {
10601 pipenode = stzalloc(sizeof(struct npipe));
10602 pipenode->type = NPIPE;
10603 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10604 lp = stzalloc(sizeof(struct nodelist));
10605 pipenode->npipe.cmdlist = lp;
10609 lp = stzalloc(sizeof(struct nodelist));
10610 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10611 lp->n = parse_command();
10613 } while (readtoken() == TPIPE);
10619 n2 = stzalloc(sizeof(struct nnot));
10627 static union node *
10632 n = stzalloc(sizeof(struct narg));
10634 /*n->narg.next = NULL; - stzalloc did it */
10635 n->narg.text = wordtext;
10636 n->narg.backquote = backquotelist;
10641 fixredir(union node *n, const char *text, int err)
10645 TRACE(("Fix redir %s %d\n", text, err));
10647 n->ndup.vname = NULL;
10649 fd = bb_strtou(text, NULL, 10);
10650 if (!errno && fd >= 0)
10651 n->ndup.dupfd = fd;
10652 else if (LONE_DASH(text))
10653 n->ndup.dupfd = -1;
10656 raise_error_syntax("bad fd number");
10657 n->ndup.vname = makename();
10662 * Returns true if the text contains nothing to expand (no dollar signs
10666 noexpand(const char *text)
10670 while ((c = *text++) != '\0') {
10671 if (c == CTLQUOTEMARK)
10675 else if (SIT(c, BASESYNTAX) == CCTL)
10684 union node *n = redirnode;
10686 if (readtoken() != TWORD)
10687 raise_error_unexpected_syntax(-1);
10688 if (n->type == NHERE) {
10689 struct heredoc *here = heredoc;
10693 if (quoteflag == 0)
10695 TRACE(("Here document %d\n", n->type));
10696 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10697 raise_error_syntax("illegal eof marker for << redirection");
10698 rmescapes(wordtext, 0);
10699 here->eofmark = wordtext;
10701 if (heredoclist == NULL)
10702 heredoclist = here;
10704 for (p = heredoclist; p->next; p = p->next)
10708 } else if (n->type == NTOFD || n->type == NFROMFD) {
10709 fixredir(n, wordtext, 0);
10711 n->nfile.fname = makename();
10715 static union node *
10718 union node *args, **app;
10719 union node *n = NULL;
10720 union node *vars, **vpp;
10721 union node **rpp, *redir;
10723 #if ENABLE_ASH_BASH_COMPAT
10724 smallint double_brackets_flag = 0;
10734 savecheckkwd = CHKALIAS;
10737 checkkwd = savecheckkwd;
10740 #if ENABLE_ASH_BASH_COMPAT
10741 case TAND: /* "&&" */
10742 case TOR: /* "||" */
10743 if (!double_brackets_flag) {
10747 wordtext = (char *) (t == TAND ? "-a" : "-o");
10750 n = stzalloc(sizeof(struct narg));
10752 /*n->narg.next = NULL; - stzalloc did it */
10753 n->narg.text = wordtext;
10754 #if ENABLE_ASH_BASH_COMPAT
10755 if (strcmp("[[", wordtext) == 0)
10756 double_brackets_flag = 1;
10757 else if (strcmp("]]", wordtext) == 0)
10758 double_brackets_flag = 0;
10760 n->narg.backquote = backquotelist;
10761 if (savecheckkwd && isassignment(wordtext)) {
10763 vpp = &n->narg.next;
10766 app = &n->narg.next;
10771 *rpp = n = redirnode;
10772 rpp = &n->nfile.next;
10773 parsefname(); /* read name of redirection file */
10776 if (args && app == &args->narg.next
10779 struct builtincmd *bcmd;
10782 /* We have a function */
10783 if (readtoken() != TRP)
10784 raise_error_unexpected_syntax(TRP);
10785 name = n->narg.text;
10786 if (!goodname(name)
10787 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10789 raise_error_syntax("bad function name");
10792 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10793 n->narg.next = parse_command();
10806 n = stzalloc(sizeof(struct ncmd));
10808 n->ncmd.args = args;
10809 n->ncmd.assign = vars;
10810 n->ncmd.redirect = redir;
10814 static union node *
10815 parse_command(void)
10817 union node *n1, *n2;
10818 union node *ap, **app;
10819 union node *cp, **cpp;
10820 union node *redir, **rpp;
10827 switch (readtoken()) {
10829 raise_error_unexpected_syntax(-1);
10832 n1 = stzalloc(sizeof(struct nif));
10834 n1->nif.test = list(0);
10835 if (readtoken() != TTHEN)
10836 raise_error_unexpected_syntax(TTHEN);
10837 n1->nif.ifpart = list(0);
10839 while (readtoken() == TELIF) {
10840 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10841 n2 = n2->nif.elsepart;
10843 n2->nif.test = list(0);
10844 if (readtoken() != TTHEN)
10845 raise_error_unexpected_syntax(TTHEN);
10846 n2->nif.ifpart = list(0);
10848 if (lasttoken == TELSE)
10849 n2->nif.elsepart = list(0);
10851 n2->nif.elsepart = NULL;
10859 n1 = stzalloc(sizeof(struct nbinary));
10860 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10861 n1->nbinary.ch1 = list(0);
10864 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10865 got == TWORD ? wordtext : ""));
10866 raise_error_unexpected_syntax(TDO);
10868 n1->nbinary.ch2 = list(0);
10873 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10874 raise_error_syntax("bad for loop variable");
10875 n1 = stzalloc(sizeof(struct nfor));
10877 n1->nfor.var = wordtext;
10878 checkkwd = CHKKWD | CHKALIAS;
10879 if (readtoken() == TIN) {
10881 while (readtoken() == TWORD) {
10882 n2 = stzalloc(sizeof(struct narg));
10884 /*n2->narg.next = NULL; - stzalloc did it */
10885 n2->narg.text = wordtext;
10886 n2->narg.backquote = backquotelist;
10888 app = &n2->narg.next;
10891 n1->nfor.args = ap;
10892 if (lasttoken != TNL && lasttoken != TSEMI)
10893 raise_error_unexpected_syntax(-1);
10895 n2 = stzalloc(sizeof(struct narg));
10897 /*n2->narg.next = NULL; - stzalloc did it */
10898 n2->narg.text = (char *)dolatstr;
10899 /*n2->narg.backquote = NULL;*/
10900 n1->nfor.args = n2;
10902 * Newline or semicolon here is optional (but note
10903 * that the original Bourne shell only allowed NL).
10905 if (lasttoken != TNL && lasttoken != TSEMI)
10908 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10909 if (readtoken() != TDO)
10910 raise_error_unexpected_syntax(TDO);
10911 n1->nfor.body = list(0);
10915 n1 = stzalloc(sizeof(struct ncase));
10917 if (readtoken() != TWORD)
10918 raise_error_unexpected_syntax(TWORD);
10919 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10921 /*n2->narg.next = NULL; - stzalloc did it */
10922 n2->narg.text = wordtext;
10923 n2->narg.backquote = backquotelist;
10925 checkkwd = CHKKWD | CHKALIAS;
10926 } while (readtoken() == TNL);
10927 if (lasttoken != TIN)
10928 raise_error_unexpected_syntax(TIN);
10929 cpp = &n1->ncase.cases;
10931 checkkwd = CHKNL | CHKKWD;
10933 while (t != TESAC) {
10934 if (lasttoken == TLP)
10936 *cpp = cp = stzalloc(sizeof(struct nclist));
10938 app = &cp->nclist.pattern;
10940 *app = ap = stzalloc(sizeof(struct narg));
10942 /*ap->narg.next = NULL; - stzalloc did it */
10943 ap->narg.text = wordtext;
10944 ap->narg.backquote = backquotelist;
10945 if (readtoken() != TPIPE)
10947 app = &ap->narg.next;
10950 //ap->narg.next = NULL;
10951 if (lasttoken != TRP)
10952 raise_error_unexpected_syntax(TRP);
10953 cp->nclist.body = list(2);
10955 cpp = &cp->nclist.next;
10957 checkkwd = CHKNL | CHKKWD;
10961 raise_error_unexpected_syntax(TENDCASE);
10968 n1 = stzalloc(sizeof(struct nredir));
10969 n1->type = NSUBSHELL;
10970 n1->nredir.n = list(0);
10971 /*n1->nredir.redirect = NULL; - stzalloc did it */
10981 return simplecmd();
10984 if (readtoken() != t)
10985 raise_error_unexpected_syntax(t);
10988 /* Now check for redirection which may follow command */
10989 checkkwd = CHKKWD | CHKALIAS;
10991 while (readtoken() == TREDIR) {
10992 *rpp = n2 = redirnode;
10993 rpp = &n2->nfile.next;
10999 if (n1->type != NSUBSHELL) {
11000 n2 = stzalloc(sizeof(struct nredir));
11005 n1->nredir.redirect = redir;
11010 #if ENABLE_ASH_BASH_COMPAT
11011 static int decode_dollar_squote(void)
11013 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11019 p = strchr(C_escapes, c);
11024 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11028 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11030 } else if (c == 'x') { /* \xHH */
11034 } while (isxdigit(c) && --cnt);
11036 if (cnt == 3) { /* \x but next char is "bad" */
11040 } else { /* simple seq like \\ or \t */
11045 c = bb_process_escape_sequence((void*)&p);
11046 } else { /* unrecognized "\z": print both chars unless ' or " */
11047 if (c != '\'' && c != '"') {
11049 c |= 0x100; /* "please encode \, then me" */
11057 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11058 * is not NULL, read a here document. In the latter case, eofmark is the
11059 * word which marks the end of the document and striptabs is true if
11060 * leading tabs should be stripped from the document. The argument c
11061 * is the first character of the input token or document.
11063 * Because C does not have internal subroutines, I have simulated them
11064 * using goto's to implement the subroutine linkage. The following macros
11065 * will run code that appears at the end of readtoken1.
11067 #define CHECKEND() {goto checkend; checkend_return:;}
11068 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11069 #define PARSESUB() {goto parsesub; parsesub_return:;}
11070 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11071 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11072 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11074 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11076 /* NB: syntax parameter fits into smallint */
11077 /* c parameter is an unsigned char or PEOF or PEOA */
11080 char line[EOFMARKLEN + 1];
11081 struct nodelist *bqlist;
11085 smallint prevsyntax; /* syntax before arithmetic */
11086 #if ENABLE_ASH_EXPAND_PRMT
11087 smallint pssyntax; /* we are expanding a prompt string */
11089 int varnest; /* levels of variables expansion */
11090 int arinest; /* levels of arithmetic expansion */
11091 int parenlevel; /* levels of parens in arithmetic */
11092 int dqvarnest; /* levels of variables expansion within double quotes */
11094 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11097 /* Avoid longjmp clobbering */
11103 (void) &parenlevel;
11106 (void) &prevsyntax;
11109 startlinno = g_parsefile->linno;
11113 #if ENABLE_ASH_EXPAND_PRMT
11114 pssyntax = (syntax == PSSYNTAX);
11118 dblquote = (syntax == DQSYNTAX);
11124 STARTSTACKSTR(out);
11126 /* For each line, until end of word */
11127 CHECKEND(); /* set c to PEOF if at end of here document */
11128 for (;;) { /* until end of line or end of word */
11129 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11130 switch (SIT(c, syntax)) {
11131 case CNL: /* '\n' */
11132 if (syntax == BASESYNTAX)
11133 goto endword; /* exit outer loop */
11135 g_parsefile->linno++;
11136 setprompt_if(doprompt, 2);
11138 goto loop; /* continue outer loop */
11143 if (eofmark == NULL || dblquote)
11144 USTPUTC(CTLESC, out);
11145 #if ENABLE_ASH_BASH_COMPAT
11146 if (c == '\\' && bash_dollar_squote) {
11147 c = decode_dollar_squote();
11149 USTPUTC('\\', out);
11150 c = (unsigned char)c;
11156 case CBACK: /* backslash */
11157 c = pgetc_without_PEOA();
11159 USTPUTC(CTLESC, out);
11160 USTPUTC('\\', out);
11162 } else if (c == '\n') {
11163 setprompt_if(doprompt, 2);
11165 #if ENABLE_ASH_EXPAND_PRMT
11166 if (c == '$' && pssyntax) {
11167 USTPUTC(CTLESC, out);
11168 USTPUTC('\\', out);
11171 /* Backslash is retained if we are in "str" and next char isn't special */
11176 && (c != '"' || eofmark != NULL)
11178 USTPUTC(CTLESC, out);
11179 USTPUTC('\\', out);
11181 if (SIT(c, SQSYNTAX) == CCTL)
11182 USTPUTC(CTLESC, out);
11190 if (eofmark == NULL) {
11191 USTPUTC(CTLQUOTEMARK, out);
11199 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11200 if (eofmark != NULL && arinest == 0
11205 if (dqvarnest == 0) {
11206 syntax = BASESYNTAX;
11213 case CVAR: /* '$' */
11214 PARSESUB(); /* parse substitution */
11216 case CENDVAR: /* '}' */
11219 if (dqvarnest > 0) {
11226 #if ENABLE_SH_MATH_SUPPORT
11227 case CLP: /* '(' in arithmetic */
11231 case CRP: /* ')' in arithmetic */
11232 if (parenlevel > 0) {
11235 if (pgetc() == ')') {
11236 if (--arinest == 0) {
11237 syntax = prevsyntax;
11238 dblquote = (syntax == DQSYNTAX);
11243 * unbalanced parens
11244 * (don't 2nd guess - no error)
11252 case CBQUOTE: /* '`' */
11256 goto endword; /* exit outer loop */
11260 if (varnest == 0) {
11261 #if ENABLE_ASH_BASH_COMPAT
11263 if (pgetc() == '>')
11264 c = 0x100 + '>'; /* flag &> */
11268 goto endword; /* exit outer loop */
11270 IF_ASH_ALIAS(if (c != PEOA))
11277 #if ENABLE_SH_MATH_SUPPORT
11278 if (syntax == ARISYNTAX)
11279 raise_error_syntax("missing '))'");
11281 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11282 raise_error_syntax("unterminated quoted string");
11283 if (varnest != 0) {
11284 startlinno = g_parsefile->linno;
11286 raise_error_syntax("missing '}'");
11288 USTPUTC('\0', out);
11289 len = out - (char *)stackblock();
11290 out = stackblock();
11291 if (eofmark == NULL) {
11292 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11295 if (isdigit_str9(out)) {
11296 PARSEREDIR(); /* passed as params: out, c */
11297 lasttoken = TREDIR;
11300 /* else: non-number X seen, interpret it
11301 * as "NNNX>file" = "NNNX >file" */
11305 quoteflag = quotef;
11306 backquotelist = bqlist;
11307 grabstackblock(len);
11311 /* end of readtoken routine */
11314 * Check to see whether we are at the end of the here document. When this
11315 * is called, c is set to the first character of the next input line. If
11316 * we are at the end of the here document, this routine sets the c to PEOF.
11320 #if ENABLE_ASH_ALIAS
11322 c = pgetc_without_PEOA();
11325 while (c == '\t') {
11326 c = pgetc_without_PEOA();
11329 if (c == *eofmark) {
11330 if (pfgets(line, sizeof(line)) != NULL) {
11334 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11336 if (*p == '\n' && *q == '\0') {
11338 g_parsefile->linno++;
11339 needprompt = doprompt;
11341 pushstring(line, NULL);
11346 goto checkend_return;
11350 * Parse a redirection operator. The variable "out" points to a string
11351 * specifying the fd to be redirected. The variable "c" contains the
11352 * first character of the redirection operator.
11355 /* out is already checked to be a valid number or "" */
11356 int fd = (*out == '\0' ? -1 : atoi(out));
11359 np = stzalloc(sizeof(struct nfile));
11364 np->type = NAPPEND;
11366 np->type = NCLOBBER;
11369 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11375 #if ENABLE_ASH_BASH_COMPAT
11376 else if (c == 0x100 + '>') { /* this flags &> redirection */
11378 pgetc(); /* this is '>', no need to check */
11382 else { /* c == '<' */
11383 /*np->nfile.fd = 0; - stzalloc did it */
11387 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11388 np = stzalloc(sizeof(struct nhere));
11389 /*np->nfile.fd = 0; - stzalloc did it */
11392 heredoc = stzalloc(sizeof(struct heredoc));
11393 heredoc->here = np;
11396 heredoc->striptabs = 1;
11398 /*heredoc->striptabs = 0; - stzalloc did it */
11404 np->type = NFROMFD;
11408 np->type = NFROMTO;
11420 goto parseredir_return;
11424 * Parse a substitution. At this point, we have read the dollar sign
11425 * and nothing else.
11428 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11429 * (assuming ascii char codes, as the original implementation did) */
11430 #define is_special(c) \
11431 (((unsigned)(c) - 33 < 32) \
11432 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11434 unsigned char subtype;
11439 if (c > 255 /* PEOA or PEOF */
11440 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11442 #if ENABLE_ASH_BASH_COMPAT
11444 bash_dollar_squote = 1;
11449 } else if (c == '(') {
11450 /* $(command) or $((arith)) */
11451 if (pgetc() == '(') {
11452 #if ENABLE_SH_MATH_SUPPORT
11455 raise_error_syntax("you disabled math support for $((arith)) syntax");
11462 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11463 USTPUTC(CTLVAR, out);
11464 typeloc = out - (char *)stackblock();
11465 USTPUTC(VSNORMAL, out);
11466 subtype = VSNORMAL;
11472 c = '#'; /* ${#} - same as $# */
11474 subtype = VSLENGTH; /* ${#VAR} */
11479 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11480 /* $[{[#]]NAME[}] */
11484 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11485 } else if (isdigit(c)) {
11486 /* $[{[#]]NUM[}] */
11490 } while (isdigit(c));
11491 } else if (is_special(c)) {
11492 /* $[{[#]]<specialchar>[}] */
11497 raise_error_syntax("bad substitution");
11499 if (c != '}' && subtype == VSLENGTH) {
11500 /* ${#VAR didn't end with } */
11506 if (subtype == 0) {
11507 /* ${VAR...} but not $VAR or ${#VAR} */
11508 /* c == first char after VAR */
11512 #if ENABLE_ASH_BASH_COMPAT
11513 if (c == ':' || c == '$' || isdigit(c)) {
11514 //TODO: support more general format ${v:EXPR:EXPR},
11515 // where EXPR follows $(()) rules
11516 subtype = VSSUBSTR;
11518 break; /* "goto do_pungetc" is bigger (!) */
11524 static const char types[] ALIGN1 = "}-+?=";
11525 const char *p = strchr(types, c);
11528 subtype = p - types + VSNORMAL;
11534 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11541 #if ENABLE_ASH_BASH_COMPAT
11543 /* ${v/[/]pattern/repl} */
11544 //TODO: encode pattern and repl separately.
11545 // Currently ${v/$var_with_slash/repl} is horribly broken
11546 subtype = VSREPLACE;
11550 subtype++; /* VSREPLACEALL */
11558 if (dblquote || arinest)
11560 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11561 if (subtype != VSNORMAL) {
11563 if (dblquote || arinest) {
11568 goto parsesub_return;
11572 * Called to parse command substitutions. Newstyle is set if the command
11573 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11574 * list of commands (passed by reference), and savelen is the number of
11575 * characters on the top of the stack which must be preserved.
11578 struct nodelist **nlpp;
11581 char *volatile str;
11582 struct jmploc jmploc;
11583 struct jmploc *volatile savehandler;
11585 smallint saveprompt = 0;
11588 (void) &saveprompt;
11590 savepbq = parsebackquote;
11591 if (setjmp(jmploc.loc)) {
11593 parsebackquote = 0;
11594 exception_handler = savehandler;
11595 longjmp(exception_handler->loc, 1);
11599 savelen = out - (char *)stackblock();
11601 str = ckmalloc(savelen);
11602 memcpy(str, stackblock(), savelen);
11604 savehandler = exception_handler;
11605 exception_handler = &jmploc;
11608 /* We must read until the closing backquote, giving special
11609 treatment to some slashes, and then push the string and
11610 reread it as input, interpreting it normally. */
11615 STARTSTACKSTR(pout);
11619 setprompt_if(needprompt, 2);
11628 g_parsefile->linno++;
11629 setprompt_if(doprompt, 2);
11631 * If eating a newline, avoid putting
11632 * the newline into the new character
11633 * stream (via the STPUTC after the
11638 if (pc != '\\' && pc != '`' && pc != '$'
11639 && (!dblquote || pc != '"')
11641 STPUTC('\\', pout);
11643 if (pc <= 255 /* not PEOA or PEOF */) {
11649 IF_ASH_ALIAS(case PEOA:)
11650 startlinno = g_parsefile->linno;
11651 raise_error_syntax("EOF in backquote substitution");
11654 g_parsefile->linno++;
11655 needprompt = doprompt;
11664 STPUTC('\0', pout);
11665 psavelen = pout - (char *)stackblock();
11666 if (psavelen > 0) {
11667 pstr = grabstackstr(pout);
11668 setinputstring(pstr);
11673 nlpp = &(*nlpp)->next;
11674 *nlpp = stzalloc(sizeof(**nlpp));
11675 /* (*nlpp)->next = NULL; - stzalloc did it */
11676 parsebackquote = oldstyle;
11679 saveprompt = doprompt;
11686 doprompt = saveprompt;
11687 else if (readtoken() != TRP)
11688 raise_error_unexpected_syntax(TRP);
11693 * Start reading from old file again, ignoring any pushed back
11694 * tokens left from the backquote parsing
11699 while (stackblocksize() <= savelen)
11701 STARTSTACKSTR(out);
11703 memcpy(out, str, savelen);
11704 STADJUST(savelen, out);
11710 parsebackquote = savepbq;
11711 exception_handler = savehandler;
11712 if (arinest || dblquote)
11713 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11715 USTPUTC(CTLBACKQ, out);
11717 goto parsebackq_oldreturn;
11718 goto parsebackq_newreturn;
11721 #if ENABLE_SH_MATH_SUPPORT
11723 * Parse an arithmetic expansion (indicate start of one and set state)
11726 if (++arinest == 1) {
11727 prevsyntax = syntax;
11728 syntax = ARISYNTAX;
11729 USTPUTC(CTLARI, out);
11736 * we collapse embedded arithmetic expansion to
11737 * parenthesis, which should be equivalent
11741 goto parsearith_return;
11745 } /* end of readtoken */
11748 * Read the next input token.
11749 * If the token is a word, we set backquotelist to the list of cmds in
11750 * backquotes. We set quoteflag to true if any part of the word was
11752 * If the token is TREDIR, then we set redirnode to a structure containing
11754 * In all cases, the variable startlinno is set to the number of the line
11755 * on which the token starts.
11757 * [Change comment: here documents and internal procedures]
11758 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11759 * word parsing code into a separate routine. In this case, readtoken
11760 * doesn't need to have any internal procedures, but parseword does.
11761 * We could also make parseoperator in essence the main routine, and
11762 * have parseword (readtoken1?) handle both words and redirection.]
11764 #define NEW_xxreadtoken
11765 #ifdef NEW_xxreadtoken
11766 /* singles must be first! */
11767 static const char xxreadtoken_chars[7] ALIGN1 = {
11768 '\n', '(', ')', /* singles */
11769 '&', '|', ';', /* doubles */
11773 #define xxreadtoken_singles 3
11774 #define xxreadtoken_doubles 3
11776 static const char xxreadtoken_tokens[] ALIGN1 = {
11777 TNL, TLP, TRP, /* only single occurrence allowed */
11778 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11779 TEOF, /* corresponds to trailing nul */
11780 TAND, TOR, TENDCASE /* if double occurrence */
11792 setprompt_if(needprompt, 2);
11793 startlinno = g_parsefile->linno;
11794 for (;;) { /* until token or start of word found */
11796 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11800 while ((c = pgetc()) != '\n' && c != PEOF)
11803 } else if (c == '\\') {
11804 if (pgetc() != '\n') {
11806 break; /* return readtoken1(...) */
11808 startlinno = ++g_parsefile->linno;
11809 setprompt_if(doprompt, 2);
11813 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11816 g_parsefile->linno++;
11817 needprompt = doprompt;
11820 p = strchr(xxreadtoken_chars, c);
11822 break; /* return readtoken1(...) */
11824 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11826 if (cc == c) { /* double occurrence? */
11827 p += xxreadtoken_doubles + 1;
11830 #if ENABLE_ASH_BASH_COMPAT
11831 if (c == '&' && cc == '>') /* &> */
11832 break; /* return readtoken1(...) */
11837 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11842 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11844 #else /* old xxreadtoken */
11845 #define RETURN(token) return lasttoken = token
11855 setprompt_if(needprompt, 2);
11856 startlinno = g_parsefile->linno;
11857 for (;;) { /* until token or start of word found */
11860 case ' ': case '\t':
11861 IF_ASH_ALIAS(case PEOA:)
11864 while ((c = pgetc()) != '\n' && c != PEOF)
11869 if (pgetc() == '\n') {
11870 startlinno = ++g_parsefile->linno;
11871 setprompt_if(doprompt, 2);
11877 g_parsefile->linno++;
11878 needprompt = doprompt;
11883 if (pgetc() == '&')
11888 if (pgetc() == '|')
11893 if (pgetc() == ';')
11906 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11909 #endif /* old xxreadtoken */
11916 smallint alreadyseen = tokpushback;
11919 #if ENABLE_ASH_ALIAS
11928 if (checkkwd & CHKNL) {
11935 if (t != TWORD || quoteflag) {
11940 * check for keywords
11942 if (checkkwd & CHKKWD) {
11943 const char *const *pp;
11945 pp = findkwd(wordtext);
11947 lasttoken = t = pp - tokname_array;
11948 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11953 if (checkkwd & CHKALIAS) {
11954 #if ENABLE_ASH_ALIAS
11956 ap = lookupalias(wordtext, 1);
11959 pushstring(ap->val, ap);
11969 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11971 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11983 return tokname_array[t][0];
11987 * Read and parse a command. Returns NODE_EOF on end of file.
11988 * (NULL is a valid parse tree indicating a blank line.)
11990 static union node *
11991 parsecmd(int interact)
11996 doprompt = interact;
11997 setprompt_if(doprompt, doprompt);
12009 * Input any here documents.
12014 struct heredoc *here;
12017 here = heredoclist;
12018 heredoclist = NULL;
12021 setprompt_if(needprompt, 2);
12022 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12023 here->eofmark, here->striptabs);
12024 n = stzalloc(sizeof(struct narg));
12025 n->narg.type = NARG;
12026 /*n->narg.next = NULL; - stzalloc did it */
12027 n->narg.text = wordtext;
12028 n->narg.backquote = backquotelist;
12029 here->here->nhere.doc = n;
12036 * called by editline -- any expansions to the prompt should be added here.
12038 #if ENABLE_ASH_EXPAND_PRMT
12039 static const char *
12040 expandstr(const char *ps)
12044 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12045 * and token processing _can_ alter it (delete NULs etc). */
12046 setinputstring((char *)ps);
12047 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12050 n.narg.type = NARG;
12051 n.narg.next = NULL;
12052 n.narg.text = wordtext;
12053 n.narg.backquote = backquotelist;
12055 expandarg(&n, NULL, 0);
12056 return stackblock();
12061 * Execute a command or commands contained in a string.
12064 evalstring(char *s, int mask)
12067 struct stackmark smark;
12071 setstackmark(&smark);
12074 while ((n = parsecmd(0)) != NODE_EOF) {
12076 popstackmark(&smark);
12089 * The eval command.
12091 static int FAST_FUNC
12092 evalcmd(int argc UNUSED_PARAM, char **argv)
12101 STARTSTACKSTR(concat);
12103 concat = stack_putstr(p, concat);
12107 STPUTC(' ', concat);
12109 STPUTC('\0', concat);
12110 p = grabstackstr(concat);
12112 evalstring(p, ~SKIPEVAL);
12118 * Read and execute commands.
12119 * "Top" is nonzero for the top level command loop;
12120 * it turns on prompting if the shell is interactive.
12126 struct stackmark smark;
12130 TRACE(("cmdloop(%d) called\n", top));
12134 setstackmark(&smark);
12137 showjobs(stderr, SHOW_CHANGED);
12140 if (iflag && top) {
12144 n = parsecmd(inter);
12146 if (DEBUG > 2 && debug && (n != NODE_EOF))
12149 if (n == NODE_EOF) {
12150 if (!top || numeof >= 50)
12152 if (!stoppedjobs()) {
12155 out2str("\nUse \"exit\" to leave shell.\n");
12158 } else if (nflag == 0) {
12159 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12164 popstackmark(&smark);
12169 return skip & SKIPEVAL;
12176 * Take commands from a file. To be compatible we should do a path
12177 * search for the file, which is necessary to find sub-commands.
12180 find_dot_file(char *name)
12183 const char *path = pathval();
12186 /* don't try this for absolute or relative paths */
12187 if (strchr(name, '/'))
12190 /* IIRC standards do not say whether . is to be searched.
12191 * And it is even smaller this way, making it unconditional for now:
12193 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12198 while ((fullname = path_advance(&path, name)) != NULL) {
12200 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12202 * Don't bother freeing here, since it will
12203 * be freed by the caller.
12207 if (fullname != name)
12208 stunalloc(fullname);
12211 /* not found in the PATH */
12212 ash_msg_and_raise_error("%s: not found", name);
12216 static int FAST_FUNC
12217 dotcmd(int argc, char **argv)
12220 struct strlist *sp;
12221 volatile struct shparam saveparam;
12223 for (sp = cmdenviron; sp; sp = sp->next)
12224 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12227 /* bash says: "bash: .: filename argument required" */
12228 return 2; /* bash compat */
12231 /* "false; . empty_file; echo $?" should print 0, not 1: */
12234 fullname = find_dot_file(argv[1]);
12238 if (argc) { /* argc > 0, argv[0] != NULL */
12239 saveparam = shellparam;
12240 shellparam.malloced = 0;
12241 shellparam.nparam = argc;
12242 shellparam.p = argv;
12245 setinputfile(fullname, INPUT_PUSH_FILE);
12246 commandname = fullname;
12251 freeparam(&shellparam);
12252 shellparam = saveparam;
12258 static int FAST_FUNC
12259 exitcmd(int argc UNUSED_PARAM, char **argv)
12264 exitstatus = number(argv[1]);
12265 raise_exception(EXEXIT);
12270 * Read a file containing shell functions.
12273 readcmdfile(char *name)
12275 setinputfile(name, INPUT_PUSH_FILE);
12281 /* ============ find_command inplementation */
12284 * Resolve a command name. If you change this routine, you may have to
12285 * change the shellexec routine as well.
12288 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12290 struct tblentry *cmdp;
12297 struct builtincmd *bcmd;
12299 /* If name contains a slash, don't use PATH or hash table */
12300 if (strchr(name, '/') != NULL) {
12301 entry->u.index = -1;
12302 if (act & DO_ABS) {
12303 while (stat(name, &statb) < 0) {
12305 if (errno == EINTR)
12308 entry->cmdtype = CMDUNKNOWN;
12312 entry->cmdtype = CMDNORMAL;
12316 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12318 updatetbl = (path == pathval());
12321 if (strstr(path, "%builtin") != NULL)
12322 act |= DO_ALTBLTIN;
12325 /* If name is in the table, check answer will be ok */
12326 cmdp = cmdlookup(name, 0);
12327 if (cmdp != NULL) {
12330 switch (cmdp->cmdtype) {
12348 } else if (cmdp->rehash == 0)
12349 /* if not invalidated by cd, we're done */
12353 /* If %builtin not in path, check for builtin next */
12354 bcmd = find_builtin(name);
12356 if (IS_BUILTIN_REGULAR(bcmd))
12357 goto builtin_success;
12358 if (act & DO_ALTPATH) {
12359 if (!(act & DO_ALTBLTIN))
12360 goto builtin_success;
12361 } else if (builtinloc <= 0) {
12362 goto builtin_success;
12366 #if ENABLE_FEATURE_SH_STANDALONE
12368 int applet_no = find_applet_by_name(name);
12369 if (applet_no >= 0) {
12370 entry->cmdtype = CMDNORMAL;
12371 entry->u.index = -2 - applet_no;
12377 /* We have to search path. */
12378 prev = -1; /* where to start */
12379 if (cmdp && cmdp->rehash) { /* doing a rehash */
12380 if (cmdp->cmdtype == CMDBUILTIN)
12383 prev = cmdp->param.index;
12389 while ((fullname = path_advance(&path, name)) != NULL) {
12390 stunalloc(fullname);
12391 /* NB: code below will still use fullname
12392 * despite it being "unallocated" */
12395 if (prefix(pathopt, "builtin")) {
12397 goto builtin_success;
12400 if ((act & DO_NOFUNC)
12401 || !prefix(pathopt, "func")
12402 ) { /* ignore unimplemented options */
12406 /* if rehash, don't redo absolute path names */
12407 if (fullname[0] == '/' && idx <= prev) {
12410 TRACE(("searchexec \"%s\": no change\n", name));
12413 while (stat(fullname, &statb) < 0) {
12415 if (errno == EINTR)
12418 if (errno != ENOENT && errno != ENOTDIR)
12422 e = EACCES; /* if we fail, this will be the error */
12423 if (!S_ISREG(statb.st_mode))
12425 if (pathopt) { /* this is a %func directory */
12426 stalloc(strlen(fullname) + 1);
12427 /* NB: stalloc will return space pointed by fullname
12428 * (because we don't have any intervening allocations
12429 * between stunalloc above and this stalloc) */
12430 readcmdfile(fullname);
12431 cmdp = cmdlookup(name, 0);
12432 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12433 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12434 stunalloc(fullname);
12437 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12439 entry->cmdtype = CMDNORMAL;
12440 entry->u.index = idx;
12444 cmdp = cmdlookup(name, 1);
12445 cmdp->cmdtype = CMDNORMAL;
12446 cmdp->param.index = idx;
12451 /* We failed. If there was an entry for this command, delete it */
12452 if (cmdp && updatetbl)
12453 delete_cmd_entry();
12455 ash_msg("%s: %s", name, errmsg(e, "not found"));
12456 entry->cmdtype = CMDUNKNOWN;
12461 entry->cmdtype = CMDBUILTIN;
12462 entry->u.cmd = bcmd;
12466 cmdp = cmdlookup(name, 1);
12467 cmdp->cmdtype = CMDBUILTIN;
12468 cmdp->param.cmd = bcmd;
12472 entry->cmdtype = cmdp->cmdtype;
12473 entry->u = cmdp->param;
12477 /* ============ trap.c */
12480 * The trap builtin.
12482 static int FAST_FUNC
12483 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12487 int signo, exitcode;
12492 for (signo = 0; signo < NSIG; signo++) {
12493 char *tr = trap_ptr[signo];
12495 /* note: bash adds "SIG", but only if invoked
12496 * as "bash". If called as "sh", or if set -o posix,
12497 * then it prints short signal names.
12498 * We are printing short names: */
12499 out1fmt("trap -- %s %s\n",
12501 get_signame(signo));
12502 /* trap_ptr != trap only if we are in special-cased `trap` code.
12503 * In this case, we will exit very soon, no need to free(). */
12504 /* if (trap_ptr != trap && tp[0]) */
12509 if (trap_ptr != trap) {
12522 signo = get_signum(*ap);
12524 /* Mimic bash message exactly */
12525 ash_msg("%s: invalid signal specification", *ap);
12531 if (LONE_DASH(action))
12534 action = ckstrdup(action);
12538 may_have_traps = 1;
12539 trap[signo] = action;
12550 /* ============ Builtins */
12552 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12554 * Lists available builtins
12556 static int FAST_FUNC
12557 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12563 "Built-in commands:\n"
12564 "------------------\n");
12565 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12566 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12567 builtintab[i].name + 1);
12573 #if ENABLE_FEATURE_SH_STANDALONE
12575 const char *a = applet_names;
12577 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12582 a += strlen(a) + 1;
12587 return EXIT_SUCCESS;
12589 #endif /* FEATURE_SH_EXTRA_QUIET */
12592 * The export and readonly commands.
12594 static int FAST_FUNC
12595 exportcmd(int argc UNUSED_PARAM, char **argv)
12601 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12603 if (nextopt("p") != 'p') {
12608 p = strchr(name, '=');
12612 vp = *findvar(hashvar(name), name);
12618 setvar(name, p, flag);
12619 } while ((name = *++aptr) != NULL);
12623 showvars(argv[0], flag, 0);
12628 * Delete a function if it exists.
12631 unsetfunc(const char *name)
12633 struct tblentry *cmdp;
12635 cmdp = cmdlookup(name, 0);
12636 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12637 delete_cmd_entry();
12641 * The unset builtin command. We unset the function before we unset the
12642 * variable to allow a function to be unset when there is a readonly variable
12643 * with the same name.
12645 static int FAST_FUNC
12646 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12653 while ((i = nextopt("vf")) != 0) {
12657 for (ap = argptr; *ap; ap++) {
12670 static const unsigned char timescmd_str[] ALIGN1 = {
12671 ' ', offsetof(struct tms, tms_utime),
12672 '\n', offsetof(struct tms, tms_stime),
12673 ' ', offsetof(struct tms, tms_cutime),
12674 '\n', offsetof(struct tms, tms_cstime),
12677 static int FAST_FUNC
12678 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12680 unsigned long clk_tck, s, t;
12681 const unsigned char *p;
12684 clk_tck = sysconf(_SC_CLK_TCK);
12689 t = *(clock_t *)(((char *) &buf) + p[1]);
12692 out1fmt("%lum%lu.%03lus%c",
12694 (t * 1000) / clk_tck,
12702 #if ENABLE_SH_MATH_SUPPORT
12704 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12705 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12707 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12709 static int FAST_FUNC
12710 letcmd(int argc UNUSED_PARAM, char **argv)
12716 ash_msg_and_raise_error("expression expected");
12718 i = ash_arith(*argv);
12726 * The read builtin. Options:
12727 * -r Do not interpret '\' specially
12728 * -s Turn off echo (tty only)
12729 * -n NCHARS Read NCHARS max
12730 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12731 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12732 * -u FD Read from given FD instead of fd 0
12733 * This uses unbuffered input, which may be avoidable in some cases.
12734 * TODO: bash also has:
12735 * -a ARRAY Read into array[0],[1],etc
12736 * -d DELIM End on DELIM char, not newline
12737 * -e Use line editing (tty only)
12739 static int FAST_FUNC
12740 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12742 char *opt_n = NULL;
12743 char *opt_p = NULL;
12744 char *opt_t = NULL;
12745 char *opt_u = NULL;
12746 int read_flags = 0;
12750 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12759 read_flags |= BUILTIN_READ_SILENT;
12765 read_flags |= BUILTIN_READ_RAW;
12775 r = shell_builtin_read(setvar2,
12777 bltinlookup("IFS"), /* can be NULL */
12785 if ((uintptr_t)r > 1)
12786 ash_msg_and_raise_error(r);
12788 return (uintptr_t)r;
12791 static int FAST_FUNC
12792 umaskcmd(int argc UNUSED_PARAM, char **argv)
12794 static const char permuser[3] ALIGN1 = "ugo";
12795 static const char permmode[3] ALIGN1 = "rwx";
12796 static const short permmask[] ALIGN2 = {
12797 S_IRUSR, S_IWUSR, S_IXUSR,
12798 S_IRGRP, S_IWGRP, S_IXGRP,
12799 S_IROTH, S_IWOTH, S_IXOTH
12802 /* TODO: use bb_parse_mode() instead */
12807 int symbolic_mode = 0;
12809 while (nextopt("S") != '\0') {
12820 if (symbolic_mode) {
12824 for (i = 0; i < 3; i++) {
12827 *p++ = permuser[i];
12829 for (j = 0; j < 3; j++) {
12830 if ((mask & permmask[3 * i + j]) == 0) {
12831 *p++ = permmode[j];
12839 out1fmt("%.4o\n", mask);
12842 if (isdigit((unsigned char) *ap)) {
12845 if (*ap >= '8' || *ap < '0')
12846 ash_msg_and_raise_error(msg_illnum, argv[1]);
12847 mask = (mask << 3) + (*ap - '0');
12848 } while (*++ap != '\0');
12851 mask = ~mask & 0777;
12852 if (!bb_parse_mode(ap, &mask)) {
12853 ash_msg_and_raise_error("illegal mode: %s", ap);
12855 umask(~mask & 0777);
12861 static int FAST_FUNC
12862 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12864 return shell_builtin_ulimit(argv);
12867 /* ============ main() and helpers */
12870 * Called to exit the shell.
12879 status = exitstatus;
12880 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12881 if (setjmp(loc.loc)) {
12882 if (exception_type == EXEXIT)
12883 /* dash bug: it just does _exit(exitstatus) here
12884 * but we have to do setjobctl(0) first!
12885 * (bug is still not fixed in dash-0.5.3 - if you run dash
12886 * under Midnight Commander, on exit from dash MC is backgrounded) */
12887 status = exitstatus;
12890 exception_handler = &loc;
12897 flush_stdout_stderr();
12907 /* from input.c: */
12908 /* we will never free this */
12909 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12912 signal(SIGCHLD, SIG_DFL);
12913 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12914 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12916 signal(SIGHUP, SIG_DFL);
12922 struct stat st1, st2;
12925 for (envp = environ; envp && *envp; envp++) {
12926 if (strchr(*envp, '=')) {
12927 setvareq(*envp, VEXPORT|VTEXTFIXED);
12931 setvar("PPID", utoa(getppid()), 0);
12933 p = lookupvar("PWD");
12935 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12936 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
12946 //usage:#define ash_trivial_usage
12947 //usage: "[-/+OPTCHARS] [-/+o OPTNAME]... [-c 'SCRIPT' [ARG0 [ARGS]] / SCRIPT_FILE [ARGS]]"
12948 //usage:#define ash_full_usage "\n\n"
12949 //usage: "Unix shell interpreter"
12951 //usage:#if ENABLE_FEATURE_SH_IS_ASH
12952 //usage:# define sh_trivial_usage ash_trivial_usage
12953 //usage:# define sh_full_usage ash_full_usage
12955 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
12956 //usage:# define bash_trivial_usage ash_trivial_usage
12957 //usage:# define bash_full_usage ash_full_usage
12961 * Process the shell command line arguments.
12964 procargs(char **argv)
12967 const char *xminusc;
12972 /* if (xargv[0]) - mmm, this is always true! */
12974 for (i = 0; i < NOPTS; i++)
12977 if (options(/*cmdline:*/ 1)) {
12978 /* it already printed err message */
12979 raise_exception(EXERROR);
12983 if (*xargv == NULL) {
12985 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12988 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12992 for (i = 0; i < NOPTS; i++)
12993 if (optlist[i] == 2)
12998 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13003 } else if (!sflag) {
13004 setinputfile(*xargv, 0);
13007 commandname = arg0;
13010 shellparam.p = xargv;
13011 #if ENABLE_ASH_GETOPTS
13012 shellparam.optind = 1;
13013 shellparam.optoff = -1;
13015 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13017 shellparam.nparam++;
13024 * Read /etc/profile or .profile.
13027 read_profile(const char *name)
13031 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13040 * This routine is called when an error or an interrupt occurs in an
13041 * interactive shell and control is returned to the main command loop.
13049 /* from input.c: */
13050 g_parsefile->left_in_buffer = 0;
13051 g_parsefile->left_in_line = 0; /* clear input buffer */
13053 /* from parser.c: */
13056 /* from redir.c: */
13057 clearredir(/*drop:*/ 0);
13061 static short profile_buf[16384];
13062 extern int etext();
13066 * Main routine. We initialize things, parse the arguments, execute
13067 * profiles if we're a login shell, and then call cmdloop to execute
13068 * commands. The setjmp call sets up the location to jump to when an
13069 * exception occurs. When an exception occurs the variable "state"
13070 * is used to figure out how far we had gotten.
13072 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13073 int ash_main(int argc UNUSED_PARAM, char **argv)
13075 const char *shinit;
13076 volatile smallint state;
13077 struct jmploc jmploc;
13078 struct stackmark smark;
13080 /* Initialize global data */
13084 #if ENABLE_ASH_ALIAS
13090 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13093 #if ENABLE_FEATURE_EDITING
13094 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13097 if (setjmp(jmploc.loc)) {
13103 e = exception_type;
13107 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13111 outcslow('\n', stderr);
13114 popstackmark(&smark);
13115 FORCE_INT_ON; /* enable interrupts */
13124 exception_handler = &jmploc;
13127 TRACE(("Shell args: "));
13128 trace_puts_args(argv);
13130 rootpid = getpid();
13133 setstackmark(&smark);
13136 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13138 const char *hp = lookupvar("HISTFILE");
13141 hp = lookupvar("HOME");
13143 char *defhp = concat_path_file(hp, ".ash_history");
13144 setvar("HISTFILE", defhp, 0);
13150 if (argv[0] && argv[0][0] == '-')
13154 read_profile("/etc/profile");
13157 read_profile(".profile");
13163 getuid() == geteuid() && getgid() == getegid() &&
13167 shinit = lookupvar("ENV");
13168 if (shinit != NULL && *shinit != '\0') {
13169 read_profile(shinit);
13175 /* evalstring pushes parsefile stack.
13176 * Ensure we don't falsely claim that 0 (stdin)
13177 * is one of stacked source fds.
13178 * Testcase: ash -c 'exec 1>&0' must not complain. */
13179 // if (!sflag) g_parsefile->pf_fd = -1;
13180 // ^^ not necessary since now we special-case fd 0
13181 // in is_hidden_fd() to not be considered "hidden fd"
13182 evalstring(minusc, 0);
13185 if (sflag || minusc == NULL) {
13186 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13188 const char *hp = lookupvar("HISTFILE");
13190 line_input_state->hist_file = hp;
13193 state4: /* XXX ??? - why isn't this before the "if" statement */
13201 extern void _mcleanup(void);
13205 TRACE(("End of main reached\n"));
13212 * Copyright (c) 1989, 1991, 1993, 1994
13213 * The Regents of the University of California. All rights reserved.
13215 * This code is derived from software contributed to Berkeley by
13216 * Kenneth Almquist.
13218 * Redistribution and use in source and binary forms, with or without
13219 * modification, are permitted provided that the following conditions
13221 * 1. Redistributions of source code must retain the above copyright
13222 * notice, this list of conditions and the following disclaimer.
13223 * 2. Redistributions in binary form must reproduce the above copyright
13224 * notice, this list of conditions and the following disclaimer in the
13225 * documentation and/or other materials provided with the distribution.
13226 * 3. Neither the name of the University nor the names of its contributors
13227 * may be used to endorse or promote products derived from this software
13228 * without specific prior written permission.
13230 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13231 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13232 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13233 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13234 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13235 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13236 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13237 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13238 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13239 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF