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 (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
53 #if !ENABLE_ASH_INTERNAL_GLOB
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
62 #if ENABLE_ASH_RANDOM_SUPPORT
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
68 #include "NUM_APPLETS.h"
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
85 # error "Do not even bother, ash will not run on NOMMU machine"
91 //config: depends on !NOMMU
93 //config: Tha 'ash' shell adds about 60k in the default configuration and is
94 //config: the most complete and most pedantically correct shell included with
95 //config: busybox. This shell is actually a derivative of the Debian 'dash'
96 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config: (written by Kenneth Almquist) from NetBSD.
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config: bool "Optimize for size instead of speed"
102 //config: depends on ASH
104 //config: Compile ash for reduced size at the price of speed.
106 //config:config ASH_INTERNAL_GLOB
107 //config: bool "Use internal glob() implementation"
109 //config: depends on ASH
111 //config: Do not use glob() function from libc, use internal implementation.
112 //config: Use this if you are getting "glob.h: No such file or directory"
113 //config: or similar build errors.
115 //config:config ASH_RANDOM_SUPPORT
116 //config: bool "Pseudorandom generator and $RANDOM variable"
118 //config: depends on ASH
120 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config: You can reset the generator by using a specified start value.
123 //config: After "unset RANDOM" the generator will switch off and this
124 //config: variable will no longer have special treatment.
126 //config:config ASH_EXPAND_PRMT
127 //config: bool "Expand prompt string"
129 //config: depends on ASH
131 //config: "PS#" may contain volatile content, such as backquote commands.
132 //config: This option recreates the prompt string from the environment
133 //config: variable each time it is displayed.
135 //config:config ASH_BASH_COMPAT
136 //config: bool "bash-compatible extensions"
138 //config: depends on ASH
140 //config: Enable bash-compatible extensions.
142 //config:config ASH_IDLE_TIMEOUT
143 //config: bool "Idle timeout variable"
145 //config: depends on ASH
147 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
149 //config:config ASH_JOB_CONTROL
150 //config: bool "Job control"
152 //config: depends on ASH
154 //config: Enable job control in the ash shell.
156 //config:config ASH_ALIAS
157 //config: bool "Alias support"
159 //config: depends on ASH
161 //config: Enable alias support in the ash shell.
163 //config:config ASH_GETOPTS
164 //config: bool "Builtin getopt to parse positional parameters"
166 //config: depends on ASH
168 //config: Enable support for getopts builtin in ash.
170 //config:config ASH_BUILTIN_ECHO
171 //config: bool "Builtin version of 'echo'"
173 //config: depends on ASH
175 //config: Enable support for echo builtin in ash.
177 //config:config ASH_BUILTIN_PRINTF
178 //config: bool "Builtin version of 'printf'"
180 //config: depends on ASH
182 //config: Enable support for printf builtin in ash.
184 //config:config ASH_BUILTIN_TEST
185 //config: bool "Builtin version of 'test'"
187 //config: depends on ASH
189 //config: Enable support for test builtin in ash.
191 //config:config ASH_HELP
192 //config: bool "help builtin"
194 //config: depends on ASH
196 //config: Enable help builtin in ash.
198 //config:config ASH_CMDCMD
199 //config: bool "'command' command to override shell builtins"
201 //config: depends on ASH
203 //config: Enable support for the ash 'command' builtin, which allows
204 //config: you to run the specified command with the specified arguments,
205 //config: even when there is an ash builtin command with the same name.
207 //config:config ASH_MAIL
208 //config: bool "Check for new mail on interactive shells"
210 //config: depends on ASH
212 //config: Enable "check for new mail" function in the ash shell.
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
223 /* ============ Hash table sizes. Configurable. */
227 #define CMDTABLESIZE 31 /* should be prime */
230 /* ============ Shell options */
232 static const char *const optletters_optnames[] = {
247 #if ENABLE_ASH_BASH_COMPAT
256 #define optletters(n) optletters_optnames[n][0]
257 #define optnames(n) (optletters_optnames[n] + 1)
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
262 /* ============ Misc data */
264 #define msg_illnum "Illegal number: %s"
267 * We enclose jmp_buf in a structure so that we can declare pointers to
268 * jump locations. The global variable handler contains the location to
269 * jump to when an exception occurs, and the global variable exception_type
270 * contains a code identifying the exception. To implement nested
271 * exception handlers, the user should save the value of handler on entry
272 * to an inner scope, set handler to point to a jmploc structure for the
273 * inner scope, and restore handler on exit from the scope.
279 struct globals_misc {
280 uint8_t exitstatus; /* exit status of last command */
281 uint8_t back_exitstatus;/* exit status of backquoted command */
282 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
283 int rootpid; /* pid of main shell */
284 /* shell level: 0 for the main shell, 1 for its children, and so on */
286 #define rootshell (!shlvl)
287 char *minusc; /* argument to -c option */
289 char *curdir; // = nullstr; /* current working directory */
290 char *physdir; // = nullstr; /* physical working directory */
292 char *arg0; /* value of $0 */
294 struct jmploc *exception_handler;
296 volatile int suppress_int; /* counter */
297 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
298 /* last pending signal */
299 volatile /*sig_atomic_t*/ smallint pending_sig;
300 smallint exception_type; /* kind of exception (0..5) */
302 #define EXINT 0 /* SIGINT received */
303 #define EXERROR 1 /* a generic error */
304 #define EXEXIT 4 /* exit the shell */
305 #define EXSIG 5 /* trapped signal in wait(1) */
308 char nullstr[1]; /* zero length string */
311 #define eflag optlist[0]
312 #define fflag optlist[1]
313 #define Iflag optlist[2]
314 #define iflag optlist[3]
315 #define mflag optlist[4]
316 #define nflag optlist[5]
317 #define sflag optlist[6]
318 #define xflag optlist[7]
319 #define vflag optlist[8]
320 #define Cflag optlist[9]
321 #define aflag optlist[10]
322 #define bflag optlist[11]
323 #define uflag optlist[12]
324 #define viflag optlist[13]
325 #if ENABLE_ASH_BASH_COMPAT
326 # define pipefail optlist[14]
331 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
332 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
335 /* trap handler commands */
337 * Sigmode records the current value of the signal handlers for the various
338 * modes. A value of zero means that the current handler is not known.
339 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
341 char sigmode[NSIG - 1];
342 #define S_DFL 1 /* default signal handling (SIG_DFL) */
343 #define S_CATCH 2 /* signal is caught */
344 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
345 #define S_HARD_IGN 4 /* signal is ignored permanently */
347 /* indicates specified signal received */
348 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
349 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
351 char **trap_ptr; /* used only by "trap hack" */
353 /* Rarely referenced stuff */
354 #if ENABLE_ASH_RANDOM_SUPPORT
357 pid_t backgndpid; /* pid of last background process */
359 extern struct globals_misc *const ash_ptr_to_globals_misc;
360 #define G_misc (*ash_ptr_to_globals_misc)
361 #define exitstatus (G_misc.exitstatus )
362 #define back_exitstatus (G_misc.back_exitstatus )
363 #define job_warning (G_misc.job_warning)
364 #define rootpid (G_misc.rootpid )
365 #define shlvl (G_misc.shlvl )
366 #define minusc (G_misc.minusc )
367 #define curdir (G_misc.curdir )
368 #define physdir (G_misc.physdir )
369 #define arg0 (G_misc.arg0 )
370 #define exception_handler (G_misc.exception_handler)
371 #define exception_type (G_misc.exception_type )
372 #define suppress_int (G_misc.suppress_int )
373 #define pending_int (G_misc.pending_int )
374 #define pending_sig (G_misc.pending_sig )
375 #define isloginsh (G_misc.isloginsh )
376 #define nullstr (G_misc.nullstr )
377 #define optlist (G_misc.optlist )
378 #define sigmode (G_misc.sigmode )
379 #define gotsig (G_misc.gotsig )
380 #define may_have_traps (G_misc.may_have_traps )
381 #define trap (G_misc.trap )
382 #define trap_ptr (G_misc.trap_ptr )
383 #define random_gen (G_misc.random_gen )
384 #define backgndpid (G_misc.backgndpid )
385 #define INIT_G_misc() do { \
386 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
394 /* ============ DEBUG */
396 static void trace_printf(const char *fmt, ...);
397 static void trace_vprintf(const char *fmt, va_list va);
398 # define TRACE(param) trace_printf param
399 # define TRACEV(param) trace_vprintf param
400 # define close(fd) do { \
402 if (close(dfd) < 0) \
403 bb_error_msg("bug on %d: closing %d(0x%x)", \
404 __LINE__, dfd, dfd); \
407 # define TRACE(param)
408 # define TRACEV(param)
412 /* ============ Utility functions */
413 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
414 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
417 isdigit_str9(const char *str)
419 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
420 while (--maxlen && isdigit(*str))
422 return (*str == '\0');
426 var_end(const char *var)
435 /* ============ Interrupts / exceptions */
437 static void exitshell(void) NORETURN;
440 * These macros allow the user to suspend the handling of interrupt signals
441 * over a period of time. This is similar to SIGHOLD or to sigblock, but
442 * much more efficient and portable. (But hacking the kernel is so much
443 * more fun than worrying about efficiency and portability. :-))
445 #define INT_OFF do { \
451 * Called to raise an exception. Since C doesn't include exceptions, we
452 * just do a longjmp to the exception handler. The type of exception is
453 * stored in the global variable "exception_type".
455 static void raise_exception(int) NORETURN;
457 raise_exception(int e)
460 if (exception_handler == NULL)
465 longjmp(exception_handler->loc, 1);
468 #define raise_exception(e) do { \
469 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
470 raise_exception(e); \
475 * Called when a SIGINT is received. (If the user specifies
476 * that SIGINT is to be trapped or ignored using the trap builtin, then
477 * this routine is not called.) Suppressint is nonzero when interrupts
478 * are held using the INT_OFF macro. (The test for iflag is just
479 * defensive programming.)
481 static void raise_interrupt(void) NORETURN;
483 raise_interrupt(void)
488 /* Signal is not automatically unmasked after it is raised,
489 * do it ourself - unmask all signals */
490 sigprocmask_allsigs(SIG_UNBLOCK);
491 /* pending_sig = 0; - now done in signal_handler() */
494 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
495 if (!(rootshell && iflag)) {
496 /* Kill ourself with SIGINT */
497 signal(SIGINT, SIG_DFL);
502 /* bash: ^C even on empty command line sets $? */
503 exitstatus = SIGINT + 128;
504 raise_exception(ex_type);
508 #define raise_interrupt() do { \
509 TRACE(("raising interrupt on line %d\n", __LINE__)); \
514 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
518 if (--suppress_int == 0 && pending_int) {
522 #define INT_ON int_on()
523 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
531 #define FORCE_INT_ON force_int_on()
533 #define SAVE_INT(v) ((v) = suppress_int)
535 #define RESTORE_INT(v) do { \
537 suppress_int = (v); \
538 if (suppress_int == 0 && pending_int) \
543 /* ============ Stdout/stderr output */
546 outstr(const char *p, FILE *file)
554 flush_stdout_stderr(void)
561 /* Was called outcslow(c,FILE*), but c was always '\n' */
563 newline_and_flush(FILE *dest)
571 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
573 out1fmt(const char *fmt, ...)
580 r = vprintf(fmt, ap);
586 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
588 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
595 ret = vsnprintf(outbuf, length, fmt, ap);
602 out1str(const char *p)
608 out2str(const char *p)
611 flush_stdout_stderr();
615 /* ============ Parser structures */
617 /* control characters in argument strings */
618 #define CTL_FIRST CTLESC
619 #define CTLESC ((unsigned char)'\201') /* escape next character */
620 #define CTLVAR ((unsigned char)'\202') /* variable defn */
621 #define CTLENDVAR ((unsigned char)'\203')
622 #define CTLBACKQ ((unsigned char)'\204')
623 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
624 #define CTLENDARI ((unsigned char)'\207')
625 #define CTLQUOTEMARK ((unsigned char)'\210')
626 #define CTL_LAST CTLQUOTEMARK
628 /* variable substitution byte (follows CTLVAR) */
629 #define VSTYPE 0x0f /* type of variable substitution */
630 #define VSNUL 0x10 /* colon--treat the empty string as unset */
632 /* values of VSTYPE field */
633 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
634 #define VSMINUS 0x2 /* ${var-text} */
635 #define VSPLUS 0x3 /* ${var+text} */
636 #define VSQUESTION 0x4 /* ${var?message} */
637 #define VSASSIGN 0x5 /* ${var=text} */
638 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
639 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
640 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
641 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
642 #define VSLENGTH 0xa /* ${#var} */
643 #if ENABLE_ASH_BASH_COMPAT
644 #define VSSUBSTR 0xc /* ${var:position:length} */
645 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
646 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
649 static const char dolatstr[] ALIGN1 = {
650 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
652 #define DOLATSTRLEN 6
671 #if ENABLE_ASH_BASH_COMPAT
688 smallint type; /* Nxxxx */
691 union node *redirect;
696 smallint pipe_backgnd;
697 struct nodelist *cmdlist;
703 union node *redirect;
716 union node *elsepart;
743 struct nodelist *backquote;
746 /* nfile and ndup layout must match!
747 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
748 * that it is actually NTO2 (>&file), and change its type.
765 char *_unused_expfname;
784 struct nredir nredir;
785 struct nbinary nbinary;
789 struct nclist nclist;
798 * NODE_EOF is returned by parsecmd when it encounters an end of file.
799 * It must be distinct from NULL.
801 #define NODE_EOF ((union node *) -1L)
804 struct nodelist *next;
817 freefunc(struct funcnode *f)
819 if (f && --f->count < 0)
824 /* ============ Debugging output */
828 static FILE *tracefile;
831 trace_printf(const char *fmt, ...)
838 fprintf(tracefile, "%u ", (int) time(NULL));
840 fprintf(tracefile, "[%u] ", (int) getpid());
842 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
844 vfprintf(tracefile, fmt, va);
849 trace_vprintf(const char *fmt, va_list va)
854 fprintf(tracefile, "%u ", (int) time(NULL));
856 fprintf(tracefile, "[%u] ", (int) getpid());
858 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
859 vfprintf(tracefile, fmt, va);
863 trace_puts(const char *s)
871 trace_puts_quoted(char *s)
878 putc('"', tracefile);
879 for (p = s; *p; p++) {
880 switch ((unsigned char)*p) {
881 case '\n': c = 'n'; goto backslash;
882 case '\t': c = 't'; goto backslash;
883 case '\r': c = 'r'; goto backslash;
884 case '\"': c = '\"'; goto backslash;
885 case '\\': c = '\\'; goto backslash;
886 case CTLESC: c = 'e'; goto backslash;
887 case CTLVAR: c = 'v'; goto backslash;
888 case CTLBACKQ: c = 'q'; goto backslash;
890 putc('\\', tracefile);
894 if (*p >= ' ' && *p <= '~')
897 putc('\\', tracefile);
898 putc((*p >> 6) & 03, tracefile);
899 putc((*p >> 3) & 07, tracefile);
900 putc(*p & 07, tracefile);
905 putc('"', tracefile);
909 trace_puts_args(char **ap)
916 trace_puts_quoted(*ap);
918 putc('\n', tracefile);
921 putc(' ', tracefile);
936 /* leave open because libedit might be using it */
939 strcpy(s, "./trace");
941 if (!freopen(s, "a", tracefile)) {
942 fprintf(stderr, "Can't re-open %s\n", s);
947 tracefile = fopen(s, "a");
948 if (tracefile == NULL) {
949 fprintf(stderr, "Can't open %s\n", s);
955 flags = fcntl(fileno(tracefile), F_GETFL);
957 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
959 setlinebuf(tracefile);
960 fputs("\nTracing started.\n", tracefile);
964 indent(int amount, char *pfx, FILE *fp)
968 for (i = 0; i < amount; i++) {
969 if (pfx && i == amount - 1)
975 /* little circular references here... */
976 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
979 sharg(union node *arg, FILE *fp)
982 struct nodelist *bqlist;
983 unsigned char subtype;
985 if (arg->type != NARG) {
986 out1fmt("<node type %d>\n", arg->type);
989 bqlist = arg->narg.backquote;
990 for (p = arg->narg.text; *p; p++) {
991 switch ((unsigned char)*p) {
1000 if (subtype == VSLENGTH)
1008 if (subtype & VSNUL)
1011 switch (subtype & VSTYPE) {
1037 case VSTRIMRIGHTMAX:
1044 out1fmt("<subtype %d>", subtype);
1053 shtree(bqlist->n, -1, NULL, fp);
1064 shcmd(union node *cmd, FILE *fp)
1072 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1078 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1082 switch (np->nfile.type) {
1083 case NTO: s = ">>"+1; dftfd = 1; break;
1084 case NCLOBBER: s = ">|"; dftfd = 1; break;
1085 case NAPPEND: s = ">>"; dftfd = 1; break;
1086 #if ENABLE_ASH_BASH_COMPAT
1089 case NTOFD: s = ">&"; dftfd = 1; break;
1090 case NFROM: s = "<"; break;
1091 case NFROMFD: s = "<&"; break;
1092 case NFROMTO: s = "<>"; break;
1093 default: s = "*error*"; break;
1095 if (np->nfile.fd != dftfd)
1096 fprintf(fp, "%d", np->nfile.fd);
1098 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1099 fprintf(fp, "%d", np->ndup.dupfd);
1101 sharg(np->nfile.fname, fp);
1108 shtree(union node *n, int ind, char *pfx, FILE *fp)
1110 struct nodelist *lp;
1116 indent(ind, pfx, fp);
1118 if (n == NODE_EOF) {
1133 shtree(n->nbinary.ch1, ind, NULL, fp);
1136 shtree(n->nbinary.ch2, ind, NULL, fp);
1144 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1145 shtree(lp->n, 0, NULL, fp);
1149 if (n->npipe.pipe_backgnd)
1155 fprintf(fp, "<node type %d>", n->type);
1163 showtree(union node *n)
1165 trace_puts("showtree called\n");
1166 shtree(n, 1, NULL, stderr);
1172 /* ============ Parser data */
1175 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1178 struct strlist *next;
1185 struct strpush *prev; /* preceding string on stack */
1187 int prev_left_in_line;
1188 #if ENABLE_ASH_ALIAS
1189 struct alias *ap; /* if push was associated with an alias */
1191 char *string; /* remember the string since it may change */
1193 /* Remember last two characters for pungetc. */
1196 /* Number of outstanding calls to pungetc. */
1201 struct parsefile *prev; /* preceding file on stack */
1202 int linno; /* current line */
1203 int pf_fd; /* file descriptor (or -1 if string) */
1204 int left_in_line; /* number of chars left in this line */
1205 int left_in_buffer; /* number of chars left in this buffer past the line */
1206 char *next_to_pgetc; /* next char in buffer */
1207 char *buf; /* input buffer */
1208 struct strpush *strpush; /* for pushing strings at this level */
1209 struct strpush basestrpush; /* so pushing one is fast */
1211 /* Remember last two characters for pungetc. */
1214 /* Number of outstanding calls to pungetc. */
1218 static struct parsefile basepf; /* top level input file */
1219 static struct parsefile *g_parsefile = &basepf; /* current input file */
1220 static int startlinno; /* line # where last token started */
1221 static char *commandname; /* currently executing command */
1222 static struct strlist *cmdenviron; /* environment for builtin command */
1225 /* ============ Message printing */
1228 ash_vmsg(const char *msg, va_list ap)
1230 fprintf(stderr, "%s: ", arg0);
1232 if (strcmp(arg0, commandname))
1233 fprintf(stderr, "%s: ", commandname);
1234 if (!iflag || g_parsefile->pf_fd > 0)
1235 fprintf(stderr, "line %d: ", startlinno);
1237 vfprintf(stderr, msg, ap);
1238 newline_and_flush(stderr);
1242 * Exverror is called to raise the error exception. If the second argument
1243 * is not NULL then error prints an error message using printf style
1244 * formatting. It then raises the error exception.
1246 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1248 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1252 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1254 TRACE(("\") pid=%d\n", getpid()));
1256 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1261 flush_stdout_stderr();
1262 raise_exception(cond);
1266 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1268 ash_msg_and_raise_error(const char *msg, ...)
1273 ash_vmsg_and_raise(EXERROR, msg, ap);
1278 static void raise_error_syntax(const char *) NORETURN;
1280 raise_error_syntax(const char *msg)
1282 ash_msg_and_raise_error("syntax error: %s", msg);
1286 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1288 ash_msg_and_raise(int cond, const char *msg, ...)
1293 ash_vmsg_and_raise(cond, msg, ap);
1299 * error/warning routines for external builtins
1302 ash_msg(const char *fmt, ...)
1312 * Return a string describing an error. The returned string may be a
1313 * pointer to a static buffer that will be overwritten on the next call.
1314 * Action describes the operation that got the error.
1317 errmsg(int e, const char *em)
1319 if (e == ENOENT || e == ENOTDIR) {
1326 /* ============ Memory allocation */
1329 /* I consider these wrappers nearly useless:
1330 * ok, they return you to nearest exception handler, but
1331 * how much memory do you leak in the process, making
1332 * memory starvation worse?
1335 ckrealloc(void * p, size_t nbytes)
1337 p = realloc(p, nbytes);
1339 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1344 ckmalloc(size_t nbytes)
1346 return ckrealloc(NULL, nbytes);
1350 ckzalloc(size_t nbytes)
1352 return memset(ckmalloc(nbytes), 0, nbytes);
1356 ckstrdup(const char *s)
1358 char *p = strdup(s);
1360 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1364 /* Using bbox equivalents. They exit if out of memory */
1365 # define ckrealloc xrealloc
1366 # define ckmalloc xmalloc
1367 # define ckzalloc xzalloc
1368 # define ckstrdup xstrdup
1372 * It appears that grabstackstr() will barf with such alignments
1373 * because stalloc() will return a string allocated in a new stackblock.
1375 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1377 /* Most machines require the value returned from malloc to be aligned
1378 * in some way. The following macro will get this right
1379 * on many machines. */
1380 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1381 /* Minimum size of a block */
1382 MINSIZE = SHELL_ALIGN(504),
1385 struct stack_block {
1386 struct stack_block *prev;
1387 char space[MINSIZE];
1391 struct stack_block *stackp;
1397 struct globals_memstack {
1398 struct stack_block *g_stackp; // = &stackbase;
1399 char *g_stacknxt; // = stackbase.space;
1400 char *sstrend; // = stackbase.space + MINSIZE;
1401 size_t g_stacknleft; // = MINSIZE;
1402 struct stack_block stackbase;
1404 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1405 #define G_memstack (*ash_ptr_to_globals_memstack)
1406 #define g_stackp (G_memstack.g_stackp )
1407 #define g_stacknxt (G_memstack.g_stacknxt )
1408 #define sstrend (G_memstack.sstrend )
1409 #define g_stacknleft (G_memstack.g_stacknleft)
1410 #define stackbase (G_memstack.stackbase )
1411 #define INIT_G_memstack() do { \
1412 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1414 g_stackp = &stackbase; \
1415 g_stacknxt = stackbase.space; \
1416 g_stacknleft = MINSIZE; \
1417 sstrend = stackbase.space + MINSIZE; \
1421 #define stackblock() ((void *)g_stacknxt)
1422 #define stackblocksize() g_stacknleft
1425 * Parse trees for commands are allocated in lifo order, so we use a stack
1426 * to make this more efficient, and also to avoid all sorts of exception
1427 * handling code to handle interrupts in the middle of a parse.
1429 * The size 504 was chosen because the Ultrix malloc handles that size
1433 stalloc(size_t nbytes)
1438 aligned = SHELL_ALIGN(nbytes);
1439 if (aligned > g_stacknleft) {
1442 struct stack_block *sp;
1444 blocksize = aligned;
1445 if (blocksize < MINSIZE)
1446 blocksize = MINSIZE;
1447 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1448 if (len < blocksize)
1449 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1452 sp->prev = g_stackp;
1453 g_stacknxt = sp->space;
1454 g_stacknleft = blocksize;
1455 sstrend = g_stacknxt + blocksize;
1460 g_stacknxt += aligned;
1461 g_stacknleft -= aligned;
1466 stzalloc(size_t nbytes)
1468 return memset(stalloc(nbytes), 0, nbytes);
1475 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1476 write(STDERR_FILENO, "stunalloc\n", 10);
1480 g_stacknleft += g_stacknxt - (char *)p;
1485 * Like strdup but works with the ash stack.
1488 sstrdup(const char *p)
1490 size_t len = strlen(p) + 1;
1491 return memcpy(stalloc(len), p, len);
1495 grabstackblock(size_t len)
1501 pushstackmark(struct stackmark *mark, size_t len)
1503 mark->stackp = g_stackp;
1504 mark->stacknxt = g_stacknxt;
1505 mark->stacknleft = g_stacknleft;
1506 grabstackblock(len);
1510 setstackmark(struct stackmark *mark)
1512 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1516 popstackmark(struct stackmark *mark)
1518 struct stack_block *sp;
1524 while (g_stackp != mark->stackp) {
1526 g_stackp = sp->prev;
1529 g_stacknxt = mark->stacknxt;
1530 g_stacknleft = mark->stacknleft;
1531 sstrend = mark->stacknxt + mark->stacknleft;
1536 * When the parser reads in a string, it wants to stick the string on the
1537 * stack and only adjust the stack pointer when it knows how big the
1538 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1539 * of space on top of the stack and stackblocklen returns the length of
1540 * this block. Growstackblock will grow this space by at least one byte,
1541 * possibly moving it (like realloc). Grabstackblock actually allocates the
1542 * part of the block that has been used.
1545 growstackblock(void)
1549 newlen = g_stacknleft * 2;
1550 if (newlen < g_stacknleft)
1551 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1555 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1556 struct stack_block *sp;
1557 struct stack_block *prevstackp;
1562 prevstackp = sp->prev;
1563 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1564 sp = ckrealloc(sp, grosslen);
1565 sp->prev = prevstackp;
1567 g_stacknxt = sp->space;
1568 g_stacknleft = newlen;
1569 sstrend = sp->space + newlen;
1572 char *oldspace = g_stacknxt;
1573 size_t oldlen = g_stacknleft;
1574 char *p = stalloc(newlen);
1576 /* free the space we just allocated */
1577 g_stacknxt = memcpy(p, oldspace, oldlen);
1578 g_stacknleft += newlen;
1583 * The following routines are somewhat easier to use than the above.
1584 * The user declares a variable of type STACKSTR, which may be declared
1585 * to be a register. The macro STARTSTACKSTR initializes things. Then
1586 * the user uses the macro STPUTC to add characters to the string. In
1587 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1588 * grown as necessary. When the user is done, she can just leave the
1589 * string there and refer to it using stackblock(). Or she can allocate
1590 * the space for it using grabstackstr(). If it is necessary to allow
1591 * someone else to use the stack temporarily and then continue to grow
1592 * the string, the user should use grabstack to allocate the space, and
1593 * then call ungrabstr(p) to return to the previous mode of operation.
1595 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1596 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1597 * is space for at least one character.
1602 size_t len = stackblocksize();
1604 return (char *)stackblock() + len;
1608 * Called from CHECKSTRSPACE.
1611 makestrspace(size_t newlen, char *p)
1613 size_t len = p - g_stacknxt;
1619 size = stackblocksize();
1621 if (nleft >= newlen)
1625 return (char *)stackblock() + len;
1629 stack_nputstr(const char *s, size_t n, char *p)
1631 p = makestrspace(n, p);
1632 p = (char *)memcpy(p, s, n) + n;
1637 stack_putstr(const char *s, char *p)
1639 return stack_nputstr(s, strlen(s), p);
1643 _STPUTC(int c, char *p)
1651 #define STARTSTACKSTR(p) ((p) = stackblock())
1652 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1653 #define CHECKSTRSPACE(n, p) do { \
1656 size_t m = sstrend - q; \
1658 (p) = makestrspace(l, q); \
1660 #define USTPUTC(c, p) (*(p)++ = (c))
1661 #define STACKSTRNUL(p) do { \
1662 if ((p) == sstrend) \
1663 (p) = growstackstr(); \
1666 #define STUNPUTC(p) (--(p))
1667 #define STTOPC(p) ((p)[-1])
1668 #define STADJUST(amount, p) ((p) += (amount))
1670 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1671 #define ungrabstackstr(s, p) stunalloc(s)
1672 #define stackstrend() ((void *)sstrend)
1675 /* ============ String helpers */
1678 * prefix -- see if pfx is a prefix of string.
1681 prefix(const char *string, const char *pfx)
1684 if (*pfx++ != *string++)
1687 return (char *) string;
1691 * Check for a valid number. This should be elsewhere.
1694 is_number(const char *p)
1699 } while (*++p != '\0');
1704 * Convert a string of digits to an integer, printing an error message on
1708 number(const char *s)
1711 ash_msg_and_raise_error(msg_illnum, s);
1716 * Produce a possibly single quoted string suitable as input to the shell.
1717 * The return string is allocated on the stack.
1720 single_quote(const char *s)
1730 len = strchrnul(s, '\'') - s;
1732 q = p = makestrspace(len + 3, p);
1735 q = (char *)memcpy(q, s, len) + len;
1744 do len++; while (*++s == '\'');
1746 q = p = makestrspace(len + 3, p);
1749 q = (char *)memcpy(q, s - len, len) + len;
1757 return stackblock();
1761 /* ============ nextopt */
1763 static char **argptr; /* argument list for builtin commands */
1764 static char *optionarg; /* set by nextopt (like getopt) */
1765 static char *optptr; /* used by nextopt */
1768 * XXX - should get rid of. Have all builtins use getopt(3).
1769 * The library getopt must have the BSD extension static variable
1770 * "optreset", otherwise it can't be used within the shell safely.
1772 * Standard option processing (a la getopt) for builtin routines.
1773 * The only argument that is passed to nextopt is the option string;
1774 * the other arguments are unnecessary. It returns the character,
1775 * or '\0' on end of input.
1778 nextopt(const char *optstring)
1785 if (p == NULL || *p == '\0') {
1786 /* We ate entire "-param", take next one */
1792 if (*++p == '\0') /* just "-" ? */
1795 if (LONE_DASH(p)) /* "--" ? */
1797 /* p => next "-param" */
1799 /* p => some option char in the middle of a "-param" */
1801 for (q = optstring; *q != c;) {
1803 ash_msg_and_raise_error("illegal option -%c", c);
1811 ash_msg_and_raise_error("no arg for -%c option", c);
1821 /* ============ Shell variables */
1824 * The parsefile structure pointed to by the global variable parsefile
1825 * contains information about the current file being read.
1828 int nparam; /* # of positional parameters (without $0) */
1829 #if ENABLE_ASH_GETOPTS
1830 int optind; /* next parameter to be processed by getopts */
1831 int optoff; /* used by getopts */
1833 unsigned char malloced; /* if parameter list dynamically allocated */
1834 char **p; /* parameter list */
1838 * Free the list of positional parameters.
1841 freeparam(volatile struct shparam *param)
1843 if (param->malloced) {
1845 ap = ap1 = param->p;
1852 #if ENABLE_ASH_GETOPTS
1853 static void FAST_FUNC getoptsreset(const char *value);
1857 struct var *next; /* next entry in hash list */
1858 int flags; /* flags are defined above */
1859 const char *var_text; /* name=value */
1860 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1861 /* the variable gets set/unset */
1865 struct localvar *next; /* next local variable in list */
1866 struct var *vp; /* the variable that was made local */
1867 int flags; /* saved flags */
1868 const char *text; /* saved text */
1872 #define VEXPORT 0x01 /* variable is exported */
1873 #define VREADONLY 0x02 /* variable cannot be modified */
1874 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1875 #define VTEXTFIXED 0x08 /* text is statically allocated */
1876 #define VSTACK 0x10 /* text is allocated on the stack */
1877 #define VUNSET 0x20 /* the variable is not set */
1878 #define VNOFUNC 0x40 /* don't call the callback function */
1879 #define VNOSET 0x80 /* do not set variable - just readonly test */
1880 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1881 #if ENABLE_ASH_RANDOM_SUPPORT
1882 # define VDYNAMIC 0x200 /* dynamic variable */
1888 /* Need to be before varinit_data[] */
1889 #if ENABLE_LOCALE_SUPPORT
1890 static void FAST_FUNC
1891 change_lc_all(const char *value)
1893 if (value && *value != '\0')
1894 setlocale(LC_ALL, value);
1896 static void FAST_FUNC
1897 change_lc_ctype(const char *value)
1899 if (value && *value != '\0')
1900 setlocale(LC_CTYPE, value);
1904 static void chkmail(void);
1905 static void changemail(const char *var_value) FAST_FUNC;
1907 # define chkmail() ((void)0)
1909 static void changepath(const char *) FAST_FUNC;
1910 #if ENABLE_ASH_RANDOM_SUPPORT
1911 static void change_random(const char *) FAST_FUNC;
1914 static const struct {
1916 const char *var_text;
1917 void (*var_func)(const char *) FAST_FUNC;
1918 } varinit_data[] = {
1920 * Note: VEXPORT would not work correctly here for NOFORK applets:
1921 * some environment strings may be constant.
1923 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1925 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1926 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1928 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1929 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1930 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1931 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1932 #if ENABLE_ASH_GETOPTS
1933 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1935 #if ENABLE_ASH_RANDOM_SUPPORT
1936 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1938 #if ENABLE_LOCALE_SUPPORT
1939 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1940 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1942 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1943 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1949 struct globals_var {
1950 struct shparam shellparam; /* $@ current positional parameters */
1951 struct redirtab *redirlist;
1952 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1953 struct var *vartab[VTABSIZE];
1954 struct var varinit[ARRAY_SIZE(varinit_data)];
1956 extern struct globals_var *const ash_ptr_to_globals_var;
1957 #define G_var (*ash_ptr_to_globals_var)
1958 #define shellparam (G_var.shellparam )
1959 //#define redirlist (G_var.redirlist )
1960 #define preverrout_fd (G_var.preverrout_fd)
1961 #define vartab (G_var.vartab )
1962 #define varinit (G_var.varinit )
1963 #define INIT_G_var() do { \
1965 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1967 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1968 varinit[i].flags = varinit_data[i].flags; \
1969 varinit[i].var_text = varinit_data[i].var_text; \
1970 varinit[i].var_func = varinit_data[i].var_func; \
1974 #define vifs varinit[0]
1976 # define vmail (&vifs)[1]
1977 # define vmpath (&vmail)[1]
1978 # define vpath (&vmpath)[1]
1980 # define vpath (&vifs)[1]
1982 #define vps1 (&vpath)[1]
1983 #define vps2 (&vps1)[1]
1984 #define vps4 (&vps2)[1]
1985 #if ENABLE_ASH_GETOPTS
1986 # define voptind (&vps4)[1]
1987 # if ENABLE_ASH_RANDOM_SUPPORT
1988 # define vrandom (&voptind)[1]
1991 # if ENABLE_ASH_RANDOM_SUPPORT
1992 # define vrandom (&vps4)[1]
1997 * The following macros access the values of the above variables.
1998 * They have to skip over the name. They return the null string
1999 * for unset variables.
2001 #define ifsval() (vifs.var_text + 4)
2002 #define ifsset() ((vifs.flags & VUNSET) == 0)
2004 # define mailval() (vmail.var_text + 5)
2005 # define mpathval() (vmpath.var_text + 9)
2006 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2008 #define pathval() (vpath.var_text + 5)
2009 #define ps1val() (vps1.var_text + 4)
2010 #define ps2val() (vps2.var_text + 4)
2011 #define ps4val() (vps4.var_text + 4)
2012 #if ENABLE_ASH_GETOPTS
2013 # define optindval() (voptind.var_text + 7)
2016 #if ENABLE_ASH_GETOPTS
2017 static void FAST_FUNC
2018 getoptsreset(const char *value)
2020 shellparam.optind = number(value) ?: 1;
2021 shellparam.optoff = -1;
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)) {
2036 if (c == '\0' || c == '=')
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 reinit_unicode_for_ash(void)
2137 /* Unicode support should be activated even if LANG is set
2138 * _during_ shell execution, not only if it was set when
2139 * shell was started. Therefore, re-check LANG every time:
2141 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2142 || ENABLE_UNICODE_USING_LOCALE
2144 const char *s = lookupvar("LC_ALL");
2145 if (!s) s = lookupvar("LC_CTYPE");
2146 if (!s) s = lookupvar("LANG");
2152 * Search the environment of a builtin command.
2155 bltinlookup(const char *name)
2159 for (sp = cmdenviron; sp; sp = sp->next) {
2160 if (varcmp(sp->text, name) == 0)
2161 return var_end(sp->text);
2163 return lookupvar(name);
2167 * Same as setvar except that the variable and value are passed in
2168 * the first argument as name=value. Since the first argument will
2169 * be actually stored in the table, it should not be a string that
2171 * Called with interrupts off.
2174 setvareq(char *s, int flags)
2176 struct var *vp, **vpp;
2179 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2180 vp = *findvar(vpp, s);
2182 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2185 if (flags & VNOSAVE)
2188 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2194 if (vp->var_func && !(flags & VNOFUNC))
2195 vp->var_func(var_end(s));
2197 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2198 free((char*)vp->var_text);
2200 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2202 /* variable s is not found */
2205 vp = ckzalloc(sizeof(*vp));
2207 /*vp->func = NULL; - ckzalloc did it */
2210 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2217 * Set the value of a variable. The flags argument is ored with the
2218 * flags of the variable. If val is NULL, the variable is unset.
2221 setvar(const char *name, const char *val, int flags)
2229 q = endofname(name);
2230 p = strchrnul(q, '=');
2232 if (!namelen || p != q)
2233 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2238 vallen = strlen(val);
2242 nameeq = ckmalloc(namelen + vallen + 2);
2243 p = memcpy(nameeq, name, namelen) + namelen;
2246 p = memcpy(p, val, vallen) + vallen;
2249 setvareq(nameeq, flags | VNOSAVE);
2253 static void FAST_FUNC
2254 setvar0(const char *name, const char *val)
2256 setvar(name, val, 0);
2260 * Unset the specified variable.
2263 unsetvar(const char *s)
2269 vpp = findvar(hashvar(s), s);
2273 int flags = vp->flags;
2276 if (flags & VREADONLY)
2278 #if ENABLE_ASH_RANDOM_SUPPORT
2279 vp->flags &= ~VDYNAMIC;
2283 if ((flags & VSTRFIXED) == 0) {
2285 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2286 free((char*)vp->var_text);
2292 vp->flags &= ~VEXPORT;
2302 * Process a linked list of variable assignments.
2305 listsetvar(struct strlist *list_set_var, int flags)
2307 struct strlist *lp = list_set_var;
2313 setvareq(lp->text, flags);
2320 * Generate a list of variables satisfying the given conditions.
2323 listvars(int on, int off, char ***end)
2334 for (vp = *vpp; vp; vp = vp->next) {
2335 if ((vp->flags & mask) == on) {
2336 if (ep == stackstrend())
2337 ep = growstackstr();
2338 *ep++ = (char*)vp->var_text;
2341 } while (++vpp < vartab + VTABSIZE);
2342 if (ep == stackstrend())
2343 ep = growstackstr();
2347 return grabstackstr(ep);
2351 /* ============ Path search helper
2353 * The variable path (passed by reference) should be set to the start
2354 * of the path before the first call; path_advance will update
2355 * this value as it proceeds. Successive calls to path_advance will return
2356 * the possible path expansions in sequence. If an option (indicated by
2357 * a percent sign) appears in the path entry then the global variable
2358 * pathopt will be set to point to it; otherwise pathopt will be set to
2361 static const char *pathopt; /* set by path_advance */
2364 path_advance(const char **path, const char *name)
2374 for (p = start; *p && *p != ':' && *p != '%'; p++)
2376 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2377 while (stackblocksize() < len)
2381 memcpy(q, start, p - start);
2389 while (*p && *p != ':')
2396 return stalloc(len);
2400 /* ============ Prompt */
2402 static smallint doprompt; /* if set, prompt the user */
2403 static smallint needprompt; /* true if interactive and at start of line */
2405 #if ENABLE_FEATURE_EDITING
2406 static line_input_t *line_input_state;
2407 static const char *cmdedit_prompt;
2409 putprompt(const char *s)
2411 if (ENABLE_ASH_EXPAND_PRMT) {
2412 free((char*)cmdedit_prompt);
2413 cmdedit_prompt = ckstrdup(s);
2420 putprompt(const char *s)
2426 #if ENABLE_ASH_EXPAND_PRMT
2427 /* expandstr() needs parsing machinery, so it is far away ahead... */
2428 static const char *expandstr(const char *ps);
2430 #define expandstr(s) s
2434 setprompt_if(smallint do_set, int whichprompt)
2437 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2444 switch (whichprompt) {
2454 #if ENABLE_ASH_EXPAND_PRMT
2455 pushstackmark(&smark, stackblocksize());
2457 putprompt(expandstr(prompt));
2458 #if ENABLE_ASH_EXPAND_PRMT
2459 popstackmark(&smark);
2464 /* ============ The cd and pwd commands */
2466 #define CD_PHYSICAL 1
2476 while ((i = nextopt("LP")) != '\0') {
2478 flags ^= CD_PHYSICAL;
2487 * Update curdir (the name of the current directory) in response to a
2491 updatepwd(const char *dir)
2498 cdcomppath = sstrdup(dir);
2501 if (curdir == nullstr)
2503 new = stack_putstr(curdir, new);
2505 new = makestrspace(strlen(dir) + 2, new);
2506 lim = (char *)stackblock() + 1;
2510 if (new > lim && *lim == '/')
2515 if (dir[1] == '/' && dir[2] != '/') {
2521 p = strtok(cdcomppath, "/");
2525 if (p[1] == '.' && p[2] == '\0') {
2537 new = stack_putstr(p, new);
2540 p = strtok(NULL, "/");
2545 return stackblock();
2549 * Find out what the current directory is. If we already know the current
2550 * directory, this routine returns immediately.
2555 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2556 return dir ? dir : nullstr;
2560 setpwd(const char *val, int setold)
2564 oldcur = dir = curdir;
2567 setvar("OLDPWD", oldcur, VEXPORT);
2570 if (physdir != nullstr) {
2571 if (physdir != oldcur)
2575 if (oldcur == val || !val) {
2581 dir = ckstrdup(val);
2582 if (oldcur != dir && oldcur != nullstr) {
2587 setvar("PWD", dir, VEXPORT);
2590 static void hashcd(void);
2593 * Actually do the chdir. We also call hashcd to let other routines
2594 * know that the current directory has changed.
2597 docd(const char *dest, int flags)
2599 const char *dir = NULL;
2602 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2605 if (!(flags & CD_PHYSICAL)) {
2606 dir = updatepwd(dest);
2620 static int FAST_FUNC
2621 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2633 dest = bltinlookup("HOME");
2634 else if (LONE_DASH(dest)) {
2635 dest = bltinlookup("OLDPWD");
2657 path = bltinlookup("CDPATH");
2660 p = path_advance(&path, dest);
2661 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2665 if (!docd(p, flags))
2676 ash_msg_and_raise_error("can't cd to %s", dest);
2679 if (flags & CD_PRINT)
2680 out1fmt("%s\n", curdir);
2684 static int FAST_FUNC
2685 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2688 const char *dir = curdir;
2692 if (physdir == nullstr)
2696 out1fmt("%s\n", dir);
2701 /* ============ ... */
2704 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2706 /* Syntax classes */
2707 #define CWORD 0 /* character is nothing special */
2708 #define CNL 1 /* newline character */
2709 #define CBACK 2 /* a backslash character */
2710 #define CSQUOTE 3 /* single quote */
2711 #define CDQUOTE 4 /* double quote */
2712 #define CENDQUOTE 5 /* a terminating quote */
2713 #define CBQUOTE 6 /* backwards single quote */
2714 #define CVAR 7 /* a dollar sign */
2715 #define CENDVAR 8 /* a '}' character */
2716 #define CLP 9 /* a left paren in arithmetic */
2717 #define CRP 10 /* a right paren in arithmetic */
2718 #define CENDFILE 11 /* end of file */
2719 #define CCTL 12 /* like CWORD, except it must be escaped */
2720 #define CSPCL 13 /* these terminate a word */
2721 #define CIGN 14 /* character should be ignored */
2724 #if ENABLE_ASH_ALIAS
2728 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2730 #if ENABLE_SH_MATH_SUPPORT
2731 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2733 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2735 static const uint16_t S_I_T[] ALIGN2 = {
2736 #if ENABLE_ASH_ALIAS
2737 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2739 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2740 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2741 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2742 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2743 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2744 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2745 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2746 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2747 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2748 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2749 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2750 #if !USE_SIT_FUNCTION
2751 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2752 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2753 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2757 /* Constants below must match table above */
2759 #if ENABLE_ASH_ALIAS
2760 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2762 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2763 CNL_CNL_CNL_CNL , /* 2 */
2764 CWORD_CCTL_CCTL_CWORD , /* 3 */
2765 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2766 CVAR_CVAR_CWORD_CVAR , /* 5 */
2767 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2768 CSPCL_CWORD_CWORD_CLP , /* 7 */
2769 CSPCL_CWORD_CWORD_CRP , /* 8 */
2770 CBACK_CBACK_CCTL_CBACK , /* 9 */
2771 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2772 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2773 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2774 CWORD_CWORD_CWORD_CWORD , /* 13 */
2775 CCTL_CCTL_CCTL_CCTL , /* 14 */
2778 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2779 * caller must ensure proper cast on it if c is *char_ptr!
2781 /* Values for syntax param */
2782 #define BASESYNTAX 0 /* not in quotes */
2783 #define DQSYNTAX 1 /* in double quotes */
2784 #define SQSYNTAX 2 /* in single quotes */
2785 #define ARISYNTAX 3 /* in arithmetic */
2786 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2788 #if USE_SIT_FUNCTION
2791 SIT(int c, int syntax)
2793 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2794 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2796 * This causes '/' to be prepended with CTLESC in dquoted string,
2797 * making "./file"* treated incorrectly because we feed
2798 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2799 * The "homegrown" glob implementation is okay with that,
2800 * but glibc one isn't. With '/' always treated as CWORD,
2803 # if ENABLE_ASH_ALIAS
2804 static const uint8_t syntax_index_table[] ALIGN1 = {
2805 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2806 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2807 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2811 static const uint8_t syntax_index_table[] ALIGN1 = {
2812 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2813 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2814 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2823 # if ENABLE_ASH_ALIAS
2829 /* Cast is purely for paranoia here,
2830 * just in case someone passed signed char to us */
2831 if ((unsigned char)c >= CTL_FIRST
2832 && (unsigned char)c <= CTL_LAST
2836 s = strchrnul(spec_symbls, c);
2839 indx = syntax_index_table[s - spec_symbls];
2841 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2844 #else /* !USE_SIT_FUNCTION */
2846 static const uint8_t syntax_index_table[] ALIGN1 = {
2847 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2848 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2858 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2859 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2881 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2882 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2883 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2884 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2885 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2886 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2887 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2888 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2889 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2890 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2891 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2893 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2894 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2895 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2896 /* 47 "/" */ CWORD_CWORD_CWORD_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)
3140 unsigned int hashval;
3147 ch = (unsigned char)*p;
3151 ch = (unsigned char)*++p;
3153 app = &atab[hashval % ATABSIZE];
3155 for (; *app; app = &(*app)->next) {
3156 if (strcmp(name, (*app)->name) == 0) {
3164 static struct alias *
3165 lookupalias(const char *name, int check)
3167 struct alias *ap = *__lookupalias(name);
3169 if (check && ap && (ap->flag & ALIASINUSE))
3174 static struct alias *
3175 freealias(struct alias *ap)
3179 if (ap->flag & ALIASINUSE) {
3180 ap->flag |= ALIASDEAD;
3192 setalias(const char *name, const char *val)
3194 struct alias *ap, **app;
3196 app = __lookupalias(name);
3200 if (!(ap->flag & ALIASINUSE)) {
3203 ap->val = ckstrdup(val);
3204 ap->flag &= ~ALIASDEAD;
3207 ap = ckzalloc(sizeof(struct alias));
3208 ap->name = ckstrdup(name);
3209 ap->val = ckstrdup(val);
3210 /*ap->flag = 0; - ckzalloc did it */
3211 /*ap->next = NULL;*/
3218 unalias(const char *name)
3222 app = __lookupalias(name);
3226 *app = freealias(*app);
3237 struct alias *ap, **app;
3241 for (i = 0; i < ATABSIZE; i++) {
3243 for (ap = *app; ap; ap = *app) {
3244 *app = freealias(*app);
3254 printalias(const struct alias *ap)
3256 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3260 * TODO - sort output
3262 static int FAST_FUNC
3263 aliascmd(int argc UNUSED_PARAM, char **argv)
3272 for (i = 0; i < ATABSIZE; i++) {
3273 for (ap = atab[i]; ap; ap = ap->next) {
3279 while ((n = *++argv) != NULL) {
3280 v = strchr(n+1, '=');
3281 if (v == NULL) { /* n+1: funny ksh stuff */
3282 ap = *__lookupalias(n);
3284 fprintf(stderr, "%s: %s not found\n", "alias", n);
3297 static int FAST_FUNC
3298 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3302 while ((i = nextopt("a")) != '\0') {
3308 for (i = 0; *argptr; argptr++) {
3309 if (unalias(*argptr)) {
3310 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3318 #endif /* ASH_ALIAS */
3321 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3324 #define FORK_NOJOB 2
3326 /* mode flags for showjob(s) */
3327 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3328 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3329 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3330 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
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;
3494 act.sa_handler = SIG_IGN;
3498 /* flags and mask matter only if !DFL and !IGN, but we do it
3499 * for all cases for more deterministic behavior:
3502 sigfillset(&act.sa_mask);
3504 sigaction_set(signo, &act);
3509 /* mode flags for set_curjob */
3510 #define CUR_DELETE 2
3511 #define CUR_RUNNING 1
3512 #define CUR_STOPPED 0
3514 /* mode flags for dowait */
3515 #define DOWAIT_NONBLOCK 0
3516 #define DOWAIT_BLOCK 1
3519 /* pgrp of shell on invocation */
3520 static int initialpgrp; //references:2
3521 static int ttyfd = -1; //5
3524 static struct job *jobtab; //5
3526 static unsigned njobs; //4
3528 static struct job *curjob; //lots
3529 /* number of presumed living untracked jobs */
3530 static int jobless; //4
3533 set_curjob(struct job *jp, unsigned mode)
3536 struct job **jpp, **curp;
3538 /* first remove from list */
3539 jpp = curp = &curjob;
3544 jpp = &jp1->prev_job;
3546 *jpp = jp1->prev_job;
3548 /* Then re-insert in correct position */
3556 /* job being deleted */
3559 /* newly created job or backgrounded job,
3560 * put after all stopped jobs.
3565 if (!jp1 || jp1->state != JOBSTOPPED)
3568 jpp = &jp1->prev_job;
3574 /* newly stopped job - becomes curjob */
3575 jp->prev_job = *jpp;
3583 jobno(const struct job *jp)
3585 return jp - jobtab + 1;
3590 * Convert a job name to a job structure.
3593 #define getjob(name, getctl) getjob(name)
3596 getjob(const char *name, int getctl)
3600 const char *err_msg = "%s: no such job";
3604 char *(*match)(const char *, const char *);
3619 if (c == '+' || c == '%') {
3621 err_msg = "No current job";
3627 err_msg = "No previous job";
3637 if (num > 0 && num <= njobs) {
3638 jp = jobtab + num - 1;
3653 if (match(jp->ps[0].ps_cmd, p)) {
3657 err_msg = "%s: ambiguous";
3667 err_msg = "job %s not created under job control";
3668 if (getctl && jp->jobctl == 0)
3673 ash_msg_and_raise_error(err_msg, name);
3677 * Mark a job structure as unused.
3680 freejob(struct job *jp)
3682 struct procstat *ps;
3686 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3687 if (ps->ps_cmd != nullstr)
3690 if (jp->ps != &jp->ps0)
3693 set_curjob(jp, CUR_DELETE);
3699 xtcsetpgrp(int fd, pid_t pgrp)
3701 if (tcsetpgrp(fd, pgrp))
3702 ash_msg_and_raise_error("can't set tty process group (%m)");
3706 * Turn job control on and off.
3708 * Note: This code assumes that the third arg to ioctl is a character
3709 * pointer, which is true on Berkeley systems but not System V. Since
3710 * System V doesn't have job control yet, this isn't a problem now.
3712 * Called with interrupts off.
3720 if (on == doing_jobctl || rootshell == 0)
3724 ofd = fd = open(_PATH_TTY, O_RDWR);
3726 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3727 * That sometimes helps to acquire controlling tty.
3728 * Obviously, a workaround for bugs when someone
3729 * failed to provide a controlling tty to bash! :) */
3735 /* fd is a tty at this point */
3736 fd = fcntl(fd, F_DUPFD, 10);
3737 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3740 goto out; /* F_DUPFD failed */
3741 close_on_exec_on(fd);
3742 while (1) { /* while we are in the background */
3743 pgrp = tcgetpgrp(fd);
3746 ash_msg("can't access tty; job control turned off");
3750 if (pgrp == getpgrp())
3761 xtcsetpgrp(fd, pgrp);
3763 /* turning job control off */
3766 /* was xtcsetpgrp, but this can make exiting ash
3767 * loop forever if pty is already deleted */
3768 tcsetpgrp(fd, pgrp);
3782 static int FAST_FUNC
3783 killcmd(int argc, char **argv)
3785 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3788 if (argv[i][0] == '%') {
3790 * "kill %N" - job kill
3791 * Converting to pgrp / pid kill
3797 jp = getjob(argv[i], 0);
3799 * In jobs started under job control, we signal
3800 * entire process group by kill -PGRP_ID.
3801 * This happens, f.e., in interactive shell.
3803 * Otherwise, we signal each child via
3804 * kill PID1 PID2 PID3.
3806 * sh -c 'sleep 1|sleep 1 & kill %1'
3807 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3808 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3810 n = jp->nprocs; /* can't be 0 (I hope) */
3813 dst = alloca(n * sizeof(int)*4);
3815 for (j = 0; j < n; j++) {
3816 struct procstat *ps = &jp->ps[j];
3817 /* Skip non-running and not-stopped members
3818 * (i.e. dead members) of the job
3820 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3823 * kill_main has matching code to expect
3824 * leading space. Needed to not confuse
3825 * negative pids with "kill -SIGNAL_NO" syntax
3827 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3831 } while (argv[++i]);
3833 return kill_main(argc, argv);
3837 showpipe(struct job *jp /*, FILE *out*/)
3839 struct procstat *ps;
3840 struct procstat *psend;
3842 psend = jp->ps + jp->nprocs;
3843 for (ps = jp->ps + 1; ps < psend; ps++)
3844 printf(" | %s", ps->ps_cmd);
3845 newline_and_flush(stdout);
3846 flush_stdout_stderr();
3851 restartjob(struct job *jp, int mode)
3853 struct procstat *ps;
3859 if (jp->state == JOBDONE)
3861 jp->state = JOBRUNNING;
3862 pgid = jp->ps[0].ps_pid;
3863 if (mode == FORK_FG)
3864 xtcsetpgrp(ttyfd, pgid);
3865 killpg(pgid, SIGCONT);
3869 if (WIFSTOPPED(ps->ps_status)) {
3875 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3880 static int FAST_FUNC
3881 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3887 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3891 jp = getjob(*argv, 1);
3892 if (mode == FORK_BG) {
3893 set_curjob(jp, CUR_RUNNING);
3894 printf("[%d] ", jobno(jp));
3896 out1str(jp->ps[0].ps_cmd);
3897 showpipe(jp /*, stdout*/);
3898 retval = restartjob(jp, mode);
3899 } while (*argv && *++argv);
3905 sprint_status48(char *s, int status, int sigonly)
3911 if (!WIFEXITED(status)) {
3912 if (JOBS && WIFSTOPPED(status))
3913 st = WSTOPSIG(status);
3915 st = WTERMSIG(status);
3917 if (st == SIGINT || st == SIGPIPE)
3919 if (JOBS && WIFSTOPPED(status))
3923 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3924 col = fmtstr(s, 32, strsignal(st));
3925 if (WCOREDUMP(status)) {
3926 strcpy(s + col, " (core dumped)");
3927 col += sizeof(" (core dumped)")-1;
3929 } else if (!sigonly) {
3930 st = WEXITSTATUS(status);
3931 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3938 dowait(int block, struct job *job)
3944 struct job *thisjob;
3946 TRACE(("dowait(0x%x) called\n", block));
3948 /* Do a wait system call. If job control is compiled in, we accept
3949 * stopped processes.
3950 * NB: _not_ safe_waitpid, we need to detect EINTR.
3953 if (block == DOWAIT_NONBLOCK)
3954 wait_flags = WNOHANG;
3956 wait_flags |= WUNTRACED;
3957 pid = waitpid(-1, &status, wait_flags);
3958 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3959 pid, status, errno, strerror(errno)));
3965 for (jp = curjob; jp; jp = jp->prev_job) {
3967 struct procstat *ps;
3968 struct procstat *psend;
3969 if (jp->state == JOBDONE)
3973 psend = ps + jp->nprocs;
3975 if (ps->ps_pid == pid) {
3976 TRACE(("Job %d: changing status of proc %d "
3977 "from 0x%x to 0x%x\n",
3978 jobno(jp), pid, ps->ps_status, status));
3979 ps->ps_status = status;
3982 if (ps->ps_status == -1)
3983 jobstate = JOBRUNNING;
3985 if (jobstate == JOBRUNNING)
3987 if (WIFSTOPPED(ps->ps_status)) {
3988 jp->stopstatus = ps->ps_status;
3989 jobstate = JOBSTOPPED;
3992 } while (++ps < psend);
3996 /* Found the job where one of its processes changed its state.
3997 * Is there at least one live and running process in this job? */
3998 if (jobstate != JOBRUNNING) {
3999 /* No. All live processes in the job are stopped
4000 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4002 thisjob->changed = 1;
4003 if (thisjob->state != jobstate) {
4004 TRACE(("Job %d: changing state from %d to %d\n",
4005 jobno(thisjob), thisjob->state, jobstate));
4006 thisjob->state = jobstate;
4008 if (jobstate == JOBSTOPPED)
4009 set_curjob(thisjob, CUR_STOPPED);
4015 /* The process wasn't found in job list */
4016 if (JOBS && !WIFSTOPPED(status))
4021 if (thisjob && thisjob == job) {
4025 len = sprint_status48(s, status, 1);
4036 blocking_dowait_with_raise_on_sig(void)
4038 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4039 if (pid <= 0 && pending_sig)
4040 raise_exception(EXSIG);
4046 showjob(struct job *jp, int mode)
4048 struct procstat *ps;
4049 struct procstat *psend;
4052 char s[16 + 16 + 48];
4053 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4057 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4058 /* just output process (group) id of pipeline */
4059 fprintf(out, "%d\n", ps->ps_pid);
4063 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4068 else if (curjob && jp == curjob->prev_job)
4071 if (mode & SHOW_PIDS)
4072 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4074 psend = ps + jp->nprocs;
4076 if (jp->state == JOBRUNNING) {
4077 strcpy(s + col, "Running");
4078 col += sizeof("Running") - 1;
4080 int status = psend[-1].ps_status;
4081 if (jp->state == JOBSTOPPED)
4082 status = jp->stopstatus;
4083 col += sprint_status48(s + col, status, 0);
4085 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4087 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4088 * or prints several "PID | <cmdN>" lines,
4089 * depending on SHOW_PIDS bit.
4090 * We do not print status of individual processes
4091 * between PID and <cmdN>. bash does it, but not very well:
4092 * first line shows overall job status, not process status,
4093 * making it impossible to know 1st process status.
4097 /* for each process */
4100 if (mode & SHOW_PIDS)
4101 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4103 fprintf(out, "%s%*c%s%s",
4105 33 - col >= 0 ? 33 - col : 0, ' ',
4106 ps == jp->ps ? "" : "| ",
4109 } while (++ps != psend);
4110 newline_and_flush(out);
4114 if (jp->state == JOBDONE) {
4115 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4121 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4122 * statuses have changed since the last call to showjobs.
4129 TRACE(("showjobs(0x%x) called\n", mode));
4131 /* Handle all finished jobs */
4132 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4135 for (jp = curjob; jp; jp = jp->prev_job) {
4136 if (!(mode & SHOW_CHANGED) || jp->changed) {
4142 static int FAST_FUNC
4143 jobscmd(int argc UNUSED_PARAM, char **argv)
4148 while ((m = nextopt("lp")) != '\0') {
4152 mode |= SHOW_ONLY_PGID;
4158 showjob(getjob(*argv, 0), mode);
4168 /* Called only on finished or stopped jobs (no members are running) */
4170 getstatus(struct job *job)
4174 struct procstat *ps;
4176 /* Fetch last member's status */
4177 ps = job->ps + job->nprocs - 1;
4178 status = ps->ps_status;
4180 /* "set -o pipefail" mode: use last _nonzero_ status */
4181 while (status == 0 && --ps >= job->ps)
4182 status = ps->ps_status;
4185 retval = WEXITSTATUS(status);
4186 if (!WIFEXITED(status)) {
4188 retval = WSTOPSIG(status);
4189 if (!WIFSTOPPED(status))
4192 /* XXX: limits number of signals */
4193 retval = WTERMSIG(status);
4195 if (retval == SIGINT)
4201 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4202 jobno(job), job->nprocs, status, retval));
4206 static int FAST_FUNC
4207 waitcmd(int argc UNUSED_PARAM, char **argv)
4214 raise_exception(EXSIG);
4221 /* wait for all jobs */
4225 if (!jp) /* no running procs */
4227 if (jp->state == JOBRUNNING)
4232 blocking_dowait_with_raise_on_sig();
4234 * "When bash is waiting for an asynchronous command via
4235 * the wait builtin, the reception of a signal for which a trap
4236 * has been set will cause the wait builtin to return immediately
4237 * with an exit status greater than 128, immediately after which
4238 * the trap is executed."
4240 * blocking_dowait_with_raise_on_sig raises signal handlers
4241 * if it gets no pid (pid < 0). However,
4242 * if child sends us a signal *and immediately exits*,
4243 * blocking_dowait_with_raise_on_sig gets pid > 0
4244 * and does not handle pending_sig. Check this case: */
4246 raise_exception(EXSIG);
4252 if (**argv != '%') {
4253 pid_t pid = number(*argv);
4258 if (job->ps[job->nprocs - 1].ps_pid == pid)
4260 job = job->prev_job;
4263 job = getjob(*argv, 0);
4265 /* loop until process terminated or stopped */
4266 while (job->state == JOBRUNNING)
4267 blocking_dowait_with_raise_on_sig();
4269 retval = getstatus(job);
4282 struct job *jp, *jq;
4284 len = njobs * sizeof(*jp);
4286 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4288 offset = (char *)jp - (char *)jq;
4290 /* Relocate pointers */
4293 jq = (struct job *)((char *)jq + l);
4297 #define joff(p) ((struct job *)((char *)(p) + l))
4298 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4299 if (joff(jp)->ps == &jq->ps0)
4300 jmove(joff(jp)->ps);
4301 if (joff(jp)->prev_job)
4302 jmove(joff(jp)->prev_job);
4312 jp = (struct job *)((char *)jp + len);
4316 } while (--jq >= jp);
4321 * Return a new job structure.
4322 * Called with interrupts off.
4325 makejob(/*union node *node,*/ int nprocs)
4330 for (i = njobs, jp = jobtab; ; jp++) {
4337 if (jp->state != JOBDONE || !jp->waited)
4346 memset(jp, 0, sizeof(*jp));
4348 /* jp->jobctl is a bitfield.
4349 * "jp->jobctl |= jobctl" likely to give awful code */
4353 jp->prev_job = curjob;
4358 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4360 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4367 * Return a string identifying a command (to be printed by the
4370 static char *cmdnextc;
4373 cmdputs(const char *s)
4375 static const char vstype[VSTYPE + 1][3] = {
4376 "", "}", "-", "+", "?", "=",
4377 "%", "%%", "#", "##"
4378 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4381 const char *p, *str;
4385 unsigned char subtype = 0;
4389 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4391 while ((c = *p++) != '\0') {
4399 if ((subtype & VSTYPE) == VSLENGTH)
4405 str = "\"}" + !(quoted & 1);
4412 #if ENABLE_SH_MATH_SUPPORT
4427 if ((subtype & VSTYPE) != VSNORMAL)
4429 str = vstype[subtype & VSTYPE];
4430 if (subtype & VSNUL)
4439 /* These can only happen inside quotes */
4452 while ((c = *str++) != '\0') {
4455 } /* while *p++ not NUL */
4458 USTPUTC('"', nextc);
4464 /* cmdtxt() and cmdlist() call each other */
4465 static void cmdtxt(union node *n);
4468 cmdlist(union node *np, int sep)
4470 for (; np; np = np->narg.next) {
4474 if (sep && np->narg.next)
4480 cmdtxt(union node *n)
4483 struct nodelist *lp;
4494 lp = n->npipe.cmdlist;
4512 cmdtxt(n->nbinary.ch1);
4528 cmdtxt(n->nif.test);
4530 if (n->nif.elsepart) {
4531 cmdtxt(n->nif.ifpart);
4533 n = n->nif.elsepart;
4551 cmdtxt(n->nbinary.ch1);
4561 cmdputs(n->nfor.var);
4563 cmdlist(n->nfor.args, 1);
4568 cmdputs(n->narg.text);
4572 cmdlist(n->ncmd.args, 1);
4573 cmdlist(n->ncmd.redirect, 0);
4586 cmdputs(n->ncase.expr->narg.text);
4588 for (np = n->ncase.cases; np; np = np->nclist.next) {
4589 cmdtxt(np->nclist.pattern);
4591 cmdtxt(np->nclist.body);
4605 #if ENABLE_ASH_BASH_COMPAT
4620 cmdputs(utoa(n->nfile.fd));
4622 if (n->type == NTOFD || n->type == NFROMFD) {
4623 cmdputs(utoa(n->ndup.dupfd));
4632 commandtext(union node *n)
4636 STARTSTACKSTR(cmdnextc);
4638 name = stackblock();
4639 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4640 return ckstrdup(name);
4645 * Fork off a subshell. If we are doing job control, give the subshell its
4646 * own process group. Jp is a job structure that the job is to be added to.
4647 * N is the command that will be evaluated by the child. Both jp and n may
4648 * be NULL. The mode parameter can be one of the following:
4649 * FORK_FG - Fork off a foreground process.
4650 * FORK_BG - Fork off a background process.
4651 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4652 * process group even if job control is on.
4654 * When job control is turned off, background processes have their standard
4655 * input redirected to /dev/null (except for the second and later processes
4658 * Called with interrupts off.
4661 * Clear traps on a fork.
4669 for (tp = trap; tp < &trap[NSIG]; tp++) {
4670 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4671 if (trap_ptr == trap)
4673 /* else: it "belongs" to trap_ptr vector, don't free */
4675 if ((tp - trap) != 0)
4676 setsignal(tp - trap);
4683 /* Lives far away from here, needed for forkchild */
4684 static void closescript(void);
4686 /* Called after fork(), in child */
4687 /* jp and n are NULL when called by openhere() for heredoc support */
4688 static NOINLINE void
4689 forkchild(struct job *jp, union node *n, int mode)
4693 TRACE(("Child shell %d\n", getpid()));
4697 /* man bash: "Non-builtin commands run by bash have signal handlers
4698 * set to the values inherited by the shell from its parent".
4699 * Do we do it correctly? */
4703 if (mode == FORK_NOJOB /* is it `xxx` ? */
4704 && n && n->type == NCMD /* is it single cmd? */
4705 /* && n->ncmd.args->type == NARG - always true? */
4706 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4707 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4708 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4710 TRACE(("Trap hack\n"));
4711 /* Awful hack for `trap` or $(trap).
4713 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4714 * contains an example where "trap" is executed in a subshell:
4716 * save_traps=$(trap)
4718 * eval "$save_traps"
4720 * Standard does not say that "trap" in subshell shall print
4721 * parent shell's traps. It only says that its output
4722 * must have suitable form, but then, in the above example
4723 * (which is not supposed to be normative), it implies that.
4725 * bash (and probably other shell) does implement it
4726 * (traps are reset to defaults, but "trap" still shows them),
4727 * but as a result, "trap" logic is hopelessly messed up:
4730 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4731 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4732 * # true | trap <--- trap is in subshell - no output (ditto)
4733 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4734 * trap -- 'echo Ho' SIGWINCH
4735 * # echo `(trap)` <--- in subshell in subshell - output
4736 * trap -- 'echo Ho' SIGWINCH
4737 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4738 * trap -- 'echo Ho' SIGWINCH
4740 * The rules when to forget and when to not forget traps
4741 * get really complex and nonsensical.
4743 * Our solution: ONLY bare $(trap) or `trap` is special.
4745 /* Save trap handler strings for trap builtin to print */
4746 trap_ptr = xmemdup(trap, sizeof(trap));
4747 /* Fall through into clearing traps */
4751 /* do job control only in root shell */
4753 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4756 if (jp->nprocs == 0)
4759 pgrp = jp->ps[0].ps_pid;
4760 /* this can fail because we are doing it in the parent also */
4762 if (mode == FORK_FG)
4763 xtcsetpgrp(ttyfd, pgrp);
4768 if (mode == FORK_BG) {
4769 /* man bash: "When job control is not in effect,
4770 * asynchronous commands ignore SIGINT and SIGQUIT" */
4773 if (jp->nprocs == 0) {
4775 if (open(bb_dev_null, O_RDONLY) != 0)
4776 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4780 if (iflag) { /* why if iflag only? */
4785 * "In all cases, bash ignores SIGQUIT. Non-builtin
4786 * commands run by bash have signal handlers
4787 * set to the values inherited by the shell
4789 * Take care of the second rule: */
4793 if (n && n->type == NCMD
4794 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4796 TRACE(("Job hack\n"));
4797 /* "jobs": we do not want to clear job list for it,
4798 * instead we remove only _its_ own_ job from job list.
4799 * This makes "jobs .... | cat" more useful.
4805 for (jp = curjob; jp; jp = jp->prev_job)
4810 /* Called after fork(), in parent */
4812 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4815 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4817 TRACE(("In parent shell: child = %d\n", pid));
4819 /* jp is NULL when called by openhere() for heredoc support */
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);
4853 /* jp and n are NULL when called by openhere() for heredoc support */
4855 forkshell(struct job *jp, union node *n, int mode)
4859 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4862 TRACE(("Fork failed, errno=%d", errno));
4865 ash_msg_and_raise_error("can't fork");
4868 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4869 forkchild(jp, n, mode);
4871 forkparent(jp, n, mode, pid);
4877 * Wait for job to finish.
4879 * Under job control we have the problem that while a child process
4880 * is running interrupts generated by the user are sent to the child
4881 * but not to the shell. This means that an infinite loop started by
4882 * an interactive user may be hard to kill. With job control turned off,
4883 * an interactive user may place an interactive program inside a loop.
4884 * If the interactive program catches interrupts, the user doesn't want
4885 * these interrupts to also abort the loop. The approach we take here
4886 * is to have the shell ignore interrupt signals while waiting for a
4887 * foreground process to terminate, and then send itself an interrupt
4888 * signal if the child process was terminated by an interrupt signal.
4889 * Unfortunately, some programs want to do a bit of cleanup and then
4890 * exit on interrupt; unless these processes terminate themselves by
4891 * sending a signal to themselves (instead of calling exit) they will
4892 * confuse this approach.
4894 * Called with interrupts off.
4897 waitforjob(struct job *jp)
4901 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4904 while (jp->state == JOBRUNNING) {
4905 /* In non-interactive shells, we _can_ get
4906 * a keyboard signal here and be EINTRed,
4907 * but we just loop back, waiting for command to complete.
4910 * "If bash is waiting for a command to complete and receives
4911 * a signal for which a trap has been set, the trap
4912 * will not be executed until the command completes."
4914 * Reality is that even if trap is not set, bash
4915 * will not act on the signal until command completes.
4916 * Try this. sleep5intoff.c:
4917 * #include <signal.h>
4918 * #include <unistd.h>
4921 * sigemptyset(&set);
4922 * sigaddset(&set, SIGINT);
4923 * sigaddset(&set, SIGQUIT);
4924 * sigprocmask(SIG_BLOCK, &set, NULL);
4928 * $ bash -c './sleep5intoff; echo hi'
4929 * ^C^C^C^C <--- pressing ^C once a second
4931 * $ bash -c './sleep5intoff; echo hi'
4932 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4935 dowait(DOWAIT_BLOCK, jp);
4942 xtcsetpgrp(ttyfd, rootpid);
4944 * This is truly gross.
4945 * If we're doing job control, then we did a TIOCSPGRP which
4946 * caused us (the shell) to no longer be in the controlling
4947 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4948 * intuit from the subprocess exit status whether a SIGINT
4949 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4951 if (jp->sigint) /* TODO: do the same with all signals */
4952 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4954 if (jp->state == JOBDONE)
4961 * return 1 if there are stopped jobs, otherwise 0
4973 if (jp && jp->state == JOBSTOPPED) {
4974 out2str("You have stopped jobs.\n");
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) {
5102 /* Can't happen, our single caller does this itself */
5108 return openhere(redir);
5111 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5112 * allocated space. Do it only when we know it is safe.
5114 fname = redir->nfile.expfname;
5116 switch (redir->nfile.type) {
5122 f = open(fname, O_RDONLY);
5127 f = open(fname, O_RDWR|O_CREAT, 0666);
5132 #if ENABLE_ASH_BASH_COMPAT
5135 /* Take care of noclobber mode. */
5137 f = noclobberopen(fname);
5144 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5149 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
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 >= 10. Throws exception on error.
5171 newfd = fcntl(from, F_DUPFD, 10);
5172 err = newfd < 0 ? errno : 0;
5175 ash_msg_and_raise_error("%d: %m", from);
5177 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5183 dup2_or_raise(int from, int to)
5187 newfd = (from != to) ? dup2(from, to) : to;
5189 /* Happens when source fd is not open: try "echo >&99" */
5190 ash_msg_and_raise_error("%d: %m", from);
5195 /* Struct def and variable are moved down to the first usage site */
5200 struct redirtab *next;
5202 struct two_fd_t two_fd[];
5204 #define redirlist (G_var.redirlist)
5206 COPYFD_RESTORE = (int)~(INT_MAX),
5210 need_to_remember(struct redirtab *rp, int fd)
5214 if (!rp) /* remembering was not requested */
5217 for (i = 0; i < rp->pair_count; i++) {
5218 if (rp->two_fd[i].orig == fd) {
5219 /* already remembered */
5226 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5228 is_hidden_fd(struct redirtab *rp, int fd)
5231 struct parsefile *pf;
5235 /* Check open scripts' fds */
5238 /* We skip pf_fd == 0 case because of the following case:
5239 * $ ash # running ash interactively
5241 * and in script.sh: "exec 9>&0".
5242 * Even though top-level pf_fd _is_ 0,
5243 * it's still ok to use it: "read" builtin uses it,
5244 * why should we cripple "exec" builtin?
5246 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5254 /* Check saved fds of redirects */
5255 fd |= COPYFD_RESTORE;
5256 for (i = 0; i < rp->pair_count; i++) {
5257 if (rp->two_fd[i].copy == fd) {
5265 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5266 * old file descriptors are stashed away so that the redirection can be
5267 * undone by calling popredir.
5269 /* flags passed to redirect */
5270 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5271 #define REDIR_SAVEFD2 03 /* set preverrout */
5273 redirect(union node *redir, int flags)
5275 struct redirtab *sv;
5280 int copied_fd2 = -1;
5289 if (flags & REDIR_PUSH) {
5290 union node *tmp = redir;
5293 #if ENABLE_ASH_BASH_COMPAT
5294 if (tmp->nfile.type == NTO2)
5297 tmp = tmp->nfile.next;
5299 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5300 sv->next = redirlist;
5301 sv->pair_count = sv_pos;
5303 while (sv_pos > 0) {
5305 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5311 fd = redir->nfile.fd;
5312 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5313 right_fd = redir->ndup.dupfd;
5314 //bb_error_msg("doing %d > %d", fd, right_fd);
5315 /* redirect from/to same file descriptor? */
5318 /* "echo >&10" and 10 is a fd opened to a sh script? */
5319 if (is_hidden_fd(sv, right_fd)) {
5320 errno = EBADF; /* as if it is closed */
5321 ash_msg_and_raise_error("%d: %m", right_fd);
5325 newfd = openredirect(redir); /* always >= 0 */
5327 /* Descriptor wasn't open before redirect.
5328 * Mark it for close in the future */
5329 if (need_to_remember(sv, fd)) {
5330 goto remember_to_close;
5335 #if ENABLE_ASH_BASH_COMPAT
5338 if (need_to_remember(sv, fd)) {
5339 /* Copy old descriptor */
5340 /* Careful to not accidentally "save"
5341 * to the same fd as right side fd in N>&M */
5342 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5343 i = fcntl(fd, F_DUPFD, minfd);
5344 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5345 * are closed in popredir() in the child, preventing them from leaking
5346 * into child. (popredir() also cleans up the mess in case of failures)
5351 /* Strange error (e.g. "too many files" EMFILE?) */
5355 ash_msg_and_raise_error("%d: %m", fd);
5358 /* EBADF: it is not open - good, remember to close it */
5361 } else { /* fd is open, save its copy */
5362 /* "exec fd>&-" should not close fds
5363 * which point to script file(s).
5364 * Force them to be restored afterwards */
5365 if (is_hidden_fd(sv, fd))
5366 i |= COPYFD_RESTORE;
5370 sv->two_fd[sv_pos].orig = fd;
5371 sv->two_fd[sv_pos].copy = i;
5375 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5376 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5377 /* Don't want to trigger debugging */
5381 dup2_or_raise(redir->ndup.dupfd, fd);
5383 } else if (fd != newfd) { /* move newfd to fd */
5384 dup2_or_raise(newfd, fd);
5385 #if ENABLE_ASH_BASH_COMPAT
5386 if (!(redir->nfile.type == NTO2 && fd == 2))
5390 #if ENABLE_ASH_BASH_COMPAT
5391 if (redir->nfile.type == NTO2 && fd == 1) {
5392 /* We already redirected it to fd 1, now copy it to 2 */
5398 } while ((redir = redir->nfile.next) != NULL);
5401 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5402 preverrout_fd = copied_fd2;
5406 * Undo the effects of the last redirection.
5409 popredir(int drop, int restore)
5411 struct redirtab *rp;
5414 if (redirlist == NULL)
5418 for (i = 0; i < rp->pair_count; i++) {
5419 int fd = rp->two_fd[i].orig;
5420 int copy = rp->two_fd[i].copy;
5421 if (copy == CLOSED) {
5426 if (copy != EMPTY) {
5427 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5428 copy &= ~COPYFD_RESTORE;
5430 dup2_or_raise(copy, fd);
5432 close(copy & ~COPYFD_RESTORE);
5435 redirlist = rp->next;
5441 * Undo all redirections. Called on error or interrupt.
5445 redirectsafe(union node *redir, int flags)
5448 volatile int saveint;
5449 struct jmploc *volatile savehandler = exception_handler;
5450 struct jmploc jmploc;
5453 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5454 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5456 exception_handler = &jmploc;
5457 redirect(redir, flags);
5459 exception_handler = savehandler;
5460 if (err && exception_type != EXERROR)
5461 longjmp(exception_handler->loc, 1);
5462 RESTORE_INT(saveint);
5467 /* ============ Routines to expand arguments to commands
5469 * We have to deal with backquotes, shell variables, and file metacharacters.
5472 #if ENABLE_SH_MATH_SUPPORT
5474 ash_arith(const char *s)
5476 arith_state_t math_state;
5479 math_state.lookupvar = lookupvar;
5480 math_state.setvar = setvar0;
5481 //math_state.endofname = endofname;
5484 result = arith(&math_state, s);
5485 if (math_state.errmsg)
5486 ash_msg_and_raise_error(math_state.errmsg);
5496 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5497 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5498 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5499 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5500 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5501 * POSIX says for this case:
5502 * Pathname expansion shall not be performed on the word by a
5503 * non-interactive shell; an interactive shell may perform it, but shall
5504 * do so only when the expansion would result in one word.
5505 * Currently, our code complies to the above rule by never globbing
5506 * redirection filenames.
5507 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5508 * (this means that on a typical Linux distro, bash almost always
5509 * performs globbing, and thus diverges from what we do).
5511 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5512 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5513 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5514 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5515 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5519 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5520 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5521 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5522 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5523 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5525 /* Add CTLESC when necessary. */
5526 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5527 /* Do not skip NUL characters. */
5528 #define QUOTES_KEEPNUL EXP_TILDE
5531 * Structure specifying which parts of the string should be searched
5532 * for IFS characters.
5535 struct ifsregion *next; /* next region in list */
5536 int begoff; /* offset of start of region */
5537 int endoff; /* offset of end of region */
5538 int nulonly; /* search for nul bytes only */
5542 struct strlist *list;
5543 struct strlist **lastp;
5546 /* output of current string */
5547 static char *expdest;
5548 /* list of back quote expressions */
5549 static struct nodelist *argbackq;
5550 /* first struct in list of ifs regions */
5551 static struct ifsregion ifsfirst;
5552 /* last struct in list */
5553 static struct ifsregion *ifslastp;
5554 /* holds expanded arg list */
5555 static struct arglist exparg;
5560 #if !ENABLE_SH_MATH_SUPPORT
5561 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5562 typedef long arith_t;
5563 # define ARITH_FMT "%ld"
5570 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5571 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5572 STADJUST(len, expdest);
5577 * Break the argument string into pieces based upon IFS and add the
5578 * strings to the argument list. The regions of the string to be
5579 * searched for IFS characters have been stored by recordregion.
5582 ifsbreakup(char *string, struct arglist *arglist)
5584 struct ifsregion *ifsp;
5589 const char *ifs, *realifs;
5594 if (ifslastp != NULL) {
5597 realifs = ifsset() ? ifsval() : defifs;
5600 p = string + ifsp->begoff;
5601 nulonly = ifsp->nulonly;
5602 ifs = nulonly ? nullstr : realifs;
5604 while (p < string + ifsp->endoff) {
5606 if ((unsigned char)*p == CTLESC)
5608 if (!strchr(ifs, *p)) {
5613 ifsspc = (strchr(defifs, *p) != NULL);
5614 /* Ignore IFS whitespace at start */
5615 if (q == start && ifsspc) {
5621 sp = stzalloc(sizeof(*sp));
5623 *arglist->lastp = sp;
5624 arglist->lastp = &sp->next;
5628 if (p >= string + ifsp->endoff) {
5632 if ((unsigned char)*p == CTLESC)
5634 if (strchr(ifs, *p) == NULL) {
5638 if (strchr(defifs, *p) == NULL) {
5653 } while (ifsp != NULL);
5662 sp = stzalloc(sizeof(*sp));
5664 *arglist->lastp = sp;
5665 arglist->lastp = &sp->next;
5671 struct ifsregion *p = ifsfirst.next;
5678 struct ifsregion *ifsp;
5683 ifsfirst.next = NULL;
5690 esclen(const char *start, const char *p)
5694 while (p > start && (unsigned char)*--p == CTLESC) {
5701 * Remove any CTLESC characters from a string.
5704 rmescapes(char *str, int flag)
5706 static const char qchars[] ALIGN1 = {
5707 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5711 unsigned protect_against_glob;
5713 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5715 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5721 if (flag & RMESCAPE_ALLOC) {
5722 size_t len = p - str;
5723 size_t fulllen = len + strlen(p) + 1;
5725 if (flag & RMESCAPE_GROW) {
5726 int strloc = str - (char *)stackblock();
5727 r = makestrspace(fulllen, expdest);
5728 /* p and str may be invalidated by makestrspace */
5729 str = (char *)stackblock() + strloc;
5731 } else if (flag & RMESCAPE_HEAP) {
5732 r = ckmalloc(fulllen);
5734 r = stalloc(fulllen);
5738 q = (char *)memcpy(q, str, len) + len;
5743 globbing = flag & RMESCAPE_GLOB;
5744 protect_against_glob = globbing;
5746 if ((unsigned char)*p == CTLQUOTEMARK) {
5747 // Note: both inquotes and protect_against_glob only affect whether
5748 inquotes = ~inquotes;
5750 protect_against_glob = globbing;
5753 if ((unsigned char)*p == CTLESC) {
5757 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5759 if (protect_against_glob) {
5762 } else if (*p == '\\' && !inquotes) {
5763 /* naked back slash */
5764 protect_against_glob = 0;
5767 #if ENABLE_ASH_BASH_COMPAT
5768 else if (*p == '/' && slash) {
5769 /* stop handling globbing and mark location of slash */
5770 globbing = slash = 0;
5774 protect_against_glob = globbing;
5779 if (flag & RMESCAPE_GROW) {
5781 STADJUST(q - r + 1, expdest);
5785 #define pmatch(a, b) !fnmatch((a), (b), 0)
5788 * Prepare a pattern for a expmeta (internal glob(3)) call.
5790 * Returns an stalloced string.
5793 preglob(const char *pattern, int flag)
5795 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5799 * Put a string on the stack.
5802 memtodest(const char *p, size_t len, int syntax, int quotes)
5809 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5812 unsigned char c = *p++;
5814 int n = SIT(c, syntax);
5815 if ((quotes & QUOTES_ESC)
5817 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5823 } else if (!(quotes & QUOTES_KEEPNUL))
5832 strtodest(const char *p, int syntax, int quotes)
5834 size_t len = strlen(p);
5835 memtodest(p, len, syntax, quotes);
5840 * Record the fact that we have to scan this region of the
5841 * string for IFS characters.
5844 recordregion(int start, int end, int nulonly)
5846 struct ifsregion *ifsp;
5848 if (ifslastp == NULL) {
5852 ifsp = ckzalloc(sizeof(*ifsp));
5853 /*ifsp->next = NULL; - ckzalloc did it */
5854 ifslastp->next = ifsp;
5858 ifslastp->begoff = start;
5859 ifslastp->endoff = end;
5860 ifslastp->nulonly = nulonly;
5864 removerecordregions(int endoff)
5866 if (ifslastp == NULL)
5869 if (ifsfirst.endoff > endoff) {
5870 while (ifsfirst.next) {
5871 struct ifsregion *ifsp;
5873 ifsp = ifsfirst.next->next;
5874 free(ifsfirst.next);
5875 ifsfirst.next = ifsp;
5878 if (ifsfirst.begoff > endoff) {
5881 ifslastp = &ifsfirst;
5882 ifsfirst.endoff = endoff;
5887 ifslastp = &ifsfirst;
5888 while (ifslastp->next && ifslastp->next->begoff < endoff)
5889 ifslastp = ifslastp->next;
5890 while (ifslastp->next) {
5891 struct ifsregion *ifsp;
5893 ifsp = ifslastp->next->next;
5894 free(ifslastp->next);
5895 ifslastp->next = ifsp;
5898 if (ifslastp->endoff > endoff)
5899 ifslastp->endoff = endoff;
5903 exptilde(char *startp, char *p, int flags)
5909 int quotes = flags & QUOTES_ESC;
5913 while ((c = *++p) != '\0') {
5920 if (flags & EXP_VARTILDE)
5930 if (*name == '\0') {
5931 home = lookupvar("HOME");
5933 pw = getpwnam(name);
5938 if (!home || !*home)
5941 strtodest(home, SQSYNTAX, quotes);
5949 * Execute a command inside back quotes. If it's a builtin command, we
5950 * want to save its output in a block obtained from malloc. Otherwise
5951 * we fork off a subprocess and get the output of the command via a pipe.
5952 * Should be called with interrupts off.
5954 struct backcmd { /* result of evalbackcmd */
5955 int fd; /* file descriptor to read from */
5956 int nleft; /* number of chars in buffer */
5957 char *buf; /* buffer */
5958 struct job *jp; /* job structure for command */
5961 /* These forward decls are needed to use "eval" code for backticks handling: */
5962 #define EV_EXIT 01 /* exit after evaluating tree */
5963 static int evaltree(union node *, int);
5965 static void FAST_FUNC
5966 evalbackcmd(union node *n, struct backcmd *result)
5980 ash_msg_and_raise_error("pipe call failed");
5981 jp = makejob(/*n,*/ 1);
5982 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5988 dup2_or_raise(pip[1], 1);
5991 /* TODO: eflag clearing makes the following not abort:
5992 * ash -c 'set -e; z=$(false;echo foo); echo $z'
5993 * which is what bash does (unless it is in POSIX mode).
5994 * dash deleted "eflag = 0" line in the commit
5995 * Date: Mon, 28 Jun 2010 17:11:58 +1000
5996 * [EVAL] Don't clear eflag in evalbackcmd
5997 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6001 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6006 result->fd = pip[0];
6010 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6011 result->fd, result->buf, result->nleft, result->jp));
6015 * Expand stuff in backwards quotes.
6018 expbackq(union node *cmd, int flag)
6026 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6027 struct stackmark smark;
6030 startloc = expdest - (char *)stackblock();
6031 pushstackmark(&smark, startloc);
6032 evalbackcmd(cmd, &in);
6033 popstackmark(&smark);
6040 memtodest(p, i, syntax, flag & QUOTES_ESC);
6044 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6045 TRACE(("expbackq: read returns %d\n", i));
6054 back_exitstatus = waitforjob(in.jp);
6058 /* Eat all trailing newlines */
6060 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6064 if (!(flag & EXP_QUOTED))
6065 recordregion(startloc, dest - (char *)stackblock(), 0);
6066 TRACE(("evalbackq: size:%d:'%.*s'\n",
6067 (int)((dest - (char *)stackblock()) - startloc),
6068 (int)((dest - (char *)stackblock()) - startloc),
6069 stackblock() + startloc));
6072 #if ENABLE_SH_MATH_SUPPORT
6074 * Expand arithmetic expression. Backup to start of expression,
6075 * evaluate, place result in (backed up) result, adjust string position.
6087 * This routine is slightly over-complicated for
6088 * efficiency. Next we scan backwards looking for the
6089 * start of arithmetic.
6091 start = stackblock();
6098 while ((unsigned char)*p != CTLARI) {
6102 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6107 esc = esclen(start, p);
6117 removerecordregions(begoff);
6121 if (flag & QUOTES_ESC)
6122 rmescapes(p + 1, 0);
6124 len = cvtnum(ash_arith(p + 1));
6126 if (!(flag & EXP_QUOTED))
6127 recordregion(begoff, begoff + len, 0);
6131 /* argstr needs it */
6132 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6135 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6136 * characters to allow for further processing. Otherwise treat
6137 * $@ like $* since no splitting will be performed.
6139 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6140 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6141 * for correct expansion of "B=$A" word.
6144 argstr(char *p, int flags, struct strlist *var_str_list)
6146 static const char spclchars[] ALIGN1 = {
6154 #if ENABLE_SH_MATH_SUPPORT
6159 const char *reject = spclchars;
6160 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6165 if (!(flags & EXP_VARTILDE)) {
6167 } else if (flags & EXP_VARTILDE2) {
6172 if (flags & EXP_TILDE) {
6175 flags &= ~EXP_TILDE;
6179 p = exptilde(p, q, flags);
6182 startloc = expdest - (char *)stackblock();
6186 length += strcspn(p + length, reject);
6190 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6192 /* c == '=' || c == ':' || c == CTLENDARI */
6198 expdest = stack_nputstr(p, length, expdest);
6199 newloc = expdest - (char *)stackblock();
6200 if (breakall && !inquotes && newloc > startloc) {
6201 recordregion(startloc, newloc, 0);
6212 if (flags & EXP_VARTILDE2) {
6216 flags |= EXP_VARTILDE2;
6221 * sort of a hack - expand tildes in variable
6222 * assignments (after the first '=' and after ':'s).
6231 case CTLENDVAR: /* ??? */
6234 inquotes ^= EXP_QUOTED;
6235 /* "$@" syntax adherence hack */
6236 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6237 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6241 if (flags & QUOTES_ESC) {
6252 * Quoted parameter expansion pattern: remove quote
6253 * unless inside inner quotes or we have a literal
6256 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6257 EXP_QPAT && *p != '\\')
6262 TRACE(("argstr: evalvar('%s')\n", p));
6263 p = evalvar(p, flags | inquotes, var_str_list);
6264 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6267 expbackq(argbackq->n, flags | inquotes);
6268 argbackq = argbackq->next;
6270 #if ENABLE_SH_MATH_SUPPORT
6273 expari(flags | inquotes);
6282 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6283 char *pattern, int quotes, int zero)
6292 const char *s = loc2;
6299 match = pmatch(pattern, s);
6304 if (quotes && (unsigned char)*loc == CTLESC)
6313 scanright(char *startp, char *rmesc, char *rmescend,
6314 char *pattern, int quotes, int match_at_start)
6316 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6317 int try2optimize = match_at_start;
6323 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6324 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6325 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6327 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6328 * and on each iteration they go back two/one char until they reach the beginning.
6329 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6331 /* TODO: document in what other circumstances we are called. */
6333 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6336 const char *s = loc2;
6337 if (match_at_start) {
6341 match = pmatch(pattern, s);
6342 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6346 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6348 /* Maybe we can optimize this:
6349 * if pattern ends with unescaped *, we can avoid checking
6350 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6351 * it wont match truncated "raw_value_of_" strings too.
6353 unsigned plen = strlen(pattern);
6354 /* Does it end with "*"? */
6355 if (plen != 0 && pattern[--plen] == '*') {
6356 /* "xxxx*" is not escaped */
6357 /* "xxx\*" is escaped */
6358 /* "xx\\*" is not escaped */
6359 /* "x\\\*" is escaped */
6361 while (plen != 0 && pattern[--plen] == '\\')
6364 break; /* ends with unescaped "*" */
6372 esc = esclen(startp, loc);
6383 static void varunset(const char *, const char *, const char *, int) NORETURN;
6385 varunset(const char *end, const char *var, const char *umsg, int varflags)
6391 msg = "parameter not set";
6393 if ((unsigned char)*end == CTLENDVAR) {
6394 if (varflags & VSNUL)
6400 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6404 subevalvar(char *p, char *varname, int strloc, int subtype,
6405 int startloc, int varflags, int flag, struct strlist *var_str_list)
6407 struct nodelist *saveargbackq = argbackq;
6408 int quotes = flag & QUOTES_ESC;
6411 char *rmesc, *rmescend;
6413 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6414 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6415 int amount, resetloc;
6416 IF_ASH_BASH_COMPAT(int workloc;)
6418 char *(*scan)(char*, char*, char*, char*, int, int);
6420 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6421 // p, varname, strloc, subtype, startloc, varflags, quotes);
6423 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6424 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6426 STPUTC('\0', expdest);
6427 argbackq = saveargbackq;
6428 startp = (char *)stackblock() + startloc;
6432 setvar0(varname, startp);
6433 amount = startp - expdest;
6434 STADJUST(amount, expdest);
6438 varunset(p, varname, startp, varflags);
6441 #if ENABLE_ASH_BASH_COMPAT
6443 //TODO: support more general format ${v:EXPR:EXPR},
6444 // where EXPR follows $(()) rules
6445 loc = str = stackblock() + strloc;
6446 /* Read POS in ${var:POS:LEN} */
6447 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6448 len = str - startp - 1;
6450 /* *loc != '\0', guaranteed by parser */
6454 /* Adjust the length by the number of escapes */
6455 for (ptr = startp; ptr < (str - 1); ptr++) {
6456 if ((unsigned char)*ptr == CTLESC) {
6464 if (*loc++ == ':') {
6468 /* Skip POS in ${var:POS:LEN} */
6470 while (*loc && *loc != ':') {
6472 * bash complains on: var=qwe; echo ${var:1a:123}
6474 ash_msg_and_raise_error(msg_illnum, str);
6478 if (*loc++ == ':') {
6483 /* ${VAR:$((-n)):l} starts n chars from the end */
6484 pos = orig_len + pos;
6486 if ((unsigned)pos >= orig_len) {
6487 /* apart from obvious ${VAR:999999:l},
6488 * covers ${VAR:$((-9999999)):l} - result is ""
6494 if (len > (orig_len - pos))
6495 len = orig_len - pos;
6497 for (str = startp; pos; str++, pos--) {
6498 if (quotes && (unsigned char)*str == CTLESC)
6501 for (loc = startp; len; len--) {
6502 if (quotes && (unsigned char)*str == CTLESC)
6507 amount = loc - expdest;
6508 STADJUST(amount, expdest);
6513 resetloc = expdest - (char *)stackblock();
6515 /* We'll comeback here if we grow the stack while handling
6516 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6517 * stack will need rebasing, and we'll need to remove our work
6520 IF_ASH_BASH_COMPAT(restart:)
6522 amount = expdest - ((char *)stackblock() + resetloc);
6523 STADJUST(-amount, expdest);
6524 startp = (char *)stackblock() + startloc;
6527 rmescend = (char *)stackblock() + strloc;
6529 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6530 if (rmesc != startp) {
6532 startp = (char *)stackblock() + startloc;
6536 str = (char *)stackblock() + strloc;
6538 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6539 * The result is a_\_z_c (not a\_\_z_c)!
6541 * The search pattern and replace string treat backslashes differently!
6542 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6543 * and string. It's only used on the first call.
6545 preglob(str, IF_ASH_BASH_COMPAT(
6546 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6547 RMESCAPE_SLASH :) 0);
6549 #if ENABLE_ASH_BASH_COMPAT
6550 workloc = expdest - (char *)stackblock();
6551 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6555 repl = strchr(str, CTLESC);
6561 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6563 /* If there's no pattern to match, return the expansion unmolested */
6572 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6573 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6575 /* No match, advance */
6576 char *restart_detect = stackblock();
6578 STPUTC(*idx, expdest);
6579 if (quotes && (unsigned char)*idx == CTLESC) {
6582 STPUTC(*idx, expdest);
6584 if (stackblock() != restart_detect)
6589 /* continue; - prone to quadratic behavior, smarter code: */
6592 if (str[0] == '*') {
6593 /* Pattern is "*foo". If "*foo" does not match "long_string",
6594 * it would never match "ong_string" etc, no point in trying.
6601 if (subtype == VSREPLACEALL) {
6603 if (quotes && (unsigned char)*idx == CTLESC)
6612 //bb_error_msg("repl:'%s'", repl);
6613 for (loc = (char*)repl; *loc; loc++) {
6614 char *restart_detect = stackblock();
6615 if (quotes && *loc == '\\') {
6616 STPUTC(CTLESC, expdest);
6619 STPUTC(*loc, expdest);
6620 if (stackblock() != restart_detect)
6625 if (subtype == VSREPLACE) {
6626 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6628 char *restart_detect = stackblock();
6629 STPUTC(*idx, expdest);
6630 if (stackblock() != restart_detect)
6639 /* We've put the replaced text into a buffer at workloc, now
6640 * move it to the right place and adjust the stack.
6642 STPUTC('\0', expdest);
6643 startp = (char *)stackblock() + startloc;
6644 memmove(startp, (char *)stackblock() + workloc, len + 1);
6645 //bb_error_msg("startp:'%s'", startp);
6646 amount = expdest - (startp + len);
6647 STADJUST(-amount, expdest);
6650 #endif /* ENABLE_ASH_BASH_COMPAT */
6652 subtype -= VSTRIMRIGHT;
6654 if (subtype < 0 || subtype > 7)
6657 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6658 zero = subtype >> 1;
6659 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6660 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6662 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6665 memmove(startp, loc, str - loc);
6666 loc = startp + (str - loc) - 1;
6669 amount = loc - expdest;
6670 STADJUST(amount, expdest);
6676 * Add the value of a specialized variable to the stack string.
6677 * name parameter (examples):
6678 * ash -c 'echo $1' name:'1='
6679 * ash -c 'echo $qwe' name:'qwe='
6680 * ash -c 'echo $$' name:'$='
6681 * ash -c 'echo ${$}' name:'$='
6682 * ash -c 'echo ${$##q}' name:'$=q'
6683 * ash -c 'echo ${#$}' name:'$='
6684 * note: examples with bad shell syntax:
6685 * ash -c 'echo ${#$1}' name:'$=1'
6686 * ash -c 'echo ${#1#}' name:'1=#'
6688 static NOINLINE ssize_t
6689 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6696 int quoted = *quotedp;
6697 int subtype = varflags & VSTYPE;
6698 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6699 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6702 sep = (flags & EXP_FULL) << CHAR_BIT;
6703 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6713 num = shellparam.nparam;
6721 goto check_1char_name;
6723 expdest = makestrspace(NOPTS, expdest);
6724 for (i = NOPTS - 1; i >= 0; i--) {
6726 USTPUTC(optletters(i), expdest);
6732 /* handles cases similar to ${#$1} */
6733 if (name[2] != '\0')
6734 raise_error_syntax("bad substitution");
6747 sep |= ifsset() ? ifsval()[0] : ' ';
6754 while ((p = *ap++) != NULL) {
6755 len += strtodest(p, syntax, quotes);
6759 memtodest(&sepc, 1, syntax, quotes);
6774 num = atoi(name); /* number(name) fails on ${N#str} etc */
6775 if (num < 0 || num > shellparam.nparam)
6777 p = num ? shellparam.p[num - 1] : arg0;
6780 /* NB: name has form "VAR=..." */
6782 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6783 * which should be considered before we check variables. */
6785 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6789 str = var_str_list->text;
6790 eq = strchr(str, '=');
6791 if (!eq) /* stop at first non-assignment */
6794 if (name_len == (unsigned)(eq - str)
6795 && strncmp(str, name, name_len) == 0
6798 /* goto value; - WRONG! */
6799 /* think "A=1 A=2 B=$A" */
6801 var_str_list = var_str_list->next;
6802 } while (var_str_list);
6806 p = lookupvar(name);
6811 len = strtodest(p, syntax, quotes);
6812 #if ENABLE_UNICODE_SUPPORT
6813 if (subtype == VSLENGTH && len > 0) {
6814 reinit_unicode_for_ash();
6815 if (unicode_status == UNICODE_ON) {
6816 STADJUST(-len, expdest);
6818 len = unicode_strlen(p);
6826 STADJUST(-len, expdest);
6831 * Expand a variable, and return a pointer to the next character in the
6835 evalvar(char *p, int flag, struct strlist *var_str_list)
6846 varflags = (unsigned char) *p++;
6847 subtype = varflags & VSTYPE;
6850 raise_error_syntax("bad substitution");
6852 quoted = flag & EXP_QUOTED;
6854 easy = (!quoted || (*var == '@' && shellparam.nparam));
6855 startloc = expdest - (char *)stackblock();
6856 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6859 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6860 if (varflags & VSNUL)
6863 if (subtype == VSPLUS) {
6864 varlen = -1 - varlen;
6868 if (subtype == VSMINUS) {
6873 flag | EXP_TILDE | EXP_WORD,
6881 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6885 subevalvar(p, var, 0, subtype, startloc, varflags,
6886 flag & ~QUOTES_ESC, var_str_list);
6889 * Remove any recorded regions beyond
6892 removerecordregions(startloc);
6896 if (varlen < 0 && uflag)
6897 varunset(p, var, 0, 0);
6899 if (subtype == VSLENGTH) {
6900 cvtnum(varlen > 0 ? varlen : 0);
6904 if (subtype == VSNORMAL) {
6908 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6917 case VSTRIMRIGHTMAX:
6918 #if ENABLE_ASH_BASH_COMPAT
6931 * Terminate the string and start recording the pattern
6934 STPUTC('\0', expdest);
6935 patloc = expdest - (char *)stackblock();
6936 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6937 startloc, varflags, flag, var_str_list)) {
6938 int amount = expdest - (
6939 (char *)stackblock() + patloc - 1
6941 STADJUST(-amount, expdest);
6943 /* Remove any recorded regions beyond start of variable */
6944 removerecordregions(startloc);
6949 if (subtype != VSNORMAL) { /* skip to end of alternative */
6952 unsigned char c = *p++;
6955 else if (c == CTLBACKQ) {
6957 argbackq = argbackq->next;
6958 } else if (c == CTLVAR) {
6959 if ((*p++ & VSTYPE) != VSNORMAL)
6961 } else if (c == CTLENDVAR) {
6971 * Add a file name to the list.
6974 addfname(const char *name)
6978 sp = stzalloc(sizeof(*sp));
6979 sp->text = sstrdup(name);
6981 exparg.lastp = &sp->next;
6984 /* If we want to use glob() from libc... */
6985 #if !ENABLE_ASH_INTERNAL_GLOB
6987 /* Add the result of glob() to the list */
6989 addglob(const glob_t *pglob)
6991 char **p = pglob->gl_pathv;
6998 expandmeta(struct strlist *str /*, int flag*/)
7000 /* TODO - EXP_REDIR */
7010 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7011 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7012 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7014 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7015 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7016 // Which means you need to unescape the string, right? Not so fast:
7017 // if there _is_ a file named "file\?" (with backslash), it is returned
7018 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7019 // You DONT KNOW by looking at the result whether you need to unescape it.
7021 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7022 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7023 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7024 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7025 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7026 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7027 i = glob(p, 0, NULL, &pglob);
7028 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7033 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7034 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7035 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7047 *exparg.lastp = str;
7048 rmescapes(str->text, 0);
7049 exparg.lastp = &str->next;
7051 default: /* GLOB_NOSPACE */
7054 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7061 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7064 * Do metacharacter (i.e. *, ?, [...]) expansion.
7067 expmeta(char *expdir, char *enddir, char *name)
7083 for (p = name; esc = 0, *p; p += esc + 1) {
7084 if (*p == '*' || *p == '?')
7086 else if (*p == '[') {
7093 if (*q == '/' || *q == '\0')
7103 if (p[esc] == '/') {
7106 start = p + esc + 1;
7110 if (metaflag == 0) { /* we've reached the end of the file name */
7111 if (enddir != expdir)
7119 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7130 } while (p < start);
7132 if (enddir == expdir) {
7134 } else if (enddir == expdir + 1 && *expdir == '/') {
7143 if (enddir != expdir)
7145 if (*endname == 0) {
7158 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7159 if (dp->d_name[0] == '.' && !matchdot)
7161 if (pmatch(start, dp->d_name)) {
7163 strcpy(enddir, dp->d_name);
7166 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7169 expmeta(expdir, p, endname);
7175 endname[-esc - 1] = esc ? '\\' : '/';
7178 static struct strlist *
7179 msort(struct strlist *list, int len)
7181 struct strlist *p, *q = NULL;
7182 struct strlist **lpp;
7190 for (n = half; --n >= 0;) {
7194 q->next = NULL; /* terminate first half of list */
7195 q = msort(list, half); /* sort first half of list */
7196 p = msort(p, len - half); /* sort second half */
7199 #if ENABLE_LOCALE_SUPPORT
7200 if (strcoll(p->text, q->text) < 0)
7202 if (strcmp(p->text, q->text) < 0)
7226 * Sort the results of file name expansion. It calculates the number of
7227 * strings to sort and then calls msort (short for merge sort) to do the
7230 static struct strlist *
7231 expsort(struct strlist *str)
7237 for (sp = str; sp; sp = sp->next)
7239 return msort(str, len);
7243 expandmeta(struct strlist *str /*, int flag*/)
7245 static const char metachars[] ALIGN1 = {
7248 /* TODO - EXP_REDIR */
7252 struct strlist **savelastp;
7258 if (!strpbrk(str->text, metachars))
7260 savelastp = exparg.lastp;
7263 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7265 int i = strlen(str->text);
7266 //BUGGY estimation of how long expanded name can be
7267 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7269 expmeta(expdir, expdir, p);
7274 if (exparg.lastp == savelastp) {
7279 *exparg.lastp = str;
7280 rmescapes(str->text, 0);
7281 exparg.lastp = &str->next;
7283 *exparg.lastp = NULL;
7284 *savelastp = sp = expsort(*savelastp);
7285 while (sp->next != NULL)
7287 exparg.lastp = &sp->next;
7292 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7295 * Perform variable substitution and command substitution on an argument,
7296 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7297 * perform splitting and file name expansion. When arglist is NULL, perform
7298 * here document expansion.
7301 expandarg(union node *arg, struct arglist *arglist, int flag)
7306 argbackq = arg->narg.backquote;
7307 STARTSTACKSTR(expdest);
7308 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7309 argstr(arg->narg.text, flag,
7310 /* var_str_list: */ arglist ? arglist->list : NULL);
7311 p = _STPUTC('\0', expdest);
7313 if (arglist == NULL) {
7314 /* here document expanded */
7317 p = grabstackstr(p);
7318 TRACE(("expandarg: p:'%s'\n", p));
7319 exparg.lastp = &exparg.list;
7323 if (flag & EXP_FULL) {
7324 ifsbreakup(p, &exparg);
7325 *exparg.lastp = NULL;
7326 exparg.lastp = &exparg.list;
7327 expandmeta(exparg.list /*, flag*/);
7329 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7331 TRACE(("expandarg: rmescapes:'%s'\n", p));
7333 sp = stzalloc(sizeof(*sp));
7336 exparg.lastp = &sp->next;
7338 *exparg.lastp = NULL;
7340 *arglist->lastp = exparg.list;
7341 arglist->lastp = exparg.lastp;
7349 * Expand shell variables and backquotes inside a here document.
7352 expandhere(union node *arg, int fd)
7354 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7355 full_write(fd, stackblock(), expdest - (char *)stackblock());
7359 * Returns true if the pattern matches the string.
7362 patmatch(char *pattern, const char *string)
7364 return pmatch(preglob(pattern, 0), string);
7368 * See if a pattern matches in a case statement.
7371 casematch(union node *pattern, char *val)
7373 struct stackmark smark;
7376 setstackmark(&smark);
7377 argbackq = pattern->narg.backquote;
7378 STARTSTACKSTR(expdest);
7379 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7380 /* var_str_list: */ NULL);
7381 STACKSTRNUL(expdest);
7383 result = patmatch(stackblock(), val);
7384 popstackmark(&smark);
7389 /* ============ find_command */
7393 int (*builtin)(int, char **) FAST_FUNC;
7394 /* unsigned flags; */
7396 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7397 /* "regular" builtins always take precedence over commands,
7398 * regardless of PATH=....%builtin... position */
7399 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7400 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7403 smallint cmdtype; /* CMDxxx */
7406 /* index >= 0 for commands without path (slashes) */
7407 /* (TODO: what exactly does the value mean? PATH position?) */
7408 /* index == -1 for commands with slashes */
7409 /* index == (-2 - applet_no) for NOFORK applets */
7410 const struct builtincmd *cmd;
7411 struct funcnode *func;
7414 /* values of cmdtype */
7415 #define CMDUNKNOWN -1 /* no entry in table for command */
7416 #define CMDNORMAL 0 /* command is an executable program */
7417 #define CMDFUNCTION 1 /* command is a shell function */
7418 #define CMDBUILTIN 2 /* command is a shell builtin */
7420 /* action to find_command() */
7421 #define DO_ERR 0x01 /* prints errors */
7422 #define DO_ABS 0x02 /* checks absolute paths */
7423 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7424 #define DO_ALTPATH 0x08 /* using alternate path */
7425 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7427 static void find_command(char *, struct cmdentry *, int, const char *);
7430 /* ============ Hashing commands */
7433 * When commands are first encountered, they are entered in a hash table.
7434 * This ensures that a full path search will not have to be done for them
7435 * on each invocation.
7437 * We should investigate converting to a linear search, even though that
7438 * would make the command name "hash" a misnomer.
7442 struct tblentry *next; /* next entry in hash chain */
7443 union param param; /* definition of builtin function */
7444 smallint cmdtype; /* CMDxxx */
7445 char rehash; /* if set, cd done since entry created */
7446 char cmdname[1]; /* name of command */
7449 static struct tblentry **cmdtable;
7450 #define INIT_G_cmdtable() do { \
7451 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7454 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7458 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7460 #if ENABLE_FEATURE_SH_STANDALONE
7461 if (applet_no >= 0) {
7462 if (APPLET_IS_NOEXEC(applet_no)) {
7466 run_applet_no_and_exit(applet_no, argv);
7468 /* re-exec ourselves with the new arguments */
7469 execve(bb_busybox_exec_path, argv, envp);
7470 /* If they called chroot or otherwise made the binary no longer
7471 * executable, fall through */
7478 execve(cmd, argv, envp);
7479 } while (errno == EINTR);
7481 execve(cmd, argv, envp);
7483 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7484 /* Run "cmd" as a shell script:
7485 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7486 * "If the execve() function fails with ENOEXEC, the shell
7487 * shall execute a command equivalent to having a shell invoked
7488 * with the command name as its first operand,
7489 * with any remaining arguments passed to the new shell"
7491 * That is, do not use $SHELL, user's shell, or /bin/sh;
7492 * just call ourselves.
7494 * Note that bash reads ~80 chars of the file, and if it sees
7495 * a zero byte before it sees newline, it doesn't try to
7496 * interpret it, but fails with "cannot execute binary file"
7497 * message and exit code 126. For one, this prevents attempts
7498 * to interpret foreign ELF binaries as shell scripts.
7501 cmd = (char*) bb_busybox_exec_path;
7502 /* NB: this is only possible because all callers of shellexec()
7503 * ensure that the argv[-1] slot exists!
7506 argv[0] = (char*) "ash";
7512 * Exec a program. Never returns. If you change this routine, you may
7513 * have to change the find_command routine as well.
7514 * argv[-1] must exist and be writable! See tryexec() for why.
7516 static void shellexec(char **, const char *, int) NORETURN;
7518 shellexec(char **argv, const char *path, int idx)
7524 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7526 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7527 if (strchr(argv[0], '/') != NULL
7528 #if ENABLE_FEATURE_SH_STANDALONE
7529 || (applet_no = find_applet_by_name(argv[0])) >= 0
7532 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7533 if (applet_no >= 0) {
7534 /* We tried execing ourself, but it didn't work.
7535 * Maybe /proc/self/exe doesn't exist?
7544 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7545 if (--idx < 0 && pathopt == NULL) {
7546 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7547 if (errno != ENOENT && errno != ENOTDIR)
7554 /* Map to POSIX errors */
7566 exitstatus = exerrno;
7567 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7568 argv[0], e, suppress_int));
7569 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7574 printentry(struct tblentry *cmdp)
7580 idx = cmdp->param.index;
7583 name = path_advance(&path, cmdp->cmdname);
7585 } while (--idx >= 0);
7586 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7590 * Clear out command entries. The argument specifies the first entry in
7591 * PATH which has changed.
7594 clearcmdentry(int firstchange)
7596 struct tblentry **tblp;
7597 struct tblentry **pp;
7598 struct tblentry *cmdp;
7601 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7603 while ((cmdp = *pp) != NULL) {
7604 if ((cmdp->cmdtype == CMDNORMAL &&
7605 cmdp->param.index >= firstchange)
7606 || (cmdp->cmdtype == CMDBUILTIN &&
7607 builtinloc >= firstchange)
7620 * Locate a command in the command hash table. If "add" is nonzero,
7621 * add the command to the table if it is not already present. The
7622 * variable "lastcmdentry" is set to point to the address of the link
7623 * pointing to the entry, so that delete_cmd_entry can delete the
7626 * Interrupts must be off if called with add != 0.
7628 static struct tblentry **lastcmdentry;
7630 static struct tblentry *
7631 cmdlookup(const char *name, int add)
7633 unsigned int hashval;
7635 struct tblentry *cmdp;
7636 struct tblentry **pp;
7639 hashval = (unsigned char)*p << 4;
7641 hashval += (unsigned char)*p++;
7643 pp = &cmdtable[hashval % CMDTABLESIZE];
7644 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7645 if (strcmp(cmdp->cmdname, name) == 0)
7649 if (add && cmdp == NULL) {
7650 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7652 /* + 1 - already done because
7653 * tblentry::cmdname is char[1] */);
7654 /*cmdp->next = NULL; - ckzalloc did it */
7655 cmdp->cmdtype = CMDUNKNOWN;
7656 strcpy(cmdp->cmdname, name);
7663 * Delete the command entry returned on the last lookup.
7666 delete_cmd_entry(void)
7668 struct tblentry *cmdp;
7671 cmdp = *lastcmdentry;
7672 *lastcmdentry = cmdp->next;
7673 if (cmdp->cmdtype == CMDFUNCTION)
7674 freefunc(cmdp->param.func);
7680 * Add a new command entry, replacing any existing command entry for
7681 * the same name - except special builtins.
7684 addcmdentry(char *name, struct cmdentry *entry)
7686 struct tblentry *cmdp;
7688 cmdp = cmdlookup(name, 1);
7689 if (cmdp->cmdtype == CMDFUNCTION) {
7690 freefunc(cmdp->param.func);
7692 cmdp->cmdtype = entry->cmdtype;
7693 cmdp->param = entry->u;
7697 static int FAST_FUNC
7698 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7700 struct tblentry **pp;
7701 struct tblentry *cmdp;
7703 struct cmdentry entry;
7706 if (nextopt("r") != '\0') {
7711 if (*argptr == NULL) {
7712 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7713 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7714 if (cmdp->cmdtype == CMDNORMAL)
7722 while ((name = *argptr) != NULL) {
7723 cmdp = cmdlookup(name, 0);
7725 && (cmdp->cmdtype == CMDNORMAL
7726 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7730 find_command(name, &entry, DO_ERR, pathval());
7731 if (entry.cmdtype == CMDUNKNOWN)
7739 * Called when a cd is done. Marks all commands so the next time they
7740 * are executed they will be rehashed.
7745 struct tblentry **pp;
7746 struct tblentry *cmdp;
7748 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7749 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7750 if (cmdp->cmdtype == CMDNORMAL
7751 || (cmdp->cmdtype == CMDBUILTIN
7752 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7762 * Fix command hash table when PATH changed.
7763 * Called before PATH is changed. The argument is the new value of PATH;
7764 * pathval() still returns the old value at this point.
7765 * Called with interrupts off.
7767 static void FAST_FUNC
7768 changepath(const char *new)
7776 firstchange = 9999; /* assume no change */
7782 if ((*old == '\0' && *new == ':')
7783 || (*old == ':' && *new == '\0')
7787 old = new; /* ignore subsequent differences */
7791 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7798 if (builtinloc < 0 && idx_bltin >= 0)
7799 builtinloc = idx_bltin; /* zap builtins */
7800 if (builtinloc >= 0 && idx_bltin < 0)
7802 clearcmdentry(firstchange);
7803 builtinloc = idx_bltin;
7828 #if ENABLE_ASH_BASH_COMPAT
7839 typedef smallint token_id_t;
7841 /* Nth bit indicates if token marks the end of a list */
7844 /* 0 */ | (1u << TEOF)
7845 /* 1 */ | (0u << TNL)
7846 /* 2 */ | (0u << TREDIR)
7847 /* 3 */ | (0u << TWORD)
7848 /* 4 */ | (0u << TSEMI)
7849 /* 5 */ | (0u << TBACKGND)
7850 /* 6 */ | (0u << TAND)
7851 /* 7 */ | (0u << TOR)
7852 /* 8 */ | (0u << TPIPE)
7853 /* 9 */ | (0u << TLP)
7854 /* 10 */ | (1u << TRP)
7855 /* 11 */ | (1u << TENDCASE)
7856 /* 12 */ | (1u << TENDBQUOTE)
7857 /* 13 */ | (0u << TNOT)
7858 /* 14 */ | (0u << TCASE)
7859 /* 15 */ | (1u << TDO)
7860 /* 16 */ | (1u << TDONE)
7861 /* 17 */ | (1u << TELIF)
7862 /* 18 */ | (1u << TELSE)
7863 /* 19 */ | (1u << TESAC)
7864 /* 20 */ | (1u << TFI)
7865 /* 21 */ | (0u << TFOR)
7866 #if ENABLE_ASH_BASH_COMPAT
7867 /* 22 */ | (0u << TFUNCTION)
7869 /* 23 */ | (0u << TIF)
7870 /* 24 */ | (0u << TIN)
7871 /* 25 */ | (1u << TTHEN)
7872 /* 26 */ | (0u << TUNTIL)
7873 /* 27 */ | (0u << TWHILE)
7874 /* 28 */ | (0u << TBEGIN)
7875 /* 29 */ | (1u << TEND)
7876 , /* thus far 29 bits used */
7879 static const char *const tokname_array[] = {
7893 #define KWDOFFSET 13
7894 /* the following are keywords */
7904 #if ENABLE_ASH_BASH_COMPAT
7916 /* Wrapper around strcmp for qsort/bsearch/... */
7918 pstrcmp(const void *a, const void *b)
7920 return strcmp((char*)a, *(char**)b);
7923 static const char *const *
7924 findkwd(const char *s)
7926 return bsearch(s, tokname_array + KWDOFFSET,
7927 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7928 sizeof(tokname_array[0]), pstrcmp);
7932 * Locate and print what a word is...
7935 describe_command(char *command, const char *path, int describe_command_verbose)
7937 struct cmdentry entry;
7938 struct tblentry *cmdp;
7939 #if ENABLE_ASH_ALIAS
7940 const struct alias *ap;
7943 path = path ? path : pathval();
7945 if (describe_command_verbose) {
7949 /* First look at the keywords */
7950 if (findkwd(command)) {
7951 out1str(describe_command_verbose ? " is a shell keyword" : command);
7955 #if ENABLE_ASH_ALIAS
7956 /* Then look at the aliases */
7957 ap = lookupalias(command, 0);
7959 if (!describe_command_verbose) {
7964 out1fmt(" is an alias for %s", ap->val);
7968 /* Then check if it is a tracked alias */
7969 cmdp = cmdlookup(command, 0);
7971 entry.cmdtype = cmdp->cmdtype;
7972 entry.u = cmdp->param;
7974 /* Finally use brute force */
7975 find_command(command, &entry, DO_ABS, path);
7978 switch (entry.cmdtype) {
7980 int j = entry.u.index;
7986 p = path_advance(&path, command);
7990 if (describe_command_verbose) {
7992 (cmdp ? " a tracked alias for" : nullstr), p
8001 if (describe_command_verbose) {
8002 out1str(" is a shell function");
8009 if (describe_command_verbose) {
8010 out1fmt(" is a %sshell builtin",
8011 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8012 "special " : nullstr
8020 if (describe_command_verbose) {
8021 out1str(": not found\n");
8030 static int FAST_FUNC
8031 typecmd(int argc UNUSED_PARAM, char **argv)
8037 /* type -p ... ? (we don't bother checking for 'p') */
8038 if (argv[1] && argv[1][0] == '-') {
8043 err |= describe_command(argv[i++], NULL, verbose);
8048 #if ENABLE_ASH_CMDCMD
8049 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8051 parse_command_args(char **argv, const char **path)
8064 if (c == '-' && !*cp) {
8072 *path = bb_default_path;
8075 /* run 'typecmd' for other options */
8084 static int FAST_FUNC
8085 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8093 const char *path = NULL;
8095 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8096 * never reaches this function.
8099 while ((c = nextopt("pvV")) != '\0')
8101 verify |= VERIFY_VERBOSE;
8103 /*verify |= VERIFY_BRIEF*/;
8109 path = bb_default_path;
8111 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8113 if (/*verify && */ cmd)
8114 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8121 /*static int funcblocksize; // size of structures in function */
8122 /*static int funcstringsize; // size of strings in node */
8123 static void *funcblock; /* block to allocate function from */
8124 static char *funcstring_end; /* end of block to allocate strings from */
8126 /* flags in argument to evaltree */
8127 #define EV_EXIT 01 /* exit after evaluating tree */
8128 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8130 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8131 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8132 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8133 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8134 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8135 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8136 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8137 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8138 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8139 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8140 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8141 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8142 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8143 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8144 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8145 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8146 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8147 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8148 #if ENABLE_ASH_BASH_COMPAT
8149 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8151 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8152 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8153 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8154 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8155 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8156 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8157 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8158 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8159 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8162 static int calcsize(int funcblocksize, union node *n);
8165 sizenodelist(int funcblocksize, struct nodelist *lp)
8168 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8169 funcblocksize = calcsize(funcblocksize, lp->n);
8172 return funcblocksize;
8176 calcsize(int funcblocksize, union node *n)
8179 return funcblocksize;
8180 funcblocksize += nodesize[n->type];
8183 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8184 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8185 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8188 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8193 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8194 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8201 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8202 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8205 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8206 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8207 funcblocksize = calcsize(funcblocksize, n->nif.test);
8210 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8211 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8212 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8215 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8216 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8219 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8220 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8221 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8225 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8226 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8227 funcblocksize = calcsize(funcblocksize, n->narg.next);
8230 #if ENABLE_ASH_BASH_COMPAT
8237 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8238 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8242 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8243 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8247 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8248 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8251 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8254 return funcblocksize;
8258 nodeckstrdup(char *s)
8260 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8261 return strcpy(funcstring_end, s);
8264 static union node *copynode(union node *);
8266 static struct nodelist *
8267 copynodelist(struct nodelist *lp)
8269 struct nodelist *start;
8270 struct nodelist **lpp;
8275 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8276 (*lpp)->n = copynode(lp->n);
8278 lpp = &(*lpp)->next;
8285 copynode(union node *n)
8292 funcblock = (char *) funcblock + nodesize[n->type];
8296 new->ncmd.redirect = copynode(n->ncmd.redirect);
8297 new->ncmd.args = copynode(n->ncmd.args);
8298 new->ncmd.assign = copynode(n->ncmd.assign);
8301 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8302 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8307 new->nredir.redirect = copynode(n->nredir.redirect);
8308 new->nredir.n = copynode(n->nredir.n);
8315 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8316 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8319 new->nif.elsepart = copynode(n->nif.elsepart);
8320 new->nif.ifpart = copynode(n->nif.ifpart);
8321 new->nif.test = copynode(n->nif.test);
8324 new->nfor.var = nodeckstrdup(n->nfor.var);
8325 new->nfor.body = copynode(n->nfor.body);
8326 new->nfor.args = copynode(n->nfor.args);
8329 new->ncase.cases = copynode(n->ncase.cases);
8330 new->ncase.expr = copynode(n->ncase.expr);
8333 new->nclist.body = copynode(n->nclist.body);
8334 new->nclist.pattern = copynode(n->nclist.pattern);
8335 new->nclist.next = copynode(n->nclist.next);
8339 new->narg.backquote = copynodelist(n->narg.backquote);
8340 new->narg.text = nodeckstrdup(n->narg.text);
8341 new->narg.next = copynode(n->narg.next);
8344 #if ENABLE_ASH_BASH_COMPAT
8351 new->nfile.fname = copynode(n->nfile.fname);
8352 new->nfile.fd = n->nfile.fd;
8353 new->nfile.next = copynode(n->nfile.next);
8357 new->ndup.vname = copynode(n->ndup.vname);
8358 new->ndup.dupfd = n->ndup.dupfd;
8359 new->ndup.fd = n->ndup.fd;
8360 new->ndup.next = copynode(n->ndup.next);
8364 new->nhere.doc = copynode(n->nhere.doc);
8365 new->nhere.fd = n->nhere.fd;
8366 new->nhere.next = copynode(n->nhere.next);
8369 new->nnot.com = copynode(n->nnot.com);
8372 new->type = n->type;
8377 * Make a copy of a parse tree.
8379 static struct funcnode *
8380 copyfunc(union node *n)
8385 /*funcstringsize = 0;*/
8386 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8387 f = ckzalloc(blocksize /* + funcstringsize */);
8388 funcblock = (char *) f + offsetof(struct funcnode, n);
8389 funcstring_end = (char *) f + blocksize;
8391 /* f->count = 0; - ckzalloc did it */
8396 * Define a shell function.
8399 defun(union node *func)
8401 struct cmdentry entry;
8404 entry.cmdtype = CMDFUNCTION;
8405 entry.u.func = copyfunc(func);
8406 addcmdentry(func->narg.text, &entry);
8410 /* Reasons for skipping commands (see comment on breakcmd routine) */
8411 #define SKIPBREAK (1 << 0)
8412 #define SKIPCONT (1 << 1)
8413 #define SKIPFUNC (1 << 2)
8414 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8415 static int skipcount; /* number of levels to skip */
8416 static int funcnest; /* depth of function calls */
8417 static int loopnest; /* current loop nesting level */
8419 /* Forward decl way out to parsing code - dotrap needs it */
8420 static int evalstring(char *s, int flags);
8422 /* Called to execute a trap.
8423 * Single callsite - at the end of evaltree().
8424 * If we return non-zero, evaltree raises EXEXIT exception.
8426 * Perhaps we should avoid entering new trap handlers
8427 * while we are executing a trap handler. [is it a TODO?]
8434 uint8_t last_status;
8439 last_status = exitstatus;
8443 TRACE(("dotrap entered\n"));
8444 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8456 /* non-trapped SIGINT is handled separately by raise_interrupt,
8457 * don't upset it by resetting gotsig[SIGINT-1] */
8458 if (sig == SIGINT && !p)
8461 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8467 exitstatus = last_status;
8468 TRACE(("dotrap returns\n"));
8471 /* forward declarations - evaluation is fairly recursive business... */
8472 static int evalloop(union node *, int);
8473 static int evalfor(union node *, int);
8474 static int evalcase(union node *, int);
8475 static int evalsubshell(union node *, int);
8476 static void expredir(union node *);
8477 static int evalpipe(union node *, int);
8478 static int evalcommand(union node *, int);
8479 static int evalbltin(const struct builtincmd *, int, char **, int);
8480 static void prehash(union node *);
8483 * Evaluate a parse tree. The value is left in the global variable
8487 evaltree(union node *n, int flags)
8489 struct jmploc *volatile savehandler = exception_handler;
8490 struct jmploc jmploc;
8492 int (*evalfn)(union node *, int);
8496 SAVE_INT(int_level);
8499 TRACE(("evaltree(NULL) called\n"));
8502 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8506 exception_handler = &jmploc;
8508 int err = setjmp(jmploc.loc);
8510 /* if it was a signal, check for trap handlers */
8511 if (exception_type == EXSIG) {
8512 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8513 exception_type, err));
8516 /* continue on the way out */
8517 TRACE(("exception %d in evaltree, propagating err=%d\n",
8518 exception_type, err));
8519 exception_handler = savehandler;
8520 longjmp(exception_handler->loc, err);
8527 out1fmt("Node type = %d\n", n->type);
8532 status = !evaltree(n->nnot.com, EV_TESTED);
8535 expredir(n->nredir.redirect);
8536 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8538 status = evaltree(n->nredir.n, flags & EV_TESTED);
8540 if (n->nredir.redirect)
8541 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8544 evalfn = evalcommand;
8546 if (eflag && !(flags & EV_TESTED))
8558 evalfn = evalsubshell;
8571 #error NAND + 1 != NOR
8573 #if NOR + 1 != NSEMI
8574 #error NOR + 1 != NSEMI
8576 unsigned is_or = n->type - NAND;
8579 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8581 if ((!status) == is_or || evalskip)
8587 status = evalfn(n, flags);
8591 status = evaltree(n->nif.test, EV_TESTED);
8598 if (n->nif.elsepart) {
8599 n = n->nif.elsepart;
8606 /* Not necessary. To test it:
8607 * "false; f() { qwerty; }; echo $?" should print 0.
8611 exitstatus = status;
8616 exception_handler = savehandler;
8619 /* Order of checks below is important:
8620 * signal handlers trigger before exit caused by "set -e".
8624 if (checkexit & status)
8625 raise_exception(EXEXIT);
8626 if (flags & EV_EXIT)
8627 raise_exception(EXEXIT);
8629 RESTORE_INT(int_level);
8630 TRACE(("leaving evaltree (no interrupts)\n"));
8635 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8638 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8643 int skip = evalskip;
8650 if (--skipcount <= 0) {
8661 evalloop(union node *n, int flags)
8672 i = evaltree(n->nbinary.ch1, EV_TESTED);
8674 if (skip == SKIPFUNC)
8678 if (n->type != NWHILE)
8682 status = evaltree(n->nbinary.ch2, flags);
8684 } while (!(skip & ~SKIPCONT));
8691 evalfor(union node *n, int flags)
8693 struct arglist arglist;
8696 struct stackmark smark;
8699 setstackmark(&smark);
8700 arglist.list = NULL;
8701 arglist.lastp = &arglist.list;
8702 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8703 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8705 *arglist.lastp = NULL;
8709 for (sp = arglist.list; sp; sp = sp->next) {
8710 setvar0(n->nfor.var, sp->text);
8711 status = evaltree(n->nfor.body, flags);
8712 if (skiploop() & ~SKIPCONT)
8716 popstackmark(&smark);
8722 evalcase(union node *n, int flags)
8726 struct arglist arglist;
8727 struct stackmark smark;
8730 setstackmark(&smark);
8731 arglist.list = NULL;
8732 arglist.lastp = &arglist.list;
8733 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8734 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8735 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8736 if (casematch(patp, arglist.list->text)) {
8737 /* Ensure body is non-empty as otherwise
8738 * EV_EXIT may prevent us from setting the
8741 if (evalskip == 0 && cp->nclist.body) {
8742 status = evaltree(cp->nclist.body, flags);
8749 popstackmark(&smark);
8755 * Kick off a subshell to evaluate a tree.
8758 evalsubshell(union node *n, int flags)
8761 int backgnd = (n->type == NBACKGND);
8764 expredir(n->nredir.redirect);
8765 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8768 jp = makejob(/*n,*/ 1);
8769 if (forkshell(jp, n, backgnd) == 0) {
8774 flags &= ~EV_TESTED;
8776 redirect(n->nredir.redirect, 0);
8777 evaltreenr(n->nredir.n, flags);
8783 status = waitforjob(jp);
8789 * Compute the names of the files in a redirection list.
8791 static void fixredir(union node *, const char *, int);
8793 expredir(union node *n)
8797 for (redir = n; redir; redir = redir->nfile.next) {
8801 fn.lastp = &fn.list;
8802 switch (redir->type) {
8806 #if ENABLE_ASH_BASH_COMPAT
8811 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8812 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8813 #if ENABLE_ASH_BASH_COMPAT
8817 // By the design of stack allocator, the loop of this kind:
8818 // while true; do while true; do break; done </dev/null; done
8819 // will look like a memory leak: ash plans to free expfname's
8820 // of "/dev/null" as soon as it finishes running the loop
8821 // (in this case, never).
8822 // This "fix" is wrong:
8823 if (redir->nfile.expfname)
8824 stunalloc(redir->nfile.expfname);
8825 // It results in corrupted state of stacked allocations.
8827 redir->nfile.expfname = fn.list->text;
8830 case NTOFD: /* >& */
8831 if (redir->ndup.vname) {
8832 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8833 if (fn.list == NULL)
8834 ash_msg_and_raise_error("redir error");
8835 #if ENABLE_ASH_BASH_COMPAT
8836 //FIXME: we used expandarg with different args!
8837 if (!isdigit_str9(fn.list->text)) {
8838 /* >&file, not >&fd */
8839 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8840 ash_msg_and_raise_error("redir error");
8842 goto store_expfname;
8845 fixredir(redir, fn.list->text, 1);
8853 * Evaluate a pipeline. All the processes in the pipeline are children
8854 * of the process creating the pipeline. (This differs from some versions
8855 * of the shell, which make the last process in a pipeline the parent
8859 evalpipe(union node *n, int flags)
8862 struct nodelist *lp;
8868 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8870 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8874 jp = makejob(/*n,*/ pipelen);
8876 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8880 if (pipe(pip) < 0) {
8882 ash_msg_and_raise_error("pipe call failed");
8885 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8899 evaltreenr(lp->n, flags);
8906 /* Don't want to trigger debugging */
8910 if (n->npipe.pipe_backgnd == 0) {
8911 status = waitforjob(jp);
8912 TRACE(("evalpipe: job done exit status %d\n", status));
8920 * Controls whether the shell is interactive or not.
8923 setinteractive(int on)
8925 static smallint is_interactive;
8927 if (++on == is_interactive)
8929 is_interactive = on;
8933 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8934 if (is_interactive > 1) {
8935 /* Looks like they want an interactive shell */
8936 static smallint did_banner;
8939 /* note: ash and hush share this string */
8940 out1fmt("\n\n%s %s\n"
8941 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8944 "built-in shell (ash)"
8958 setinteractive(iflag);
8960 #if ENABLE_FEATURE_EDITING_VI
8962 line_input_state->flags |= VI_MODE;
8964 line_input_state->flags &= ~VI_MODE;
8966 viflag = 0; /* forcibly keep the option off */
8970 static struct localvar *localvars;
8973 * Called after a function returns.
8974 * Interrupts must be off.
8979 struct localvar *lvp;
8982 while ((lvp = localvars) != NULL) {
8983 localvars = lvp->next;
8985 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8986 if (vp == NULL) { /* $- saved */
8987 memcpy(optlist, lvp->text, sizeof(optlist));
8988 free((char*)lvp->text);
8990 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8991 unsetvar(vp->var_text);
8994 vp->var_func(var_end(lvp->text));
8995 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8996 free((char*)vp->var_text);
8997 vp->flags = lvp->flags;
8998 vp->var_text = lvp->text;
9005 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9007 volatile struct shparam saveparam;
9008 struct localvar *volatile savelocalvars;
9009 struct jmploc *volatile savehandler;
9010 struct jmploc jmploc;
9013 saveparam = shellparam;
9014 savelocalvars = localvars;
9015 savehandler = exception_handler;
9016 e = setjmp(jmploc.loc);
9021 exception_handler = &jmploc;
9023 shellparam.malloced = 0;
9027 shellparam.nparam = argc - 1;
9028 shellparam.p = argv + 1;
9029 #if ENABLE_ASH_GETOPTS
9030 shellparam.optind = 1;
9031 shellparam.optoff = -1;
9033 evaltree(func->n.narg.next, flags & EV_TESTED);
9039 localvars = savelocalvars;
9040 freeparam(&shellparam);
9041 shellparam = saveparam;
9042 exception_handler = savehandler;
9044 evalskip &= ~SKIPFUNC;
9049 * Make a variable a local variable. When a variable is made local, it's
9050 * value and flags are saved in a localvar structure. The saved values
9051 * will be restored when the shell function returns. We handle the name
9052 * "-" as a special case: it makes changes to "set +-options" local
9053 * (options will be restored on return from the function).
9058 struct localvar *lvp;
9061 char *eq = strchr(name, '=');
9064 /* Cater for duplicate "local". Examples:
9065 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9066 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9070 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9074 * it's a duplicate "local VAR" declaration, do nothing
9081 lvp = ckzalloc(sizeof(*lvp));
9082 if (LONE_DASH(name)) {
9084 p = ckmalloc(sizeof(optlist));
9085 lvp->text = memcpy(p, optlist, sizeof(optlist));
9088 vpp = hashvar(name);
9089 vp = *findvar(vpp, name);
9091 /* variable did not exist yet */
9093 setvareq(name, VSTRFIXED);
9095 setvar(name, NULL, VSTRFIXED);
9096 vp = *vpp; /* the new variable */
9097 lvp->flags = VUNSET;
9099 lvp->text = vp->var_text;
9100 lvp->flags = vp->flags;
9101 /* make sure neither "struct var" nor string gets freed
9102 * during (un)setting:
9104 vp->flags |= VSTRFIXED|VTEXTFIXED;
9108 /* "local VAR" unsets VAR: */
9109 setvar0(name, NULL);
9113 lvp->next = localvars;
9119 * The "local" command.
9121 static int FAST_FUNC
9122 localcmd(int argc UNUSED_PARAM, char **argv)
9127 ash_msg_and_raise_error("not in a function");
9130 while ((name = *argv++) != NULL) {
9136 static int FAST_FUNC
9137 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9142 static int FAST_FUNC
9143 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9148 static int FAST_FUNC
9149 execcmd(int argc UNUSED_PARAM, char **argv)
9152 iflag = 0; /* exit on error */
9155 /* We should set up signals for "exec CMD"
9156 * the same way as for "CMD" without "exec".
9157 * But optschanged->setinteractive->setsignal
9158 * still thought we are a root shell. Therefore, for example,
9159 * SIGQUIT is still set to IGN. Fix it:
9163 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9164 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9165 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9167 shellexec(argv + 1, pathval(), 0);
9174 * The return command.
9176 static int FAST_FUNC
9177 returncmd(int argc UNUSED_PARAM, char **argv)
9180 * If called outside a function, do what ksh does;
9181 * skip the rest of the file.
9183 evalskip = SKIPFUNC;
9184 return argv[1] ? number(argv[1]) : exitstatus;
9187 /* Forward declarations for builtintab[] */
9188 static int breakcmd(int, char **) FAST_FUNC;
9189 static int dotcmd(int, char **) FAST_FUNC;
9190 static int evalcmd(int, char **, int) FAST_FUNC;
9191 static int exitcmd(int, char **) FAST_FUNC;
9192 static int exportcmd(int, char **) FAST_FUNC;
9193 #if ENABLE_ASH_GETOPTS
9194 static int getoptscmd(int, char **) FAST_FUNC;
9197 static int helpcmd(int, char **) FAST_FUNC;
9200 static int historycmd(int, char **) FAST_FUNC;
9202 #if ENABLE_SH_MATH_SUPPORT
9203 static int letcmd(int, char **) FAST_FUNC;
9205 static int readcmd(int, char **) FAST_FUNC;
9206 static int setcmd(int, char **) FAST_FUNC;
9207 static int shiftcmd(int, char **) FAST_FUNC;
9208 static int timescmd(int, char **) FAST_FUNC;
9209 static int trapcmd(int, char **) FAST_FUNC;
9210 static int umaskcmd(int, char **) FAST_FUNC;
9211 static int unsetcmd(int, char **) FAST_FUNC;
9212 static int ulimitcmd(int, char **) FAST_FUNC;
9214 #define BUILTIN_NOSPEC "0"
9215 #define BUILTIN_SPECIAL "1"
9216 #define BUILTIN_REGULAR "2"
9217 #define BUILTIN_SPEC_REG "3"
9218 #define BUILTIN_ASSIGN "4"
9219 #define BUILTIN_SPEC_ASSG "5"
9220 #define BUILTIN_REG_ASSG "6"
9221 #define BUILTIN_SPEC_REG_ASSG "7"
9223 /* Stubs for calling non-FAST_FUNC's */
9224 #if ENABLE_ASH_BUILTIN_ECHO
9225 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9227 #if ENABLE_ASH_BUILTIN_PRINTF
9228 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9230 #if ENABLE_ASH_BUILTIN_TEST
9231 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9234 /* Keep these in proper order since it is searched via bsearch() */
9235 static const struct builtincmd builtintab[] = {
9236 { BUILTIN_SPEC_REG "." , dotcmd },
9237 { BUILTIN_SPEC_REG ":" , truecmd },
9238 #if ENABLE_ASH_BUILTIN_TEST
9239 { BUILTIN_REGULAR "[" , testcmd },
9240 #if ENABLE_ASH_BASH_COMPAT
9241 { BUILTIN_REGULAR "[[" , testcmd },
9244 #if ENABLE_ASH_ALIAS
9245 { BUILTIN_REG_ASSG "alias" , aliascmd },
9248 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9250 { BUILTIN_SPEC_REG "break" , breakcmd },
9251 { BUILTIN_REGULAR "cd" , cdcmd },
9252 { BUILTIN_NOSPEC "chdir" , cdcmd },
9253 #if ENABLE_ASH_CMDCMD
9254 { BUILTIN_REGULAR "command" , commandcmd },
9256 { BUILTIN_SPEC_REG "continue", breakcmd },
9257 #if ENABLE_ASH_BUILTIN_ECHO
9258 { BUILTIN_REGULAR "echo" , echocmd },
9260 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9261 { BUILTIN_SPEC_REG "exec" , execcmd },
9262 { BUILTIN_SPEC_REG "exit" , exitcmd },
9263 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9264 { BUILTIN_REGULAR "false" , falsecmd },
9266 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9268 #if ENABLE_ASH_GETOPTS
9269 { BUILTIN_REGULAR "getopts" , getoptscmd },
9271 { BUILTIN_NOSPEC "hash" , hashcmd },
9273 { BUILTIN_NOSPEC "help" , helpcmd },
9276 { BUILTIN_NOSPEC "history" , historycmd },
9279 { BUILTIN_REGULAR "jobs" , jobscmd },
9280 { BUILTIN_REGULAR "kill" , killcmd },
9282 #if ENABLE_SH_MATH_SUPPORT
9283 { BUILTIN_NOSPEC "let" , letcmd },
9285 { BUILTIN_ASSIGN "local" , localcmd },
9286 #if ENABLE_ASH_BUILTIN_PRINTF
9287 { BUILTIN_REGULAR "printf" , printfcmd },
9289 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9290 { BUILTIN_REGULAR "read" , readcmd },
9291 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9292 { BUILTIN_SPEC_REG "return" , returncmd },
9293 { BUILTIN_SPEC_REG "set" , setcmd },
9294 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9295 #if ENABLE_ASH_BASH_COMPAT
9296 { BUILTIN_SPEC_REG "source" , dotcmd },
9298 #if ENABLE_ASH_BUILTIN_TEST
9299 { BUILTIN_REGULAR "test" , testcmd },
9301 { BUILTIN_SPEC_REG "times" , timescmd },
9302 { BUILTIN_SPEC_REG "trap" , trapcmd },
9303 { BUILTIN_REGULAR "true" , truecmd },
9304 { BUILTIN_NOSPEC "type" , typecmd },
9305 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9306 { BUILTIN_REGULAR "umask" , umaskcmd },
9307 #if ENABLE_ASH_ALIAS
9308 { BUILTIN_REGULAR "unalias" , unaliascmd },
9310 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9311 { BUILTIN_REGULAR "wait" , waitcmd },
9314 /* Should match the above table! */
9315 #define COMMANDCMD (builtintab + \
9317 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9318 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9319 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9320 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9321 /* break cd cddir */ 3)
9322 #define EVALCMD (COMMANDCMD + \
9323 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9324 /* continue */ 1 + \
9325 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9327 #define EXECCMD (EVALCMD + \
9331 * Search the table of builtin commands.
9334 pstrcmp1(const void *a, const void *b)
9336 return strcmp((char*)a, *(char**)b + 1);
9338 static struct builtincmd *
9339 find_builtin(const char *name)
9341 struct builtincmd *bp;
9344 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9351 * Execute a simple command.
9354 isassignment(const char *p)
9356 const char *q = endofname(p);
9361 static int FAST_FUNC
9362 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9364 /* Preserve exitstatus of a previous possible redirection
9365 * as POSIX mandates */
9366 return back_exitstatus;
9369 evalcommand(union node *cmd, int flags)
9371 static const struct builtincmd null_bltin = {
9372 "\0\0", bltincmd /* why three NULs? */
9374 struct stackmark smark;
9376 struct arglist arglist;
9377 struct arglist varlist;
9380 const struct strlist *sp;
9381 struct cmdentry cmdentry;
9388 struct builtincmd *bcmd;
9389 smallint cmd_is_exec;
9390 smallint pseudovarflag = 0;
9392 /* First expand the arguments. */
9393 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9394 setstackmark(&smark);
9395 back_exitstatus = 0;
9397 cmdentry.cmdtype = CMDBUILTIN;
9398 cmdentry.u.cmd = &null_bltin;
9399 varlist.lastp = &varlist.list;
9400 *varlist.lastp = NULL;
9401 arglist.lastp = &arglist.list;
9402 *arglist.lastp = NULL;
9405 if (cmd->ncmd.args) {
9406 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9407 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9410 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9411 struct strlist **spp;
9413 spp = arglist.lastp;
9414 if (pseudovarflag && isassignment(argp->narg.text))
9415 expandarg(argp, &arglist, EXP_VARTILDE);
9417 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9419 for (sp = *spp; sp; sp = sp->next)
9423 /* Reserve one extra spot at the front for shellexec. */
9424 nargv = stalloc(sizeof(char *) * (argc + 2));
9426 for (sp = arglist.list; sp; sp = sp->next) {
9427 TRACE(("evalcommand arg: %s\n", sp->text));
9428 *nargv++ = sp->text;
9433 if (iflag && funcnest == 0 && argc > 0)
9434 lastarg = nargv[-1];
9437 expredir(cmd->ncmd.redirect);
9438 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9440 path = vpath.var_text;
9441 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9442 struct strlist **spp;
9445 spp = varlist.lastp;
9446 expandarg(argp, &varlist, EXP_VARTILDE);
9449 * Modify the command lookup path, if a PATH= assignment
9453 if (varcmp(p, path) == 0)
9457 /* Print the command if xflag is set. */
9460 const char *p = " %s" + 1;
9462 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9464 for (n = 0; n < 2; n++) {
9466 fdprintf(preverrout_fd, p, sp->text);
9472 safe_write(preverrout_fd, "\n", 1);
9478 /* Now locate the command. */
9480 int cmd_flag = DO_ERR;
9481 #if ENABLE_ASH_CMDCMD
9482 const char *oldpath = path + 5;
9486 find_command(argv[0], &cmdentry, cmd_flag, path);
9487 if (cmdentry.cmdtype == CMDUNKNOWN) {
9488 flush_stdout_stderr();
9493 /* implement bltin and command here */
9494 if (cmdentry.cmdtype != CMDBUILTIN)
9497 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9498 if (cmdentry.u.cmd == EXECCMD)
9500 #if ENABLE_ASH_CMDCMD
9501 if (cmdentry.u.cmd == COMMANDCMD) {
9503 nargv = parse_command_args(argv, &path);
9506 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9507 * nargv => "PROG". path is updated if -p.
9509 argc -= nargv - argv;
9511 cmd_flag |= DO_NOFUNC;
9519 /* We have a redirection error. */
9521 raise_exception(EXERROR);
9523 exitstatus = status;
9527 /* Execute the command. */
9528 switch (cmdentry.cmdtype) {
9531 #if ENABLE_FEATURE_SH_NOFORK
9532 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9533 * around run_nofork_applet() call.
9534 * (2) Should this check also be done in forkshell()?
9535 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9537 /* find_command() encodes applet_no as (-2 - applet_no) */
9538 int applet_no = (- cmdentry.u.index - 2);
9539 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9540 listsetvar(varlist.list, VEXPORT|VSTACK);
9541 /* run <applet>_main() */
9542 status = run_nofork_applet(applet_no, argv);
9546 /* Can we avoid forking off? For example, very last command
9547 * in a script or a subshell does not need forking,
9548 * we can just exec it.
9550 if (!(flags & EV_EXIT) || may_have_traps) {
9551 /* No, forking off a child is necessary */
9553 jp = makejob(/*cmd,*/ 1);
9554 if (forkshell(jp, cmd, FORK_FG) != 0) {
9556 status = waitforjob(jp);
9558 TRACE(("forked child exited with %d\n", status));
9563 /* fall through to exec'ing external program */
9565 listsetvar(varlist.list, VEXPORT|VSTACK);
9566 shellexec(argv, path, cmdentry.u.index);
9570 cmdenviron = varlist.list;
9572 struct strlist *list = cmdenviron;
9574 if (spclbltin > 0 || argc == 0) {
9576 if (cmd_is_exec && argc > 1)
9579 listsetvar(list, i);
9581 /* Tight loop with builtins only:
9582 * "while kill -0 $child; do true; done"
9583 * will never exit even if $child died, unless we do this
9584 * to reap the zombie and make kill detect that it's gone: */
9585 dowait(DOWAIT_NONBLOCK, NULL);
9587 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9589 int i = exception_type;
9594 exit_status = 128 + SIGINT;
9596 exit_status = 128 + pending_sig;
9597 exitstatus = exit_status;
9598 if (i == EXINT || spclbltin > 0) {
9600 longjmp(exception_handler->loc, 1);
9607 listsetvar(varlist.list, 0);
9608 /* See above for the rationale */
9609 dowait(DOWAIT_NONBLOCK, NULL);
9610 if (evalfun(cmdentry.u.func, argc, argv, flags))
9613 status = exitstatus;
9618 if (cmd->ncmd.redirect)
9619 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9621 /* dsl: I think this is intended to be used to support
9622 * '_' in 'vi' command mode during line editing...
9623 * However I implemented that within libedit itself.
9625 setvar0("_", lastarg);
9627 popstackmark(&smark);
9633 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9635 char *volatile savecmdname;
9636 struct jmploc *volatile savehandler;
9637 struct jmploc jmploc;
9641 savecmdname = commandname;
9642 savehandler = exception_handler;
9643 i = setjmp(jmploc.loc);
9646 exception_handler = &jmploc;
9647 commandname = argv[0];
9649 optptr = NULL; /* initialize nextopt */
9651 status = evalcmd(argc, argv, flags);
9653 status = (*cmd->builtin)(argc, argv);
9654 flush_stdout_stderr();
9655 status |= ferror(stdout);
9656 exitstatus = status;
9659 commandname = savecmdname;
9660 exception_handler = savehandler;
9666 goodname(const char *p)
9668 return endofname(p)[0] == '\0';
9673 * Search for a command. This is called before we fork so that the
9674 * location of the command will be available in the parent as well as
9675 * the child. The check for "goodname" is an overly conservative
9676 * check that the name will not be subject to expansion.
9679 prehash(union node *n)
9681 struct cmdentry entry;
9683 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9684 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9688 /* ============ Builtin commands
9690 * Builtin commands whose functions are closely tied to evaluation
9691 * are implemented here.
9695 * Handle break and continue commands. Break, continue, and return are
9696 * all handled by setting the evalskip flag. The evaluation routines
9697 * above all check this flag, and if it is set they start skipping
9698 * commands rather than executing them. The variable skipcount is
9699 * the number of loops to break/continue, or the number of function
9700 * levels to return. (The latter is always 1.) It should probably
9701 * be an error to break out of more loops than exist, but it isn't
9702 * in the standard shell so we don't make it one here.
9704 static int FAST_FUNC
9705 breakcmd(int argc UNUSED_PARAM, char **argv)
9707 int n = argv[1] ? number(argv[1]) : 1;
9710 ash_msg_and_raise_error(msg_illnum, argv[1]);
9714 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9722 * This implements the input routines used by the parser.
9726 INPUT_PUSH_FILE = 1,
9727 INPUT_NOFILE_OK = 2,
9730 static smallint checkkwd;
9731 /* values of checkkwd variable */
9732 #define CHKALIAS 0x1
9737 * Push a string back onto the input at this current parsefile level.
9738 * We handle aliases this way.
9740 #if !ENABLE_ASH_ALIAS
9741 #define pushstring(s, ap) pushstring(s)
9744 pushstring(char *s, struct alias *ap)
9751 if (g_parsefile->strpush) {
9752 sp = ckzalloc(sizeof(*sp));
9753 sp->prev = g_parsefile->strpush;
9755 sp = &(g_parsefile->basestrpush);
9757 g_parsefile->strpush = sp;
9758 sp->prev_string = g_parsefile->next_to_pgetc;
9759 sp->prev_left_in_line = g_parsefile->left_in_line;
9760 sp->unget = g_parsefile->unget;
9761 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9762 #if ENABLE_ASH_ALIAS
9765 ap->flag |= ALIASINUSE;
9769 g_parsefile->next_to_pgetc = s;
9770 g_parsefile->left_in_line = len;
9771 g_parsefile->unget = 0;
9778 struct strpush *sp = g_parsefile->strpush;
9781 #if ENABLE_ASH_ALIAS
9783 if (g_parsefile->next_to_pgetc[-1] == ' '
9784 || g_parsefile->next_to_pgetc[-1] == '\t'
9786 checkkwd |= CHKALIAS;
9788 if (sp->string != sp->ap->val) {
9791 sp->ap->flag &= ~ALIASINUSE;
9792 if (sp->ap->flag & ALIASDEAD) {
9793 unalias(sp->ap->name);
9797 g_parsefile->next_to_pgetc = sp->prev_string;
9798 g_parsefile->left_in_line = sp->prev_left_in_line;
9799 g_parsefile->unget = sp->unget;
9800 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9801 g_parsefile->strpush = sp->prev;
9802 if (sp != &(g_parsefile->basestrpush))
9811 char *buf = g_parsefile->buf;
9813 g_parsefile->next_to_pgetc = buf;
9814 #if ENABLE_FEATURE_EDITING
9816 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9817 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9820 # if ENABLE_ASH_IDLE_TIMEOUT
9822 const char *tmout_var = lookupvar("TMOUT");
9824 timeout = atoi(tmout_var) * 1000;
9830 # if ENABLE_FEATURE_TAB_COMPLETION
9831 line_input_state->path_lookup = pathval();
9833 reinit_unicode_for_ash();
9834 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9836 /* Ctrl+C pressed */
9847 /* Ctrl+D pressed */
9850 # if ENABLE_ASH_IDLE_TIMEOUT
9851 else if (errno == EAGAIN && timeout > 0) {
9852 puts("\007timed out waiting for input: auto-logout");
9859 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9862 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9864 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9865 int flags = fcntl(0, F_GETFL);
9866 if (flags >= 0 && (flags & O_NONBLOCK)) {
9867 flags &= ~O_NONBLOCK;
9868 if (fcntl(0, F_SETFL, flags) >= 0) {
9869 out2str("sh: turning off NDELAY mode\n");
9880 * Refill the input buffer and return the next input character:
9882 * 1) If a string was pushed back on the input, pop it;
9883 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9884 * or we are reading from a string so we can't refill the buffer,
9886 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9887 * 4) Process input up to the next newline, deleting nul characters.
9889 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9890 #define pgetc_debug(...) ((void)0)
9891 static int pgetc(void);
9898 if (g_parsefile->strpush) {
9899 #if ENABLE_ASH_ALIAS
9900 if (g_parsefile->left_in_line == -1
9901 && g_parsefile->strpush->ap
9902 && g_parsefile->next_to_pgetc[-1] != ' '
9903 && g_parsefile->next_to_pgetc[-1] != '\t'
9905 pgetc_debug("preadbuffer PEOA");
9912 /* on both branches above g_parsefile->left_in_line < 0.
9913 * "pgetc" needs refilling.
9916 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9917 * pungetc() may increment it a few times.
9918 * Assuming it won't increment it to less than -90.
9920 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9921 pgetc_debug("preadbuffer PEOF1");
9922 /* even in failure keep left_in_line and next_to_pgetc
9923 * in lock step, for correct multi-layer pungetc.
9924 * left_in_line was decremented before preadbuffer(),
9925 * must inc next_to_pgetc: */
9926 g_parsefile->next_to_pgetc++;
9930 more = g_parsefile->left_in_buffer;
9932 flush_stdout_stderr();
9936 /* don't try reading again */
9937 g_parsefile->left_in_line = -99;
9938 pgetc_debug("preadbuffer PEOF2");
9939 g_parsefile->next_to_pgetc++;
9944 /* Find out where's the end of line.
9945 * Set g_parsefile->left_in_line
9946 * and g_parsefile->left_in_buffer acordingly.
9947 * NUL chars are deleted.
9949 q = g_parsefile->next_to_pgetc;
9957 memmove(q, q + 1, more);
9961 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9967 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9968 if (g_parsefile->left_in_line < 0)
9973 g_parsefile->left_in_buffer = more;
9978 out2str(g_parsefile->next_to_pgetc);
9982 pgetc_debug("preadbuffer at %d:%p'%s'",
9983 g_parsefile->left_in_line,
9984 g_parsefile->next_to_pgetc,
9985 g_parsefile->next_to_pgetc);
9986 return (unsigned char)*g_parsefile->next_to_pgetc++;
9992 g_parsefile->linno++;
9993 setprompt_if(doprompt, 2);
9998 g_parsefile->linno++;
9999 needprompt = doprompt;
10007 pgetc_debug("pgetc at %d:%p'%s'",
10008 g_parsefile->left_in_line,
10009 g_parsefile->next_to_pgetc,
10010 g_parsefile->next_to_pgetc);
10011 if (g_parsefile->unget)
10012 return g_parsefile->lastc[--g_parsefile->unget];
10014 if (--g_parsefile->left_in_line >= 0)
10015 c = (signed char)*g_parsefile->next_to_pgetc++;
10019 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10020 g_parsefile->lastc[0] = c;
10025 #if ENABLE_ASH_ALIAS
10027 pgetc_without_PEOA(void)
10031 pgetc_debug("pgetc at %d:%p'%s'",
10032 g_parsefile->left_in_line,
10033 g_parsefile->next_to_pgetc,
10034 g_parsefile->next_to_pgetc);
10036 } while (c == PEOA);
10040 # define pgetc_without_PEOA() pgetc()
10044 * Read a line from the script.
10047 pfgets(char *line, int len)
10053 while (--nleft > 0) {
10054 c = pgetc_without_PEOA();
10069 * Undo a call to pgetc. Only two characters may be pushed back.
10070 * PEOF may be pushed back.
10075 g_parsefile->unget++;
10078 /* This one eats backslash+newline */
10084 while ((c = pgetc()) == '\\') {
10085 if (pgetc() != '\n') {
10097 * To handle the "." command, a stack of input files is used. Pushfile
10098 * adds a new entry to the stack and popfile restores the previous level.
10103 struct parsefile *pf;
10105 pf = ckzalloc(sizeof(*pf));
10106 pf->prev = g_parsefile;
10108 /*pf->strpush = NULL; - ckzalloc did it */
10109 /*pf->basestrpush.prev = NULL;*/
10117 struct parsefile *pf = g_parsefile;
10120 if (pf->pf_fd >= 0)
10123 while (pf->strpush)
10125 g_parsefile = pf->prev;
10131 * Return to top level.
10136 while (g_parsefile != &basepf)
10141 * Close the file(s) that the shell is reading commands from. Called
10142 * after a fork is done.
10148 if (g_parsefile->pf_fd > 0) {
10149 close(g_parsefile->pf_fd);
10150 g_parsefile->pf_fd = 0;
10155 * Like setinputfile, but takes an open file descriptor. Call this with
10159 setinputfd(int fd, int push)
10163 g_parsefile->buf = NULL;
10165 g_parsefile->pf_fd = fd;
10166 if (g_parsefile->buf == NULL)
10167 g_parsefile->buf = ckmalloc(IBUFSIZ);
10168 g_parsefile->left_in_buffer = 0;
10169 g_parsefile->left_in_line = 0;
10170 g_parsefile->linno = 1;
10174 * Set the input to take input from a file. If push is set, push the
10175 * old input onto the stack first.
10178 setinputfile(const char *fname, int flags)
10183 fd = open(fname, O_RDONLY);
10185 if (flags & INPUT_NOFILE_OK)
10188 ash_msg_and_raise_error("can't open '%s'", fname);
10193 close_on_exec_on(fd);
10194 setinputfd(fd, flags & INPUT_PUSH_FILE);
10201 * Like setinputfile, but takes input from a string.
10204 setinputstring(char *string)
10208 g_parsefile->next_to_pgetc = string;
10209 g_parsefile->left_in_line = strlen(string);
10210 g_parsefile->buf = NULL;
10211 g_parsefile->linno = 1;
10217 * Routines to check for mail.
10220 #if ENABLE_ASH_MAIL
10222 /* Hash of mtimes of mailboxes */
10223 static unsigned mailtime_hash;
10224 /* Set if MAIL or MAILPATH is changed. */
10225 static smallint mail_var_path_changed;
10228 * Print appropriate message(s) if mail has arrived.
10229 * If mail_var_path_changed is set,
10230 * then the value of MAIL has mail_var_path_changed,
10231 * so we just update the values.
10240 struct stackmark smark;
10243 setstackmark(&smark);
10244 mpath = mpathset() ? mpathval() : mailval();
10247 p = path_advance(&mpath, nullstr);
10252 for (q = p; *q; q++)
10258 q[-1] = '\0'; /* delete trailing '/' */
10259 if (stat(p, &statb) < 0) {
10262 /* Very simplistic "hash": just a sum of all mtimes */
10263 new_hash += (unsigned)statb.st_mtime;
10265 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10266 if (mailtime_hash != 0)
10267 out2str("you have mail\n");
10268 mailtime_hash = new_hash;
10270 mail_var_path_changed = 0;
10271 popstackmark(&smark);
10274 static void FAST_FUNC
10275 changemail(const char *val UNUSED_PARAM)
10277 mail_var_path_changed = 1;
10280 #endif /* ASH_MAIL */
10283 /* ============ ??? */
10286 * Set the shell parameters.
10289 setparam(char **argv)
10295 for (nparam = 0; argv[nparam]; nparam++)
10297 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10299 *ap++ = ckstrdup(*argv++);
10302 freeparam(&shellparam);
10303 shellparam.malloced = 1;
10304 shellparam.nparam = nparam;
10305 shellparam.p = newparam;
10306 #if ENABLE_ASH_GETOPTS
10307 shellparam.optind = 1;
10308 shellparam.optoff = -1;
10313 * Process shell options. The global variable argptr contains a pointer
10314 * to the argument list; we advance it past the options.
10316 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10317 * For a non-interactive shell, an error condition encountered
10318 * by a special built-in ... shall cause the shell to write a diagnostic message
10319 * to standard error and exit as shown in the following table:
10320 * Error Special Built-In
10322 * Utility syntax error (option or operand error) Shall exit
10324 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10325 * we see that bash does not do that (set "finishes" with error code 1 instead,
10326 * and shell continues), and people rely on this behavior!
10328 * set -o barfoo 2>/dev/null
10331 * Oh well. Let's mimic that.
10334 plus_minus_o(char *name, int val)
10339 for (i = 0; i < NOPTS; i++) {
10340 if (strcmp(name, optnames(i)) == 0) {
10345 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10348 for (i = 0; i < NOPTS; i++) {
10350 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10352 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10358 setoption(int flag, int val)
10362 for (i = 0; i < NOPTS; i++) {
10363 if (optletters(i) == flag) {
10368 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10372 options(int cmdline)
10380 while ((p = *argptr) != NULL) {
10382 if (c != '-' && c != '+')
10385 val = 0; /* val = 0 if c == '+' */
10388 if (p[0] == '\0' || LONE_DASH(p)) {
10390 /* "-" means turn off -x and -v */
10393 /* "--" means reset params */
10394 else if (*argptr == NULL)
10397 break; /* "-" or "--" terminates options */
10400 /* first char was + or - */
10401 while ((c = *p++) != '\0') {
10402 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10403 if (c == 'c' && cmdline) {
10404 minusc = p; /* command is after shell args */
10405 } else if (c == 'o') {
10406 if (plus_minus_o(*argptr, val)) {
10407 /* it already printed err message */
10408 return 1; /* error */
10412 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10414 /* bash does not accept +-login, we also won't */
10415 } else if (cmdline && val && (c == '-')) { /* long options */
10416 if (strcmp(p, "login") == 0)
10428 * The shift builtin command.
10430 static int FAST_FUNC
10431 shiftcmd(int argc UNUSED_PARAM, char **argv)
10438 n = number(argv[1]);
10439 if (n > shellparam.nparam)
10440 n = 0; /* bash compat, was = shellparam.nparam; */
10442 shellparam.nparam -= n;
10443 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10444 if (shellparam.malloced)
10447 ap2 = shellparam.p;
10448 while ((*ap2++ = *ap1++) != NULL)
10450 #if ENABLE_ASH_GETOPTS
10451 shellparam.optind = 1;
10452 shellparam.optoff = -1;
10459 * POSIX requires that 'set' (but not export or readonly) output the
10460 * variables in lexicographic order - by the locale's collating order (sigh).
10461 * Maybe we could keep them in an ordered balanced binary tree
10462 * instead of hashed lists.
10463 * For now just roll 'em through qsort for printing...
10466 showvars(const char *sep_prefix, int on, int off)
10469 char **ep, **epend;
10471 ep = listvars(on, off, &epend);
10472 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10474 sep = *sep_prefix ? " " : sep_prefix;
10476 for (; ep < epend; ep++) {
10480 p = strchrnul(*ep, '=');
10483 q = single_quote(++p);
10484 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10490 * The set command builtin.
10492 static int FAST_FUNC
10493 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10498 return showvars(nullstr, 0, VUNSET);
10501 retval = options(/*cmdline:*/ 0);
10502 if (retval == 0) { /* if no parse error... */
10504 if (*argptr != NULL) {
10512 #if ENABLE_ASH_RANDOM_SUPPORT
10513 static void FAST_FUNC
10514 change_random(const char *value)
10518 if (value == NULL) {
10519 /* "get", generate */
10520 t = next_random(&random_gen);
10521 /* set without recursion */
10522 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10523 vrandom.flags &= ~VNOFUNC;
10526 t = strtoul(value, NULL, 10);
10527 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10532 #if ENABLE_ASH_GETOPTS
10534 getopts(char *optstr, char *optvar, char **optfirst)
10541 int ind = shellparam.optind;
10542 int off = shellparam.optoff;
10546 shellparam.optind = -1;
10547 optnext = optfirst + ind - 1;
10549 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10552 p = optnext[-1] + off;
10553 if (p == NULL || *p == '\0') {
10554 /* Current word is done, advance */
10556 if (p == NULL || *p != '-' || *++p == '\0') {
10563 if (LONE_DASH(p)) /* check for "--" */
10568 for (q = optstr; *q != c;) {
10570 if (optstr[0] == ':') {
10572 /*sbuf[1] = '\0'; - already is */
10573 setvar0("OPTARG", sbuf);
10575 fprintf(stderr, "Illegal option -%c\n", c);
10576 unsetvar("OPTARG");
10586 if (*p == '\0' && (p = *optnext) == NULL) {
10587 if (optstr[0] == ':') {
10589 /*sbuf[1] = '\0'; - already is */
10590 setvar0("OPTARG", sbuf);
10593 fprintf(stderr, "No arg for -%c option\n", c);
10594 unsetvar("OPTARG");
10602 setvar0("OPTARG", p);
10605 setvar0("OPTARG", nullstr);
10607 ind = optnext - optfirst + 1;
10608 setvar("OPTIND", itoa(ind), VNOFUNC);
10610 /*sbuf[1] = '\0'; - already is */
10611 setvar0(optvar, sbuf);
10613 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10614 shellparam.optind = ind;
10620 * The getopts builtin. Shellparam.optnext points to the next argument
10621 * to be processed. Shellparam.optptr points to the next character to
10622 * be processed in the current argument. If shellparam.optnext is NULL,
10623 * then it's the first time getopts has been called.
10625 static int FAST_FUNC
10626 getoptscmd(int argc, char **argv)
10631 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10633 optbase = shellparam.p;
10634 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10635 shellparam.optind = 1;
10636 shellparam.optoff = -1;
10639 optbase = &argv[3];
10640 if ((unsigned)shellparam.optind > argc - 2) {
10641 shellparam.optind = 1;
10642 shellparam.optoff = -1;
10646 return getopts(argv[1], argv[2], optbase);
10648 #endif /* ASH_GETOPTS */
10651 /* ============ Shell parser */
10654 struct heredoc *next; /* next here document in list */
10655 union node *here; /* redirection node */
10656 char *eofmark; /* string indicating end of input */
10657 smallint striptabs; /* if set, strip leading tabs */
10660 static smallint tokpushback; /* last token pushed back */
10661 static smallint quoteflag; /* set if (part of) last token was quoted */
10662 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10663 static struct heredoc *heredoclist; /* list of here documents to read */
10664 static char *wordtext; /* text of last word returned by readtoken */
10665 static struct nodelist *backquotelist;
10666 static union node *redirnode;
10667 static struct heredoc *heredoc;
10669 static const char *
10670 tokname(char *buf, int tok)
10673 return tokname_array[tok];
10674 sprintf(buf, "\"%s\"", tokname_array[tok]);
10678 /* raise_error_unexpected_syntax:
10679 * Called when an unexpected token is read during the parse. The argument
10680 * is the token that is expected, or -1 if more than one type of token can
10681 * occur at this point.
10683 static void raise_error_unexpected_syntax(int) NORETURN;
10685 raise_error_unexpected_syntax(int token)
10691 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10693 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10694 raise_error_syntax(msg);
10698 #define EOFMARKLEN 79
10700 /* parsing is heavily cross-recursive, need these forward decls */
10701 static union node *andor(void);
10702 static union node *pipeline(void);
10703 static union node *parse_command(void);
10704 static void parseheredoc(void);
10705 static int peektoken(void);
10706 static int readtoken(void);
10708 static union node *
10711 union node *n1, *n2, *n3;
10716 switch (peektoken()) {
10724 if (!n1 && (nlflag & 1))
10730 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10731 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10737 if (tok == TBACKGND) {
10738 if (n2->type == NPIPE) {
10739 n2->npipe.pipe_backgnd = 1;
10741 if (n2->type != NREDIR) {
10742 n3 = stzalloc(sizeof(struct nredir));
10744 /*n3->nredir.redirect = NULL; - stzalloc did it */
10747 n2->type = NBACKGND;
10753 n3 = stzalloc(sizeof(struct nbinary));
10755 n3->nbinary.ch1 = n1;
10756 n3->nbinary.ch2 = n2;
10769 raise_error_unexpected_syntax(-1);
10776 static union node *
10779 union node *n1, *n2, *n3;
10787 } else if (t == TOR) {
10793 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10795 n3 = stzalloc(sizeof(struct nbinary));
10797 n3->nbinary.ch1 = n1;
10798 n3->nbinary.ch2 = n2;
10803 static union node *
10806 union node *n1, *n2, *pipenode;
10807 struct nodelist *lp, *prev;
10811 TRACE(("pipeline: entered\n"));
10812 if (readtoken() == TNOT) {
10814 checkkwd = CHKKWD | CHKALIAS;
10817 n1 = parse_command();
10818 if (readtoken() == TPIPE) {
10819 pipenode = stzalloc(sizeof(struct npipe));
10820 pipenode->type = NPIPE;
10821 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10822 lp = stzalloc(sizeof(struct nodelist));
10823 pipenode->npipe.cmdlist = lp;
10827 lp = stzalloc(sizeof(struct nodelist));
10828 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10829 lp->n = parse_command();
10831 } while (readtoken() == TPIPE);
10837 n2 = stzalloc(sizeof(struct nnot));
10845 static union node *
10850 n = stzalloc(sizeof(struct narg));
10852 /*n->narg.next = NULL; - stzalloc did it */
10853 n->narg.text = wordtext;
10854 n->narg.backquote = backquotelist;
10859 fixredir(union node *n, const char *text, int err)
10863 TRACE(("Fix redir %s %d\n", text, err));
10865 n->ndup.vname = NULL;
10867 fd = bb_strtou(text, NULL, 10);
10868 if (!errno && fd >= 0)
10869 n->ndup.dupfd = fd;
10870 else if (LONE_DASH(text))
10871 n->ndup.dupfd = -1;
10874 raise_error_syntax("bad fd number");
10875 n->ndup.vname = makename();
10880 * Returns true if the text contains nothing to expand (no dollar signs
10884 noexpand(const char *text)
10888 while ((c = *text++) != '\0') {
10889 if (c == CTLQUOTEMARK)
10893 else if (SIT(c, BASESYNTAX) == CCTL)
10902 union node *n = redirnode;
10904 if (readtoken() != TWORD)
10905 raise_error_unexpected_syntax(-1);
10906 if (n->type == NHERE) {
10907 struct heredoc *here = heredoc;
10911 if (quoteflag == 0)
10913 TRACE(("Here document %d\n", n->type));
10914 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10915 raise_error_syntax("illegal eof marker for << redirection");
10916 rmescapes(wordtext, 0);
10917 here->eofmark = wordtext;
10919 if (heredoclist == NULL)
10920 heredoclist = here;
10922 for (p = heredoclist; p->next; p = p->next)
10926 } else if (n->type == NTOFD || n->type == NFROMFD) {
10927 fixredir(n, wordtext, 0);
10929 n->nfile.fname = makename();
10933 static union node *
10936 union node *args, **app;
10937 union node *n = NULL;
10938 union node *vars, **vpp;
10939 union node **rpp, *redir;
10941 #if ENABLE_ASH_BASH_COMPAT
10942 smallint double_brackets_flag = 0;
10943 smallint function_flag = 0;
10953 savecheckkwd = CHKALIAS;
10956 checkkwd = savecheckkwd;
10959 #if ENABLE_ASH_BASH_COMPAT
10961 if (peektoken() != TWORD)
10962 raise_error_unexpected_syntax(TWORD);
10965 case TAND: /* "&&" */
10966 case TOR: /* "||" */
10967 if (!double_brackets_flag) {
10971 wordtext = (char *) (t == TAND ? "-a" : "-o");
10974 n = stzalloc(sizeof(struct narg));
10976 /*n->narg.next = NULL; - stzalloc did it */
10977 n->narg.text = wordtext;
10978 #if ENABLE_ASH_BASH_COMPAT
10979 if (strcmp("[[", wordtext) == 0)
10980 double_brackets_flag = 1;
10981 else if (strcmp("]]", wordtext) == 0)
10982 double_brackets_flag = 0;
10984 n->narg.backquote = backquotelist;
10985 if (savecheckkwd && isassignment(wordtext)) {
10987 vpp = &n->narg.next;
10990 app = &n->narg.next;
10993 #if ENABLE_ASH_BASH_COMPAT
10994 if (function_flag) {
10995 checkkwd = CHKNL | CHKKWD;
10996 switch (peektoken()) {
11008 if (strcmp("[[", wordtext) == 0)
11012 raise_error_unexpected_syntax(-1);
11018 *rpp = n = redirnode;
11019 rpp = &n->nfile.next;
11020 parsefname(); /* read name of redirection file */
11023 IF_ASH_BASH_COMPAT(do_func:)
11024 if (args && app == &args->narg.next
11027 struct builtincmd *bcmd;
11030 /* We have a function */
11031 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11032 raise_error_unexpected_syntax(TRP);
11033 name = n->narg.text;
11034 if (!goodname(name)
11035 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11037 raise_error_syntax("bad function name");
11040 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11041 n->narg.next = parse_command();
11044 IF_ASH_BASH_COMPAT(function_flag = 0;)
11055 n = stzalloc(sizeof(struct ncmd));
11057 n->ncmd.args = args;
11058 n->ncmd.assign = vars;
11059 n->ncmd.redirect = redir;
11063 static union node *
11064 parse_command(void)
11066 union node *n1, *n2;
11067 union node *ap, **app;
11068 union node *cp, **cpp;
11069 union node *redir, **rpp;
11076 switch (readtoken()) {
11078 raise_error_unexpected_syntax(-1);
11081 n1 = stzalloc(sizeof(struct nif));
11083 n1->nif.test = list(0);
11084 if (readtoken() != TTHEN)
11085 raise_error_unexpected_syntax(TTHEN);
11086 n1->nif.ifpart = list(0);
11088 while (readtoken() == TELIF) {
11089 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11090 n2 = n2->nif.elsepart;
11092 n2->nif.test = list(0);
11093 if (readtoken() != TTHEN)
11094 raise_error_unexpected_syntax(TTHEN);
11095 n2->nif.ifpart = list(0);
11097 if (lasttoken == TELSE)
11098 n2->nif.elsepart = list(0);
11100 n2->nif.elsepart = NULL;
11108 n1 = stzalloc(sizeof(struct nbinary));
11109 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11110 n1->nbinary.ch1 = list(0);
11113 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11114 got == TWORD ? wordtext : ""));
11115 raise_error_unexpected_syntax(TDO);
11117 n1->nbinary.ch2 = list(0);
11122 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11123 raise_error_syntax("bad for loop variable");
11124 n1 = stzalloc(sizeof(struct nfor));
11126 n1->nfor.var = wordtext;
11127 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11128 if (readtoken() == TIN) {
11130 while (readtoken() == TWORD) {
11131 n2 = stzalloc(sizeof(struct narg));
11133 /*n2->narg.next = NULL; - stzalloc did it */
11134 n2->narg.text = wordtext;
11135 n2->narg.backquote = backquotelist;
11137 app = &n2->narg.next;
11140 n1->nfor.args = ap;
11141 if (lasttoken != TNL && lasttoken != TSEMI)
11142 raise_error_unexpected_syntax(-1);
11144 n2 = stzalloc(sizeof(struct narg));
11146 /*n2->narg.next = NULL; - stzalloc did it */
11147 n2->narg.text = (char *)dolatstr;
11148 /*n2->narg.backquote = NULL;*/
11149 n1->nfor.args = n2;
11151 * Newline or semicolon here is optional (but note
11152 * that the original Bourne shell only allowed NL).
11154 if (lasttoken != TSEMI)
11157 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11158 if (readtoken() != TDO)
11159 raise_error_unexpected_syntax(TDO);
11160 n1->nfor.body = list(0);
11164 n1 = stzalloc(sizeof(struct ncase));
11166 if (readtoken() != TWORD)
11167 raise_error_unexpected_syntax(TWORD);
11168 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11170 /*n2->narg.next = NULL; - stzalloc did it */
11171 n2->narg.text = wordtext;
11172 n2->narg.backquote = backquotelist;
11173 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11174 if (readtoken() != TIN)
11175 raise_error_unexpected_syntax(TIN);
11176 cpp = &n1->ncase.cases;
11178 checkkwd = CHKNL | CHKKWD;
11180 while (t != TESAC) {
11181 if (lasttoken == TLP)
11183 *cpp = cp = stzalloc(sizeof(struct nclist));
11185 app = &cp->nclist.pattern;
11187 *app = ap = stzalloc(sizeof(struct narg));
11189 /*ap->narg.next = NULL; - stzalloc did it */
11190 ap->narg.text = wordtext;
11191 ap->narg.backquote = backquotelist;
11192 if (readtoken() != TPIPE)
11194 app = &ap->narg.next;
11197 //ap->narg.next = NULL;
11198 if (lasttoken != TRP)
11199 raise_error_unexpected_syntax(TRP);
11200 cp->nclist.body = list(2);
11202 cpp = &cp->nclist.next;
11204 checkkwd = CHKNL | CHKKWD;
11208 raise_error_unexpected_syntax(TENDCASE);
11215 n1 = stzalloc(sizeof(struct nredir));
11216 n1->type = NSUBSHELL;
11217 n1->nredir.n = list(0);
11218 /*n1->nredir.redirect = NULL; - stzalloc did it */
11225 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11229 return simplecmd();
11232 if (readtoken() != t)
11233 raise_error_unexpected_syntax(t);
11236 /* Now check for redirection which may follow command */
11237 checkkwd = CHKKWD | CHKALIAS;
11239 while (readtoken() == TREDIR) {
11240 *rpp = n2 = redirnode;
11241 rpp = &n2->nfile.next;
11247 if (n1->type != NSUBSHELL) {
11248 n2 = stzalloc(sizeof(struct nredir));
11253 n1->nredir.redirect = redir;
11258 #if ENABLE_ASH_BASH_COMPAT
11260 decode_dollar_squote(void)
11262 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11268 p = strchr(C_escapes, c);
11273 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11277 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11279 } else if (c == 'x') { /* \xHH */
11283 } while (isxdigit(c) && --cnt);
11285 if (cnt == 3) { /* \x but next char is "bad" */
11289 } else { /* simple seq like \\ or \t */
11294 c = bb_process_escape_sequence((void*)&p);
11295 } else { /* unrecognized "\z": print both chars unless ' or " */
11296 if (c != '\'' && c != '"') {
11298 c |= 0x100; /* "please encode \, then me" */
11306 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11307 * is not NULL, read a here document. In the latter case, eofmark is the
11308 * word which marks the end of the document and striptabs is true if
11309 * leading tabs should be stripped from the document. The argument c
11310 * is the first character of the input token or document.
11312 * Because C does not have internal subroutines, I have simulated them
11313 * using goto's to implement the subroutine linkage. The following macros
11314 * will run code that appears at the end of readtoken1.
11316 #define CHECKEND() {goto checkend; checkend_return:;}
11317 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11318 #define PARSESUB() {goto parsesub; parsesub_return:;}
11319 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11320 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11321 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11323 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11325 /* NB: syntax parameter fits into smallint */
11326 /* c parameter is an unsigned char or PEOF or PEOA */
11329 char line[EOFMARKLEN + 1];
11330 struct nodelist *bqlist;
11334 smallint prevsyntax; /* syntax before arithmetic */
11335 #if ENABLE_ASH_EXPAND_PRMT
11336 smallint pssyntax; /* we are expanding a prompt string */
11338 int varnest; /* levels of variables expansion */
11339 int arinest; /* levels of arithmetic expansion */
11340 int parenlevel; /* levels of parens in arithmetic */
11341 int dqvarnest; /* levels of variables expansion within double quotes */
11343 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11345 startlinno = g_parsefile->linno;
11349 #if ENABLE_ASH_EXPAND_PRMT
11350 pssyntax = (syntax == PSSYNTAX);
11354 dblquote = (syntax == DQSYNTAX);
11360 STARTSTACKSTR(out);
11362 /* For each line, until end of word */
11363 CHECKEND(); /* set c to PEOF if at end of here document */
11364 for (;;) { /* until end of line or end of word */
11365 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11366 switch (SIT(c, syntax)) {
11367 case CNL: /* '\n' */
11368 if (syntax == BASESYNTAX)
11369 goto endword; /* exit outer loop */
11373 goto loop; /* continue outer loop */
11378 #if ENABLE_ASH_BASH_COMPAT
11379 if (c == '\\' && bash_dollar_squote) {
11380 c = decode_dollar_squote();
11382 /* skip $'\000', $'\x00' (like bash) */
11386 /* Unknown escape. Encode as '\z' */
11387 c = (unsigned char)c;
11388 if (eofmark == NULL || dblquote)
11389 USTPUTC(CTLESC, out);
11390 USTPUTC('\\', out);
11394 if (eofmark == NULL || dblquote)
11395 USTPUTC(CTLESC, out);
11398 case CBACK: /* backslash */
11399 c = pgetc_without_PEOA();
11401 USTPUTC(CTLESC, out);
11402 USTPUTC('\\', out);
11404 } else if (c == '\n') {
11407 #if ENABLE_ASH_EXPAND_PRMT
11408 if (c == '$' && pssyntax) {
11409 USTPUTC(CTLESC, out);
11410 USTPUTC('\\', out);
11413 /* Backslash is retained if we are in "str" and next char isn't special */
11418 && (c != '"' || eofmark != NULL)
11420 USTPUTC('\\', out);
11422 USTPUTC(CTLESC, out);
11430 if (eofmark == NULL) {
11431 USTPUTC(CTLQUOTEMARK, out);
11439 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11440 if (eofmark != NULL && varnest == 0) {
11443 if (dqvarnest == 0) {
11444 syntax = BASESYNTAX;
11451 case CVAR: /* '$' */
11452 PARSESUB(); /* parse substitution */
11454 case CENDVAR: /* '}' */
11457 if (dqvarnest > 0) {
11464 #if ENABLE_SH_MATH_SUPPORT
11465 case CLP: /* '(' in arithmetic */
11469 case CRP: /* ')' in arithmetic */
11470 if (parenlevel > 0) {
11473 if (pgetc_eatbnl() == ')') {
11475 if (--arinest == 0) {
11476 syntax = prevsyntax;
11480 * unbalanced parens
11481 * (don't 2nd guess - no error)
11489 case CBQUOTE: /* '`' */
11493 goto endword; /* exit outer loop */
11497 if (varnest == 0) {
11498 #if ENABLE_ASH_BASH_COMPAT
11500 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11501 if (pgetc() == '>')
11502 c = 0x100 + '>'; /* flag &> */
11506 goto endword; /* exit outer loop */
11508 IF_ASH_ALIAS(if (c != PEOA))
11515 #if ENABLE_SH_MATH_SUPPORT
11516 if (syntax == ARISYNTAX)
11517 raise_error_syntax("missing '))'");
11519 if (syntax != BASESYNTAX && eofmark == NULL)
11520 raise_error_syntax("unterminated quoted string");
11521 if (varnest != 0) {
11522 startlinno = g_parsefile->linno;
11524 raise_error_syntax("missing '}'");
11526 USTPUTC('\0', out);
11527 len = out - (char *)stackblock();
11528 out = stackblock();
11529 if (eofmark == NULL) {
11530 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11533 if (isdigit_str9(out)) {
11534 PARSEREDIR(); /* passed as params: out, c */
11535 lasttoken = TREDIR;
11538 /* else: non-number X seen, interpret it
11539 * as "NNNX>file" = "NNNX >file" */
11543 quoteflag = quotef;
11544 backquotelist = bqlist;
11545 grabstackblock(len);
11549 /* end of readtoken routine */
11552 * Check to see whether we are at the end of the here document. When this
11553 * is called, c is set to the first character of the next input line. If
11554 * we are at the end of the here document, this routine sets the c to PEOF.
11558 #if ENABLE_ASH_ALIAS
11560 c = pgetc_without_PEOA();
11563 while (c == '\t') {
11564 c = pgetc_without_PEOA();
11567 if (c == *eofmark) {
11568 if (pfgets(line, sizeof(line)) != NULL) {
11573 for (q = eofmark + 1;; p++, q++) {
11577 if (!*q || cc != *q)
11584 pushstring(line, NULL);
11589 goto checkend_return;
11593 * Parse a redirection operator. The variable "out" points to a string
11594 * specifying the fd to be redirected. The variable "c" contains the
11595 * first character of the redirection operator.
11598 /* out is already checked to be a valid number or "" */
11599 int fd = (*out == '\0' ? -1 : atoi(out));
11602 np = stzalloc(sizeof(struct nfile));
11607 np->type = NAPPEND;
11609 np->type = NCLOBBER;
11612 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11618 #if ENABLE_ASH_BASH_COMPAT
11619 else if (c == 0x100 + '>') { /* this flags &> redirection */
11621 pgetc(); /* this is '>', no need to check */
11625 else { /* c == '<' */
11626 /*np->nfile.fd = 0; - stzalloc did it */
11630 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11631 np = stzalloc(sizeof(struct nhere));
11632 /*np->nfile.fd = 0; - stzalloc did it */
11635 heredoc = stzalloc(sizeof(struct heredoc));
11636 heredoc->here = np;
11639 heredoc->striptabs = 1;
11641 /*heredoc->striptabs = 0; - stzalloc did it */
11647 np->type = NFROMFD;
11651 np->type = NFROMTO;
11663 goto parseredir_return;
11667 * Parse a substitution. At this point, we have read the dollar sign
11668 * and nothing else.
11671 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11672 * (assuming ascii char codes, as the original implementation did) */
11673 #define is_special(c) \
11674 (((unsigned)(c) - 33 < 32) \
11675 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11677 unsigned char subtype;
11680 c = pgetc_eatbnl();
11681 if (c > 255 /* PEOA or PEOF */
11682 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11684 #if ENABLE_ASH_BASH_COMPAT
11685 if (syntax != DQSYNTAX && c == '\'')
11686 bash_dollar_squote = 1;
11691 } else if (c == '(') {
11692 /* $(command) or $((arith)) */
11693 if (pgetc_eatbnl() == '(') {
11694 #if ENABLE_SH_MATH_SUPPORT
11697 raise_error_syntax("you disabled math support for $((arith)) syntax");
11704 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11705 USTPUTC(CTLVAR, out);
11706 typeloc = out - (char *)stackblock();
11708 subtype = VSNORMAL;
11710 c = pgetc_eatbnl();
11715 /* $[{[#]]NAME[}] */
11718 c = pgetc_eatbnl();
11719 } while (is_in_name(c));
11720 } else if (isdigit(c)) {
11721 /* $[{[#]]NUM[}] */
11724 c = pgetc_eatbnl();
11725 } while (isdigit(c));
11726 } else if (is_special(c)) {
11727 /* $[{[#]]<specialchar>[}] */
11730 c = pgetc_eatbnl();
11731 if (!subtype && cc == '#') {
11732 subtype = VSLENGTH;
11733 if (c == '_' || isalnum(c))
11736 c = pgetc_eatbnl();
11737 if (cc == '}' || c != '}') {
11748 if (c != '}' && subtype == VSLENGTH) {
11749 /* ${#VAR didn't end with } */
11753 if (subtype == 0) {
11754 static const char types[] ALIGN1 = "}-+?=";
11755 /* ${VAR...} but not $VAR or ${#VAR} */
11756 /* c == first char after VAR */
11759 c = pgetc_eatbnl();
11760 #if ENABLE_ASH_BASH_COMPAT
11761 /* This check is only needed to not misinterpret
11762 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11765 if (!strchr(types, c)) {
11766 subtype = VSSUBSTR;
11768 break; /* "goto badsub" is bigger (!) */
11774 const char *p = strchr(types, c);
11777 subtype |= p - types + VSNORMAL;
11783 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11784 c = pgetc_eatbnl();
11790 #if ENABLE_ASH_BASH_COMPAT
11792 /* ${v/[/]pattern/repl} */
11793 //TODO: encode pattern and repl separately.
11794 // Currently ${v/$var_with_slash/repl} is horribly broken
11795 subtype = VSREPLACE;
11796 c = pgetc_eatbnl();
11799 subtype++; /* VSREPLACEALL */
11807 ((unsigned char *)stackblock())[typeloc] = subtype;
11808 if (subtype != VSNORMAL) {
11815 goto parsesub_return;
11819 * Called to parse command substitutions. Newstyle is set if the command
11820 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11821 * list of commands (passed by reference), and savelen is the number of
11822 * characters on the top of the stack which must be preserved.
11825 struct nodelist **nlpp;
11829 smallint saveprompt = 0;
11832 savelen = out - (char *)stackblock();
11835 * FIXME: this can allocate very large block on stack and SEGV.
11837 * echo "..<100kbytes>..`true` $(true) `true` ..."
11838 * allocates 100kb for every command subst. With about
11839 * a hundred command substitutions stack overflows.
11840 * With larger prepended string, SEGV happens sooner.
11842 str = alloca(savelen);
11843 memcpy(str, stackblock(), savelen);
11847 /* We must read until the closing backquote, giving special
11848 * treatment to some slashes, and then push the string and
11849 * reread it as input, interpreting it normally.
11855 STARTSTACKSTR(pout);
11859 setprompt_if(needprompt, 2);
11870 * If eating a newline, avoid putting
11871 * the newline into the new character
11872 * stream (via the STPUTC after the
11877 if (pc != '\\' && pc != '`' && pc != '$'
11878 && (!dblquote || pc != '"')
11880 STPUTC('\\', pout);
11882 if (pc <= 255 /* not PEOA or PEOF */) {
11888 IF_ASH_ALIAS(case PEOA:)
11889 startlinno = g_parsefile->linno;
11890 raise_error_syntax("EOF in backquote substitution");
11902 STPUTC('\0', pout);
11903 psavelen = pout - (char *)stackblock();
11904 if (psavelen > 0) {
11905 pstr = grabstackstr(pout);
11906 setinputstring(pstr);
11911 nlpp = &(*nlpp)->next;
11912 *nlpp = stzalloc(sizeof(**nlpp));
11913 /* (*nlpp)->next = NULL; - stzalloc did it */
11916 saveprompt = doprompt;
11923 doprompt = saveprompt;
11924 else if (readtoken() != TRP)
11925 raise_error_unexpected_syntax(TRP);
11930 * Start reading from old file again, ignoring any pushed back
11931 * tokens left from the backquote parsing
11936 while (stackblocksize() <= savelen)
11938 STARTSTACKSTR(out);
11940 memcpy(out, str, savelen);
11941 STADJUST(savelen, out);
11943 USTPUTC(CTLBACKQ, out);
11945 goto parsebackq_oldreturn;
11946 goto parsebackq_newreturn;
11949 #if ENABLE_SH_MATH_SUPPORT
11951 * Parse an arithmetic expansion (indicate start of one and set state)
11954 if (++arinest == 1) {
11955 prevsyntax = syntax;
11956 syntax = ARISYNTAX;
11958 USTPUTC(CTLARI, out);
11959 goto parsearith_return;
11962 } /* end of readtoken */
11965 * Read the next input token.
11966 * If the token is a word, we set backquotelist to the list of cmds in
11967 * backquotes. We set quoteflag to true if any part of the word was
11969 * If the token is TREDIR, then we set redirnode to a structure containing
11971 * In all cases, the variable startlinno is set to the number of the line
11972 * on which the token starts.
11974 * [Change comment: here documents and internal procedures]
11975 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11976 * word parsing code into a separate routine. In this case, readtoken
11977 * doesn't need to have any internal procedures, but parseword does.
11978 * We could also make parseoperator in essence the main routine, and
11979 * have parseword (readtoken1?) handle both words and redirection.]
11981 #define NEW_xxreadtoken
11982 #ifdef NEW_xxreadtoken
11983 /* singles must be first! */
11984 static const char xxreadtoken_chars[7] ALIGN1 = {
11985 '\n', '(', ')', /* singles */
11986 '&', '|', ';', /* doubles */
11990 #define xxreadtoken_singles 3
11991 #define xxreadtoken_doubles 3
11993 static const char xxreadtoken_tokens[] ALIGN1 = {
11994 TNL, TLP, TRP, /* only single occurrence allowed */
11995 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11996 TEOF, /* corresponds to trailing nul */
11997 TAND, TOR, TENDCASE /* if double occurrence */
12009 setprompt_if(needprompt, 2);
12010 startlinno = g_parsefile->linno;
12011 for (;;) { /* until token or start of word found */
12013 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12017 while ((c = pgetc()) != '\n' && c != PEOF)
12020 } else if (c == '\\') {
12021 if (pgetc() != '\n') {
12023 break; /* return readtoken1(...) */
12029 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12035 p = strchr(xxreadtoken_chars, c);
12037 break; /* return readtoken1(...) */
12039 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12041 if (cc == c) { /* double occurrence? */
12042 p += xxreadtoken_doubles + 1;
12045 #if ENABLE_ASH_BASH_COMPAT
12046 if (c == '&' && cc == '>') /* &> */
12047 break; /* return readtoken1(...) */
12052 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12057 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12059 #else /* old xxreadtoken */
12060 #define RETURN(token) return lasttoken = token
12070 setprompt_if(needprompt, 2);
12071 startlinno = g_parsefile->linno;
12072 for (;;) { /* until token or start of word found */
12075 case ' ': case '\t':
12076 IF_ASH_ALIAS(case PEOA:)
12079 while ((c = pgetc()) != '\n' && c != PEOF)
12084 if (pgetc() == '\n') {
12096 if (pgetc() == '&')
12101 if (pgetc() == '|')
12106 if (pgetc() == ';')
12119 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12122 #endif /* old xxreadtoken */
12128 int kwd = checkkwd;
12130 smallint alreadyseen = tokpushback;
12133 #if ENABLE_ASH_ALIAS
12149 if (t != TWORD || quoteflag) {
12154 * check for keywords
12156 if (kwd & CHKKWD) {
12157 const char *const *pp;
12159 pp = findkwd(wordtext);
12161 lasttoken = t = pp - tokname_array;
12162 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12167 if (checkkwd & CHKALIAS) {
12168 #if ENABLE_ASH_ALIAS
12170 ap = lookupalias(wordtext, 1);
12173 pushstring(ap->val, ap);
12183 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12185 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12201 * Read and parse a command. Returns NODE_EOF on end of file.
12202 * (NULL is a valid parse tree indicating a blank line.)
12204 static union node *
12205 parsecmd(int interact)
12210 doprompt = interact;
12211 setprompt_if(doprompt, doprompt);
12217 * Input any here documents.
12222 struct heredoc *here;
12225 here = heredoclist;
12226 heredoclist = NULL;
12229 setprompt_if(needprompt, 2);
12230 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12231 here->eofmark, here->striptabs);
12232 n = stzalloc(sizeof(struct narg));
12233 n->narg.type = NARG;
12234 /*n->narg.next = NULL; - stzalloc did it */
12235 n->narg.text = wordtext;
12236 n->narg.backquote = backquotelist;
12237 here->here->nhere.doc = n;
12244 * called by editline -- any expansions to the prompt should be added here.
12246 #if ENABLE_ASH_EXPAND_PRMT
12247 static const char *
12248 expandstr(const char *ps)
12253 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12254 * and token processing _can_ alter it (delete NULs etc). */
12255 setinputstring((char *)ps);
12257 saveprompt = doprompt;
12259 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12260 doprompt = saveprompt;
12264 n.narg.type = NARG;
12265 n.narg.next = NULL;
12266 n.narg.text = wordtext;
12267 n.narg.backquote = backquotelist;
12269 expandarg(&n, NULL, EXP_QUOTED);
12270 return stackblock();
12275 * Execute a command or commands contained in a string.
12278 evalstring(char *s, int flags)
12281 struct stackmark smark;
12286 setstackmark(&smark);
12289 while ((n = parsecmd(0)) != NODE_EOF) {
12292 i = evaltree(n, flags);
12295 popstackmark(&smark);
12299 popstackmark(&smark);
12307 * The eval command.
12309 static int FAST_FUNC
12310 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12319 STARTSTACKSTR(concat);
12321 concat = stack_putstr(p, concat);
12325 STPUTC(' ', concat);
12327 STPUTC('\0', concat);
12328 p = grabstackstr(concat);
12330 return evalstring(p, flags & EV_TESTED);
12336 * Read and execute commands.
12337 * "Top" is nonzero for the top level command loop;
12338 * it turns on prompting if the shell is interactive.
12344 struct stackmark smark;
12349 TRACE(("cmdloop(%d) called\n", top));
12353 setstackmark(&smark);
12356 showjobs(SHOW_CHANGED|SHOW_STDERR);
12359 if (iflag && top) {
12363 n = parsecmd(inter);
12365 if (DEBUG > 2 && debug && (n != NODE_EOF))
12368 if (n == NODE_EOF) {
12369 if (!top || numeof >= 50)
12371 if (!stoppedjobs()) {
12374 out2str("\nUse \"exit\" to leave shell.\n");
12377 } else if (nflag == 0) {
12380 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12383 i = evaltree(n, 0);
12387 popstackmark(&smark);
12391 evalskip &= ~SKIPFUNC;
12399 * Take commands from a file. To be compatible we should do a path
12400 * search for the file, which is necessary to find sub-commands.
12403 find_dot_file(char *name)
12406 const char *path = pathval();
12409 /* don't try this for absolute or relative paths */
12410 if (strchr(name, '/'))
12413 /* IIRC standards do not say whether . is to be searched.
12414 * And it is even smaller this way, making it unconditional for now:
12416 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12421 while ((fullname = path_advance(&path, name)) != NULL) {
12423 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12425 * Don't bother freeing here, since it will
12426 * be freed by the caller.
12430 if (fullname != name)
12431 stunalloc(fullname);
12434 /* not found in the PATH */
12435 ash_msg_and_raise_error("%s: not found", name);
12439 static int FAST_FUNC
12440 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12442 /* "false; . empty_file; echo $?" should print 0, not 1: */
12446 struct strlist *sp;
12447 volatile struct shparam saveparam;
12449 for (sp = cmdenviron; sp; sp = sp->next)
12450 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12452 nextopt(nullstr); /* handle possible "--" */
12456 /* bash says: "bash: .: filename argument required" */
12457 return 2; /* bash compat */
12460 /* This aborts if file isn't found, which is POSIXly correct.
12461 * bash returns exitcode 1 instead.
12463 fullname = find_dot_file(argv[0]);
12465 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12467 saveparam = shellparam;
12468 shellparam.malloced = 0;
12472 shellparam.nparam = argc;
12473 shellparam.p = argv;
12476 /* This aborts if file can't be opened, which is POSIXly correct.
12477 * bash returns exitcode 1 instead.
12479 setinputfile(fullname, INPUT_PUSH_FILE);
12480 commandname = fullname;
12481 status = cmdloop(0);
12485 freeparam(&shellparam);
12486 shellparam = saveparam;
12492 static int FAST_FUNC
12493 exitcmd(int argc UNUSED_PARAM, char **argv)
12498 exitstatus = number(argv[1]);
12499 raise_exception(EXEXIT);
12504 * Read a file containing shell functions.
12507 readcmdfile(char *name)
12509 setinputfile(name, INPUT_PUSH_FILE);
12515 /* ============ find_command inplementation */
12518 * Resolve a command name. If you change this routine, you may have to
12519 * change the shellexec routine as well.
12522 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12524 struct tblentry *cmdp;
12531 struct builtincmd *bcmd;
12533 /* If name contains a slash, don't use PATH or hash table */
12534 if (strchr(name, '/') != NULL) {
12535 entry->u.index = -1;
12536 if (act & DO_ABS) {
12537 while (stat(name, &statb) < 0) {
12539 if (errno == EINTR)
12542 entry->cmdtype = CMDUNKNOWN;
12546 entry->cmdtype = CMDNORMAL;
12550 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12552 updatetbl = (path == pathval());
12555 if (strstr(path, "%builtin") != NULL)
12556 act |= DO_ALTBLTIN;
12559 /* If name is in the table, check answer will be ok */
12560 cmdp = cmdlookup(name, 0);
12561 if (cmdp != NULL) {
12564 switch (cmdp->cmdtype) {
12582 } else if (cmdp->rehash == 0)
12583 /* if not invalidated by cd, we're done */
12587 /* If %builtin not in path, check for builtin next */
12588 bcmd = find_builtin(name);
12590 if (IS_BUILTIN_REGULAR(bcmd))
12591 goto builtin_success;
12592 if (act & DO_ALTPATH) {
12593 if (!(act & DO_ALTBLTIN))
12594 goto builtin_success;
12595 } else if (builtinloc <= 0) {
12596 goto builtin_success;
12600 #if ENABLE_FEATURE_SH_STANDALONE
12602 int applet_no = find_applet_by_name(name);
12603 if (applet_no >= 0) {
12604 entry->cmdtype = CMDNORMAL;
12605 entry->u.index = -2 - applet_no;
12611 /* We have to search path. */
12612 prev = -1; /* where to start */
12613 if (cmdp && cmdp->rehash) { /* doing a rehash */
12614 if (cmdp->cmdtype == CMDBUILTIN)
12617 prev = cmdp->param.index;
12623 while ((fullname = path_advance(&path, name)) != NULL) {
12624 stunalloc(fullname);
12625 /* NB: code below will still use fullname
12626 * despite it being "unallocated" */
12629 if (prefix(pathopt, "builtin")) {
12631 goto builtin_success;
12634 if ((act & DO_NOFUNC)
12635 || !prefix(pathopt, "func")
12636 ) { /* ignore unimplemented options */
12640 /* if rehash, don't redo absolute path names */
12641 if (fullname[0] == '/' && idx <= prev) {
12644 TRACE(("searchexec \"%s\": no change\n", name));
12647 while (stat(fullname, &statb) < 0) {
12649 if (errno == EINTR)
12652 if (errno != ENOENT && errno != ENOTDIR)
12656 e = EACCES; /* if we fail, this will be the error */
12657 if (!S_ISREG(statb.st_mode))
12659 if (pathopt) { /* this is a %func directory */
12660 stalloc(strlen(fullname) + 1);
12661 /* NB: stalloc will return space pointed by fullname
12662 * (because we don't have any intervening allocations
12663 * between stunalloc above and this stalloc) */
12664 readcmdfile(fullname);
12665 cmdp = cmdlookup(name, 0);
12666 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12667 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12668 stunalloc(fullname);
12671 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12673 entry->cmdtype = CMDNORMAL;
12674 entry->u.index = idx;
12678 cmdp = cmdlookup(name, 1);
12679 cmdp->cmdtype = CMDNORMAL;
12680 cmdp->param.index = idx;
12685 /* We failed. If there was an entry for this command, delete it */
12686 if (cmdp && updatetbl)
12687 delete_cmd_entry();
12689 ash_msg("%s: %s", name, errmsg(e, "not found"));
12690 entry->cmdtype = CMDUNKNOWN;
12695 entry->cmdtype = CMDBUILTIN;
12696 entry->u.cmd = bcmd;
12700 cmdp = cmdlookup(name, 1);
12701 cmdp->cmdtype = CMDBUILTIN;
12702 cmdp->param.cmd = bcmd;
12706 entry->cmdtype = cmdp->cmdtype;
12707 entry->u = cmdp->param;
12712 * The trap builtin.
12714 static int FAST_FUNC
12715 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12719 int signo, exitcode;
12724 for (signo = 0; signo < NSIG; signo++) {
12725 char *tr = trap_ptr[signo];
12727 /* note: bash adds "SIG", but only if invoked
12728 * as "bash". If called as "sh", or if set -o posix,
12729 * then it prints short signal names.
12730 * We are printing short names: */
12731 out1fmt("trap -- %s %s\n",
12733 get_signame(signo));
12734 /* trap_ptr != trap only if we are in special-cased `trap` code.
12735 * In this case, we will exit very soon, no need to free(). */
12736 /* if (trap_ptr != trap && tp[0]) */
12741 if (trap_ptr != trap) {
12754 signo = get_signum(*ap);
12756 /* Mimic bash message exactly */
12757 ash_msg("%s: invalid signal specification", *ap);
12763 if (LONE_DASH(action))
12766 if (action[0]) /* not NULL and not "" and not "-" */
12767 may_have_traps = 1;
12768 action = ckstrdup(action);
12772 trap[signo] = action;
12783 /* ============ Builtins */
12785 #if ENABLE_ASH_HELP
12786 static int FAST_FUNC
12787 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12793 "Built-in commands:\n"
12794 "------------------\n");
12795 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12796 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12797 builtintab[i].name + 1);
12803 # if ENABLE_FEATURE_SH_STANDALONE
12805 const char *a = applet_names;
12807 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12812 while (*a++ != '\0')
12817 newline_and_flush(stdout);
12818 return EXIT_SUCCESS;
12823 static int FAST_FUNC
12824 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12826 show_history(line_input_state);
12827 return EXIT_SUCCESS;
12832 * The export and readonly commands.
12834 static int FAST_FUNC
12835 exportcmd(int argc UNUSED_PARAM, char **argv)
12845 /* "readonly" in bash accepts, but ignores -n.
12846 * We do the same: it saves a conditional in nextopt's param.
12849 while ((opt = nextopt("np")) != '\0') {
12851 flag_off = VEXPORT;
12854 if (argv[0][0] == 'r') {
12856 flag_off = 0; /* readonly ignores -n */
12858 flag_off = ~flag_off;
12860 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12866 p = strchr(name, '=');
12870 vp = *findvar(hashvar(name), name);
12872 vp->flags = ((vp->flags | flag) & flag_off);
12876 setvar(name, p, (flag & flag_off));
12877 } while ((name = *++aptr) != NULL);
12882 /* No arguments. Show the list of exported or readonly vars.
12885 showvars(argv[0], flag, 0);
12890 * Delete a function if it exists.
12893 unsetfunc(const char *name)
12895 struct tblentry *cmdp;
12897 cmdp = cmdlookup(name, 0);
12898 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12899 delete_cmd_entry();
12903 * The unset builtin command. We unset the function before we unset the
12904 * variable to allow a function to be unset when there is a readonly variable
12905 * with the same name.
12907 static int FAST_FUNC
12908 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12915 while ((i = nextopt("vf")) != 0) {
12919 for (ap = argptr; *ap; ap++) {
12932 static const unsigned char timescmd_str[] ALIGN1 = {
12933 ' ', offsetof(struct tms, tms_utime),
12934 '\n', offsetof(struct tms, tms_stime),
12935 ' ', offsetof(struct tms, tms_cutime),
12936 '\n', offsetof(struct tms, tms_cstime),
12939 static int FAST_FUNC
12940 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12942 unsigned long clk_tck, s, t;
12943 const unsigned char *p;
12946 clk_tck = bb_clk_tck();
12951 t = *(clock_t *)(((char *) &buf) + p[1]);
12954 out1fmt("%lum%lu.%03lus%c",
12956 (t * 1000) / clk_tck,
12964 #if ENABLE_SH_MATH_SUPPORT
12966 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12967 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12969 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12971 static int FAST_FUNC
12972 letcmd(int argc UNUSED_PARAM, char **argv)
12978 ash_msg_and_raise_error("expression expected");
12980 i = ash_arith(*argv);
12988 * The read builtin. Options:
12989 * -r Do not interpret '\' specially
12990 * -s Turn off echo (tty only)
12991 * -n NCHARS Read NCHARS max
12992 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12993 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12994 * -u FD Read from given FD instead of fd 0
12995 * This uses unbuffered input, which may be avoidable in some cases.
12996 * TODO: bash also has:
12997 * -a ARRAY Read into array[0],[1],etc
12998 * -d DELIM End on DELIM char, not newline
12999 * -e Use line editing (tty only)
13001 static int FAST_FUNC
13002 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13004 char *opt_n = NULL;
13005 char *opt_p = NULL;
13006 char *opt_t = NULL;
13007 char *opt_u = NULL;
13008 int read_flags = 0;
13012 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13021 read_flags |= BUILTIN_READ_SILENT;
13027 read_flags |= BUILTIN_READ_RAW;
13037 /* "read -s" needs to save/restore termios, can't allow ^C
13038 * to jump out of it.
13041 r = shell_builtin_read(setvar0,
13043 bltinlookup("IFS"), /* can be NULL */
13052 if ((uintptr_t)r > 1)
13053 ash_msg_and_raise_error(r);
13055 return (uintptr_t)r;
13058 static int FAST_FUNC
13059 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13061 static const char permuser[3] ALIGN1 = "ogu";
13064 int symbolic_mode = 0;
13066 while (nextopt("S") != '\0') {
13075 if (*argptr == NULL) {
13076 if (symbolic_mode) {
13077 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13084 *p++ = permuser[i];
13086 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13087 if (!(mask & 0400)) *p++ = 'r';
13088 if (!(mask & 0200)) *p++ = 'w';
13089 if (!(mask & 0100)) *p++ = 'x';
13097 out1fmt("%04o\n", mask);
13100 char *modestr = *argptr;
13101 /* numeric umasks are taken as-is */
13102 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13103 if (!isdigit(modestr[0]))
13105 mask = bb_parse_mode(modestr, mask);
13106 if ((unsigned)mask > 0777) {
13107 ash_msg_and_raise_error("illegal mode: %s", modestr);
13109 if (!isdigit(modestr[0]))
13116 static int FAST_FUNC
13117 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13119 return shell_builtin_ulimit(argv);
13122 /* ============ main() and helpers */
13125 * Called to exit the shell.
13134 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13135 save_history(line_input_state);
13137 status = exitstatus;
13138 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13139 if (setjmp(loc.loc)) {
13140 if (exception_type == EXEXIT)
13141 status = exitstatus;
13144 exception_handler = &loc;
13150 /*free(p); - we'll exit soon */
13153 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13154 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13157 flush_stdout_stderr();
13165 /* we will never free this */
13166 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13168 signal(SIGCHLD, SIG_DFL);
13169 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13170 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13172 signal(SIGHUP, SIG_DFL);
13177 struct stat st1, st2;
13180 for (envp = environ; envp && *envp; envp++) {
13181 p = endofname(*envp);
13182 if (p != *envp && *p == '=') {
13183 setvareq(*envp, VEXPORT|VTEXTFIXED);
13187 setvareq((char*)defoptindvar, VTEXTFIXED);
13189 setvar0("PPID", utoa(getppid()));
13190 #if ENABLE_ASH_BASH_COMPAT
13191 p = lookupvar("SHLVL");
13192 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13193 if (!lookupvar("HOSTNAME")) {
13194 struct utsname uts;
13196 setvar0("HOSTNAME", uts.nodename);
13199 p = lookupvar("PWD");
13201 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13202 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13212 //usage:#define ash_trivial_usage
13213 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13214 //usage:#define ash_full_usage "\n\n"
13215 //usage: "Unix shell interpreter"
13217 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13218 //usage:# define sh_trivial_usage ash_trivial_usage
13219 //usage:# define sh_full_usage ash_full_usage
13221 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13222 //usage:# define bash_trivial_usage ash_trivial_usage
13223 //usage:# define bash_full_usage ash_full_usage
13227 * Process the shell command line arguments.
13230 procargs(char **argv)
13233 const char *xminusc;
13238 /* if (xargv[0]) - mmm, this is always true! */
13240 for (i = 0; i < NOPTS; i++)
13243 if (options(/*cmdline:*/ 1)) {
13244 /* it already printed err message */
13245 raise_exception(EXERROR);
13249 if (*xargv == NULL) {
13251 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13254 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13258 for (i = 0; i < NOPTS; i++)
13259 if (optlist[i] == 2)
13264 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13269 } else if (!sflag) {
13270 setinputfile(*xargv, 0);
13273 commandname = arg0;
13276 shellparam.p = xargv;
13277 #if ENABLE_ASH_GETOPTS
13278 shellparam.optind = 1;
13279 shellparam.optoff = -1;
13281 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13283 shellparam.nparam++;
13290 * Read /etc/profile, ~/.profile, $ENV.
13293 read_profile(const char *name)
13295 name = expandstr(name);
13296 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13303 * This routine is called when an error or an interrupt occurs in an
13304 * interactive shell and control is returned to the main command loop.
13305 * (In dash, this function is auto-generated by build machinery).
13314 /* from expand.c: */
13317 /* from input.c: */
13318 g_parsefile->left_in_buffer = 0;
13319 g_parsefile->left_in_line = 0; /* clear input buffer */
13322 /* from redir.c: */
13324 popredir(/*drop:*/ 0, /*restore:*/ 0);
13328 static short profile_buf[16384];
13329 extern int etext();
13333 * Main routine. We initialize things, parse the arguments, execute
13334 * profiles if we're a login shell, and then call cmdloop to execute
13335 * commands. The setjmp call sets up the location to jump to when an
13336 * exception occurs. When an exception occurs the variable "state"
13337 * is used to figure out how far we had gotten.
13339 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13340 int ash_main(int argc UNUSED_PARAM, char **argv)
13342 volatile smallint state;
13343 struct jmploc jmploc;
13344 struct stackmark smark;
13346 /* Initialize global data */
13350 #if ENABLE_ASH_ALIAS
13356 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13359 #if ENABLE_FEATURE_EDITING
13360 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13363 if (setjmp(jmploc.loc)) {
13369 e = exception_type;
13371 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13375 newline_and_flush(stderr);
13378 popstackmark(&smark);
13379 FORCE_INT_ON; /* enable interrupts */
13388 exception_handler = &jmploc;
13391 TRACE(("Shell args: "));
13392 trace_puts_args(argv);
13394 rootpid = getpid();
13397 setstackmark(&smark);
13400 if (argv[0] && argv[0][0] == '-')
13406 read_profile("/etc/profile");
13409 hp = lookupvar("HOME");
13411 read_profile("$HOME/.profile");
13417 getuid() == geteuid() && getgid() == getegid() &&
13421 const char *shinit = lookupvar("ENV");
13422 if (shinit != NULL && *shinit != '\0')
13423 read_profile(shinit);
13425 popstackmark(&smark);
13429 /* evalstring pushes parsefile stack.
13430 * Ensure we don't falsely claim that 0 (stdin)
13431 * is one of stacked source fds.
13432 * Testcase: ash -c 'exec 1>&0' must not complain. */
13433 // if (!sflag) g_parsefile->pf_fd = -1;
13434 // ^^ not necessary since now we special-case fd 0
13435 // in is_hidden_fd() to not be considered "hidden fd"
13436 evalstring(minusc, 0);
13439 if (sflag || minusc == NULL) {
13440 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13442 const char *hp = lookupvar("HISTFILE");
13444 hp = lookupvar("HOME");
13446 hp = concat_path_file(hp, ".ash_history");
13447 setvar0("HISTFILE", hp);
13449 hp = lookupvar("HISTFILE");
13453 line_input_state->hist_file = hp;
13454 # if ENABLE_FEATURE_SH_HISTFILESIZE
13455 hp = lookupvar("HISTFILESIZE");
13456 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13460 state4: /* XXX ??? - why isn't this before the "if" statement */
13468 extern void _mcleanup(void);
13472 TRACE(("End of main reached\n"));
13479 * Copyright (c) 1989, 1991, 1993, 1994
13480 * The Regents of the University of California. All rights reserved.
13482 * This code is derived from software contributed to Berkeley by
13483 * Kenneth Almquist.
13485 * Redistribution and use in source and binary forms, with or without
13486 * modification, are permitted provided that the following conditions
13488 * 1. Redistributions of source code must retain the above copyright
13489 * notice, this list of conditions and the following disclaimer.
13490 * 2. Redistributions in binary form must reproduce the above copyright
13491 * notice, this list of conditions and the following disclaimer in the
13492 * documentation and/or other materials provided with the distribution.
13493 * 3. Neither the name of the University nor the names of its contributors
13494 * may be used to endorse or promote products derived from this software
13495 * without specific prior written permission.
13497 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13498 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13499 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13500 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13501 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13502 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13503 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13504 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13505 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13506 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF