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)
1497 len = SHELL_ALIGN(len);
1499 g_stacknleft -= len;
1503 pushstackmark(struct stackmark *mark, size_t len)
1505 mark->stackp = g_stackp;
1506 mark->stacknxt = g_stacknxt;
1507 mark->stacknleft = g_stacknleft;
1508 grabstackblock(len);
1512 setstackmark(struct stackmark *mark)
1514 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1518 popstackmark(struct stackmark *mark)
1520 struct stack_block *sp;
1526 while (g_stackp != mark->stackp) {
1528 g_stackp = sp->prev;
1531 g_stacknxt = mark->stacknxt;
1532 g_stacknleft = mark->stacknleft;
1533 sstrend = mark->stacknxt + mark->stacknleft;
1538 * When the parser reads in a string, it wants to stick the string on the
1539 * stack and only adjust the stack pointer when it knows how big the
1540 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1541 * of space on top of the stack and stackblocklen returns the length of
1542 * this block. Growstackblock will grow this space by at least one byte,
1543 * possibly moving it (like realloc). Grabstackblock actually allocates the
1544 * part of the block that has been used.
1547 growstackblock(void)
1551 newlen = g_stacknleft * 2;
1552 if (newlen < g_stacknleft)
1553 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1557 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1558 struct stack_block *sp;
1559 struct stack_block *prevstackp;
1564 prevstackp = sp->prev;
1565 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1566 sp = ckrealloc(sp, grosslen);
1567 sp->prev = prevstackp;
1569 g_stacknxt = sp->space;
1570 g_stacknleft = newlen;
1571 sstrend = sp->space + newlen;
1574 char *oldspace = g_stacknxt;
1575 size_t oldlen = g_stacknleft;
1576 char *p = stalloc(newlen);
1578 /* free the space we just allocated */
1579 g_stacknxt = memcpy(p, oldspace, oldlen);
1580 g_stacknleft += newlen;
1585 * The following routines are somewhat easier to use than the above.
1586 * The user declares a variable of type STACKSTR, which may be declared
1587 * to be a register. The macro STARTSTACKSTR initializes things. Then
1588 * the user uses the macro STPUTC to add characters to the string. In
1589 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1590 * grown as necessary. When the user is done, she can just leave the
1591 * string there and refer to it using stackblock(). Or she can allocate
1592 * the space for it using grabstackstr(). If it is necessary to allow
1593 * someone else to use the stack temporarily and then continue to grow
1594 * the string, the user should use grabstack to allocate the space, and
1595 * then call ungrabstr(p) to return to the previous mode of operation.
1597 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1598 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1599 * is space for at least one character.
1604 size_t len = stackblocksize();
1606 return (char *)stackblock() + len;
1610 * Called from CHECKSTRSPACE.
1613 makestrspace(size_t newlen, char *p)
1615 size_t len = p - g_stacknxt;
1621 size = stackblocksize();
1623 if (nleft >= newlen)
1627 return (char *)stackblock() + len;
1631 stack_nputstr(const char *s, size_t n, char *p)
1633 p = makestrspace(n, p);
1634 p = (char *)memcpy(p, s, n) + n;
1639 stack_putstr(const char *s, char *p)
1641 return stack_nputstr(s, strlen(s), p);
1645 _STPUTC(int c, char *p)
1653 #define STARTSTACKSTR(p) ((p) = stackblock())
1654 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1655 #define CHECKSTRSPACE(n, p) do { \
1658 size_t m = sstrend - q; \
1660 (p) = makestrspace(l, q); \
1662 #define USTPUTC(c, p) (*(p)++ = (c))
1663 #define STACKSTRNUL(p) do { \
1664 if ((p) == sstrend) \
1665 (p) = growstackstr(); \
1668 #define STUNPUTC(p) (--(p))
1669 #define STTOPC(p) ((p)[-1])
1670 #define STADJUST(amount, p) ((p) += (amount))
1672 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1673 #define ungrabstackstr(s, p) stunalloc(s)
1674 #define stackstrend() ((void *)sstrend)
1677 /* ============ String helpers */
1680 * prefix -- see if pfx is a prefix of string.
1683 prefix(const char *string, const char *pfx)
1686 if (*pfx++ != *string++)
1689 return (char *) string;
1693 * Check for a valid number. This should be elsewhere.
1696 is_number(const char *p)
1701 } while (*++p != '\0');
1706 * Convert a string of digits to an integer, printing an error message on
1710 number(const char *s)
1713 ash_msg_and_raise_error(msg_illnum, s);
1718 * Produce a possibly single quoted string suitable as input to the shell.
1719 * The return string is allocated on the stack.
1722 single_quote(const char *s)
1732 len = strchrnul(s, '\'') - s;
1734 q = p = makestrspace(len + 3, p);
1737 q = (char *)memcpy(q, s, len) + len;
1746 do len++; while (*++s == '\'');
1748 q = p = makestrspace(len + 3, p);
1751 q = (char *)memcpy(q, s - len, len) + len;
1759 return stackblock();
1763 /* ============ nextopt */
1765 static char **argptr; /* argument list for builtin commands */
1766 static char *optionarg; /* set by nextopt (like getopt) */
1767 static char *optptr; /* used by nextopt */
1770 * XXX - should get rid of. Have all builtins use getopt(3).
1771 * The library getopt must have the BSD extension static variable
1772 * "optreset", otherwise it can't be used within the shell safely.
1774 * Standard option processing (a la getopt) for builtin routines.
1775 * The only argument that is passed to nextopt is the option string;
1776 * the other arguments are unnecessary. It returns the character,
1777 * or '\0' on end of input.
1780 nextopt(const char *optstring)
1787 if (p == NULL || *p == '\0') {
1788 /* We ate entire "-param", take next one */
1794 if (*++p == '\0') /* just "-" ? */
1797 if (LONE_DASH(p)) /* "--" ? */
1799 /* p => next "-param" */
1801 /* p => some option char in the middle of a "-param" */
1803 for (q = optstring; *q != c;) {
1805 ash_msg_and_raise_error("illegal option -%c", c);
1813 ash_msg_and_raise_error("no arg for -%c option", c);
1823 /* ============ Shell variables */
1826 * The parsefile structure pointed to by the global variable parsefile
1827 * contains information about the current file being read.
1830 int nparam; /* # of positional parameters (without $0) */
1831 #if ENABLE_ASH_GETOPTS
1832 int optind; /* next parameter to be processed by getopts */
1833 int optoff; /* used by getopts */
1835 unsigned char malloced; /* if parameter list dynamically allocated */
1836 char **p; /* parameter list */
1840 * Free the list of positional parameters.
1843 freeparam(volatile struct shparam *param)
1845 if (param->malloced) {
1847 ap = ap1 = param->p;
1854 #if ENABLE_ASH_GETOPTS
1855 static void FAST_FUNC getoptsreset(const char *value);
1859 struct var *next; /* next entry in hash list */
1860 int flags; /* flags are defined above */
1861 const char *var_text; /* name=value */
1862 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1863 /* the variable gets set/unset */
1867 struct localvar *next; /* next local variable in list */
1868 struct var *vp; /* the variable that was made local */
1869 int flags; /* saved flags */
1870 const char *text; /* saved text */
1874 #define VEXPORT 0x01 /* variable is exported */
1875 #define VREADONLY 0x02 /* variable cannot be modified */
1876 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1877 #define VTEXTFIXED 0x08 /* text is statically allocated */
1878 #define VSTACK 0x10 /* text is allocated on the stack */
1879 #define VUNSET 0x20 /* the variable is not set */
1880 #define VNOFUNC 0x40 /* don't call the callback function */
1881 #define VNOSET 0x80 /* do not set variable - just readonly test */
1882 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1883 #if ENABLE_ASH_RANDOM_SUPPORT
1884 # define VDYNAMIC 0x200 /* dynamic variable */
1890 /* Need to be before varinit_data[] */
1891 #if ENABLE_LOCALE_SUPPORT
1892 static void FAST_FUNC
1893 change_lc_all(const char *value)
1895 if (value && *value != '\0')
1896 setlocale(LC_ALL, value);
1898 static void FAST_FUNC
1899 change_lc_ctype(const char *value)
1901 if (value && *value != '\0')
1902 setlocale(LC_CTYPE, value);
1906 static void chkmail(void);
1907 static void changemail(const char *var_value) FAST_FUNC;
1909 # define chkmail() ((void)0)
1911 static void changepath(const char *) FAST_FUNC;
1912 #if ENABLE_ASH_RANDOM_SUPPORT
1913 static void change_random(const char *) FAST_FUNC;
1916 static const struct {
1918 const char *var_text;
1919 void (*var_func)(const char *) FAST_FUNC;
1920 } varinit_data[] = {
1922 * Note: VEXPORT would not work correctly here for NOFORK applets:
1923 * some environment strings may be constant.
1925 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1927 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1928 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1930 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1931 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1932 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1933 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1934 #if ENABLE_ASH_GETOPTS
1935 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1937 #if ENABLE_ASH_RANDOM_SUPPORT
1938 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1940 #if ENABLE_LOCALE_SUPPORT
1941 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1942 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1944 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1945 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1951 struct globals_var {
1952 struct shparam shellparam; /* $@ current positional parameters */
1953 struct redirtab *redirlist;
1954 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1955 struct var *vartab[VTABSIZE];
1956 struct var varinit[ARRAY_SIZE(varinit_data)];
1958 extern struct globals_var *const ash_ptr_to_globals_var;
1959 #define G_var (*ash_ptr_to_globals_var)
1960 #define shellparam (G_var.shellparam )
1961 //#define redirlist (G_var.redirlist )
1962 #define preverrout_fd (G_var.preverrout_fd)
1963 #define vartab (G_var.vartab )
1964 #define varinit (G_var.varinit )
1965 #define INIT_G_var() do { \
1967 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1969 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1970 varinit[i].flags = varinit_data[i].flags; \
1971 varinit[i].var_text = varinit_data[i].var_text; \
1972 varinit[i].var_func = varinit_data[i].var_func; \
1976 #define vifs varinit[0]
1978 # define vmail (&vifs)[1]
1979 # define vmpath (&vmail)[1]
1980 # define vpath (&vmpath)[1]
1982 # define vpath (&vifs)[1]
1984 #define vps1 (&vpath)[1]
1985 #define vps2 (&vps1)[1]
1986 #define vps4 (&vps2)[1]
1987 #if ENABLE_ASH_GETOPTS
1988 # define voptind (&vps4)[1]
1989 # if ENABLE_ASH_RANDOM_SUPPORT
1990 # define vrandom (&voptind)[1]
1993 # if ENABLE_ASH_RANDOM_SUPPORT
1994 # define vrandom (&vps4)[1]
1999 * The following macros access the values of the above variables.
2000 * They have to skip over the name. They return the null string
2001 * for unset variables.
2003 #define ifsval() (vifs.var_text + 4)
2004 #define ifsset() ((vifs.flags & VUNSET) == 0)
2006 # define mailval() (vmail.var_text + 5)
2007 # define mpathval() (vmpath.var_text + 9)
2008 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2010 #define pathval() (vpath.var_text + 5)
2011 #define ps1val() (vps1.var_text + 4)
2012 #define ps2val() (vps2.var_text + 4)
2013 #define ps4val() (vps4.var_text + 4)
2014 #if ENABLE_ASH_GETOPTS
2015 # define optindval() (voptind.var_text + 7)
2018 #if ENABLE_ASH_GETOPTS
2019 static void FAST_FUNC
2020 getoptsreset(const char *value)
2022 shellparam.optind = number(value);
2023 shellparam.optoff = -1;
2028 * Compares two strings up to the first = or '\0'. The first
2029 * string must be terminated by '='; the second may be terminated by
2030 * either '=' or '\0'.
2033 varcmp(const char *p, const char *q)
2037 while ((c = *p) == (d = *q)) {
2038 if (c == '\0' || c == '=')
2052 * Find the appropriate entry in the hash table from the name.
2054 static struct var **
2055 hashvar(const char *p)
2059 hashval = ((unsigned char) *p) << 4;
2060 while (*p && *p != '=')
2061 hashval += (unsigned char) *p++;
2062 return &vartab[hashval % VTABSIZE];
2066 vpcmp(const void *a, const void *b)
2068 return varcmp(*(const char **)a, *(const char **)b);
2072 * This routine initializes the builtin variables.
2082 * PS1 depends on uid
2084 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2085 vps1.var_text = "PS1=\\w \\$ ";
2088 vps1.var_text = "PS1=# ";
2091 end = vp + ARRAY_SIZE(varinit);
2093 vpp = hashvar(vp->var_text);
2096 } while (++vp < end);
2099 static struct var **
2100 findvar(struct var **vpp, const char *name)
2102 for (; *vpp; vpp = &(*vpp)->next) {
2103 if (varcmp((*vpp)->var_text, name) == 0) {
2111 * Find the value of a variable. Returns NULL if not set.
2113 static const char* FAST_FUNC
2114 lookupvar(const char *name)
2118 v = *findvar(hashvar(name), name);
2120 #if ENABLE_ASH_RANDOM_SUPPORT
2122 * Dynamic variables are implemented roughly the same way they are
2123 * in bash. Namely, they're "special" so long as they aren't unset.
2124 * As soon as they're unset, they're no longer dynamic, and dynamic
2125 * lookup will no longer happen at that point. -- PFM.
2127 if (v->flags & VDYNAMIC)
2130 if (!(v->flags & VUNSET))
2131 return var_end(v->var_text);
2137 reinit_unicode_for_ash(void)
2139 /* Unicode support should be activated even if LANG is set
2140 * _during_ shell execution, not only if it was set when
2141 * shell was started. Therefore, re-check LANG every time:
2143 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2144 || ENABLE_UNICODE_USING_LOCALE
2146 const char *s = lookupvar("LC_ALL");
2147 if (!s) s = lookupvar("LC_CTYPE");
2148 if (!s) s = lookupvar("LANG");
2154 * Search the environment of a builtin command.
2157 bltinlookup(const char *name)
2161 for (sp = cmdenviron; sp; sp = sp->next) {
2162 if (varcmp(sp->text, name) == 0)
2163 return var_end(sp->text);
2165 return lookupvar(name);
2169 * Same as setvar except that the variable and value are passed in
2170 * the first argument as name=value. Since the first argument will
2171 * be actually stored in the table, it should not be a string that
2173 * Called with interrupts off.
2176 setvareq(char *s, int flags)
2178 struct var *vp, **vpp;
2181 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2182 vp = *findvar(vpp, s);
2184 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2187 if (flags & VNOSAVE)
2190 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2196 if (vp->var_func && !(flags & VNOFUNC))
2197 vp->var_func(var_end(s));
2199 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2200 free((char*)vp->var_text);
2202 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2204 /* variable s is not found */
2207 vp = ckzalloc(sizeof(*vp));
2209 /*vp->func = NULL; - ckzalloc did it */
2212 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2219 * Set the value of a variable. The flags argument is ored with the
2220 * flags of the variable. If val is NULL, the variable is unset.
2223 setvar(const char *name, const char *val, int flags)
2231 q = endofname(name);
2232 p = strchrnul(q, '=');
2234 if (!namelen || p != q)
2235 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2240 vallen = strlen(val);
2244 nameeq = ckmalloc(namelen + vallen + 2);
2245 p = memcpy(nameeq, name, namelen) + namelen;
2248 p = memcpy(p, val, vallen) + vallen;
2251 setvareq(nameeq, flags | VNOSAVE);
2255 static void FAST_FUNC
2256 setvar0(const char *name, const char *val)
2258 setvar(name, val, 0);
2261 #if ENABLE_ASH_GETOPTS
2263 * Safe version of setvar, returns 1 on success 0 on failure.
2266 setvarsafe(const char *name, const char *val, int flags)
2269 volatile int saveint;
2270 struct jmploc *volatile savehandler = exception_handler;
2271 struct jmploc jmploc;
2274 if (setjmp(jmploc.loc))
2277 exception_handler = &jmploc;
2278 setvar(name, val, flags);
2281 exception_handler = savehandler;
2282 RESTORE_INT(saveint);
2288 * Unset the specified variable.
2291 unsetvar(const char *s)
2297 vpp = findvar(hashvar(s), s);
2301 int flags = vp->flags;
2304 if (flags & VREADONLY)
2306 #if ENABLE_ASH_RANDOM_SUPPORT
2307 vp->flags &= ~VDYNAMIC;
2311 if ((flags & VSTRFIXED) == 0) {
2313 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2314 free((char*)vp->var_text);
2320 vp->flags &= ~VEXPORT;
2330 * Process a linked list of variable assignments.
2333 listsetvar(struct strlist *list_set_var, int flags)
2335 struct strlist *lp = list_set_var;
2341 setvareq(lp->text, flags);
2348 * Generate a list of variables satisfying the given conditions.
2351 listvars(int on, int off, char ***end)
2362 for (vp = *vpp; vp; vp = vp->next) {
2363 if ((vp->flags & mask) == on) {
2364 if (ep == stackstrend())
2365 ep = growstackstr();
2366 *ep++ = (char*)vp->var_text;
2369 } while (++vpp < vartab + VTABSIZE);
2370 if (ep == stackstrend())
2371 ep = growstackstr();
2375 return grabstackstr(ep);
2379 /* ============ Path search helper
2381 * The variable path (passed by reference) should be set to the start
2382 * of the path before the first call; path_advance will update
2383 * this value as it proceeds. Successive calls to path_advance will return
2384 * the possible path expansions in sequence. If an option (indicated by
2385 * a percent sign) appears in the path entry then the global variable
2386 * pathopt will be set to point to it; otherwise pathopt will be set to
2389 static const char *pathopt; /* set by path_advance */
2392 path_advance(const char **path, const char *name)
2402 for (p = start; *p && *p != ':' && *p != '%'; p++)
2404 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2405 while (stackblocksize() < len)
2409 memcpy(q, start, p - start);
2417 while (*p && *p != ':')
2424 return stalloc(len);
2428 /* ============ Prompt */
2430 static smallint doprompt; /* if set, prompt the user */
2431 static smallint needprompt; /* true if interactive and at start of line */
2433 #if ENABLE_FEATURE_EDITING
2434 static line_input_t *line_input_state;
2435 static const char *cmdedit_prompt;
2437 putprompt(const char *s)
2439 if (ENABLE_ASH_EXPAND_PRMT) {
2440 free((char*)cmdedit_prompt);
2441 cmdedit_prompt = ckstrdup(s);
2448 putprompt(const char *s)
2454 #if ENABLE_ASH_EXPAND_PRMT
2455 /* expandstr() needs parsing machinery, so it is far away ahead... */
2456 static const char *expandstr(const char *ps);
2458 #define expandstr(s) s
2462 setprompt_if(smallint do_set, int whichprompt)
2465 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2472 switch (whichprompt) {
2482 #if ENABLE_ASH_EXPAND_PRMT
2483 pushstackmark(&smark, stackblocksize());
2485 putprompt(expandstr(prompt));
2486 #if ENABLE_ASH_EXPAND_PRMT
2487 popstackmark(&smark);
2492 /* ============ The cd and pwd commands */
2494 #define CD_PHYSICAL 1
2504 while ((i = nextopt("LP")) != '\0') {
2506 flags ^= CD_PHYSICAL;
2515 * Update curdir (the name of the current directory) in response to a
2519 updatepwd(const char *dir)
2526 cdcomppath = sstrdup(dir);
2529 if (curdir == nullstr)
2531 new = stack_putstr(curdir, new);
2533 new = makestrspace(strlen(dir) + 2, new);
2534 lim = (char *)stackblock() + 1;
2538 if (new > lim && *lim == '/')
2543 if (dir[1] == '/' && dir[2] != '/') {
2549 p = strtok(cdcomppath, "/");
2553 if (p[1] == '.' && p[2] == '\0') {
2565 new = stack_putstr(p, new);
2568 p = strtok(NULL, "/");
2573 return stackblock();
2577 * Find out what the current directory is. If we already know the current
2578 * directory, this routine returns immediately.
2583 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2584 return dir ? dir : nullstr;
2588 setpwd(const char *val, int setold)
2592 oldcur = dir = curdir;
2595 setvar("OLDPWD", oldcur, VEXPORT);
2598 if (physdir != nullstr) {
2599 if (physdir != oldcur)
2603 if (oldcur == val || !val) {
2609 dir = ckstrdup(val);
2610 if (oldcur != dir && oldcur != nullstr) {
2615 setvar("PWD", dir, VEXPORT);
2618 static void hashcd(void);
2621 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2622 * know that the current directory has changed.
2625 docd(const char *dest, int flags)
2627 const char *dir = NULL;
2630 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2633 if (!(flags & CD_PHYSICAL)) {
2634 dir = updatepwd(dest);
2648 static int FAST_FUNC
2649 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2661 dest = bltinlookup("HOME");
2662 else if (LONE_DASH(dest)) {
2663 dest = bltinlookup("OLDPWD");
2685 path = bltinlookup("CDPATH");
2694 p = path_advance(&path, dest);
2695 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2699 if (!docd(p, flags))
2704 ash_msg_and_raise_error("can't cd to %s", dest);
2707 if (flags & CD_PRINT)
2708 out1fmt("%s\n", curdir);
2712 static int FAST_FUNC
2713 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2716 const char *dir = curdir;
2720 if (physdir == nullstr)
2724 out1fmt("%s\n", dir);
2729 /* ============ ... */
2732 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2734 /* Syntax classes */
2735 #define CWORD 0 /* character is nothing special */
2736 #define CNL 1 /* newline character */
2737 #define CBACK 2 /* a backslash character */
2738 #define CSQUOTE 3 /* single quote */
2739 #define CDQUOTE 4 /* double quote */
2740 #define CENDQUOTE 5 /* a terminating quote */
2741 #define CBQUOTE 6 /* backwards single quote */
2742 #define CVAR 7 /* a dollar sign */
2743 #define CENDVAR 8 /* a '}' character */
2744 #define CLP 9 /* a left paren in arithmetic */
2745 #define CRP 10 /* a right paren in arithmetic */
2746 #define CENDFILE 11 /* end of file */
2747 #define CCTL 12 /* like CWORD, except it must be escaped */
2748 #define CSPCL 13 /* these terminate a word */
2749 #define CIGN 14 /* character should be ignored */
2752 #if ENABLE_ASH_ALIAS
2756 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2758 #if ENABLE_SH_MATH_SUPPORT
2759 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2761 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2763 static const uint16_t S_I_T[] ALIGN2 = {
2764 #if ENABLE_ASH_ALIAS
2765 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2767 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2768 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2769 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2770 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2771 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2772 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2773 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2774 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2775 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2776 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2777 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2778 #if !USE_SIT_FUNCTION
2779 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2780 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2781 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2785 /* Constants below must match table above */
2787 #if ENABLE_ASH_ALIAS
2788 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2790 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2791 CNL_CNL_CNL_CNL , /* 2 */
2792 CWORD_CCTL_CCTL_CWORD , /* 3 */
2793 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2794 CVAR_CVAR_CWORD_CVAR , /* 5 */
2795 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2796 CSPCL_CWORD_CWORD_CLP , /* 7 */
2797 CSPCL_CWORD_CWORD_CRP , /* 8 */
2798 CBACK_CBACK_CCTL_CBACK , /* 9 */
2799 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2800 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2801 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2802 CWORD_CWORD_CWORD_CWORD , /* 13 */
2803 CCTL_CCTL_CCTL_CCTL , /* 14 */
2806 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2807 * caller must ensure proper cast on it if c is *char_ptr!
2809 /* Values for syntax param */
2810 #define BASESYNTAX 0 /* not in quotes */
2811 #define DQSYNTAX 1 /* in double quotes */
2812 #define SQSYNTAX 2 /* in single quotes */
2813 #define ARISYNTAX 3 /* in arithmetic */
2814 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2816 #if USE_SIT_FUNCTION
2819 SIT(int c, int syntax)
2821 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2822 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2824 * This causes '/' to be prepended with CTLESC in dquoted string,
2825 * making "./file"* treated incorrectly because we feed
2826 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2827 * The "homegrown" glob implementation is okay with that,
2828 * but glibc one isn't. With '/' always treated as CWORD,
2831 # if ENABLE_ASH_ALIAS
2832 static const uint8_t syntax_index_table[] ALIGN1 = {
2833 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2834 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2835 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2839 static const uint8_t syntax_index_table[] ALIGN1 = {
2840 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2841 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2842 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2851 # if ENABLE_ASH_ALIAS
2857 /* Cast is purely for paranoia here,
2858 * just in case someone passed signed char to us */
2859 if ((unsigned char)c >= CTL_FIRST
2860 && (unsigned char)c <= CTL_LAST
2864 s = strchrnul(spec_symbls, c);
2867 indx = syntax_index_table[s - spec_symbls];
2869 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2872 #else /* !USE_SIT_FUNCTION */
2874 static const uint8_t syntax_index_table[] ALIGN1 = {
2875 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2876 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2886 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2887 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2911 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2913 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2915 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2916 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2917 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2918 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2919 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2921 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2922 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2923 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2924 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2937 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2938 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2940 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2941 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2969 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2970 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2971 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2974 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3002 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3003 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3004 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3005 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3007 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3008 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3009 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3010 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3011 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3012 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3013 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3014 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3133 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3134 # if ENABLE_ASH_ALIAS
3135 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3139 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3141 #endif /* !USE_SIT_FUNCTION */
3144 /* ============ Alias handling */
3146 #if ENABLE_ASH_ALIAS
3148 #define ALIASINUSE 1
3159 static struct alias **atab; // [ATABSIZE];
3160 #define INIT_G_alias() do { \
3161 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3165 static struct alias **
3166 __lookupalias(const char *name)
3168 unsigned int hashval;
3175 ch = (unsigned char)*p;
3179 ch = (unsigned char)*++p;
3181 app = &atab[hashval % ATABSIZE];
3183 for (; *app; app = &(*app)->next) {
3184 if (strcmp(name, (*app)->name) == 0) {
3192 static struct alias *
3193 lookupalias(const char *name, int check)
3195 struct alias *ap = *__lookupalias(name);
3197 if (check && ap && (ap->flag & ALIASINUSE))
3202 static struct alias *
3203 freealias(struct alias *ap)
3207 if (ap->flag & ALIASINUSE) {
3208 ap->flag |= ALIASDEAD;
3220 setalias(const char *name, const char *val)
3222 struct alias *ap, **app;
3224 app = __lookupalias(name);
3228 if (!(ap->flag & ALIASINUSE)) {
3231 ap->val = ckstrdup(val);
3232 ap->flag &= ~ALIASDEAD;
3235 ap = ckzalloc(sizeof(struct alias));
3236 ap->name = ckstrdup(name);
3237 ap->val = ckstrdup(val);
3238 /*ap->flag = 0; - ckzalloc did it */
3239 /*ap->next = NULL;*/
3246 unalias(const char *name)
3250 app = __lookupalias(name);
3254 *app = freealias(*app);
3265 struct alias *ap, **app;
3269 for (i = 0; i < ATABSIZE; i++) {
3271 for (ap = *app; ap; ap = *app) {
3272 *app = freealias(*app);
3282 printalias(const struct alias *ap)
3284 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3288 * TODO - sort output
3290 static int FAST_FUNC
3291 aliascmd(int argc UNUSED_PARAM, char **argv)
3300 for (i = 0; i < ATABSIZE; i++) {
3301 for (ap = atab[i]; ap; ap = ap->next) {
3307 while ((n = *++argv) != NULL) {
3308 v = strchr(n+1, '=');
3309 if (v == NULL) { /* n+1: funny ksh stuff */
3310 ap = *__lookupalias(n);
3312 fprintf(stderr, "%s: %s not found\n", "alias", n);
3325 static int FAST_FUNC
3326 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3330 while ((i = nextopt("a")) != '\0') {
3336 for (i = 0; *argptr; argptr++) {
3337 if (unalias(*argptr)) {
3338 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3346 #endif /* ASH_ALIAS */
3349 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3352 #define FORK_NOJOB 2
3354 /* mode flags for showjob(s) */
3355 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3356 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3357 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3358 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3361 * A job structure contains information about a job. A job is either a
3362 * single process or a set of processes contained in a pipeline. In the
3363 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3367 pid_t ps_pid; /* process id */
3368 int ps_status; /* last process status from wait() */
3369 char *ps_cmd; /* text of command being run */
3373 struct procstat ps0; /* status of process */
3374 struct procstat *ps; /* status or processes when more than one */
3376 int stopstatus; /* status of a stopped job */
3379 nprocs: 16, /* number of processes */
3381 #define JOBRUNNING 0 /* at least one proc running */
3382 #define JOBSTOPPED 1 /* all procs are stopped */
3383 #define JOBDONE 2 /* all procs are completed */
3385 sigint: 1, /* job was killed by SIGINT */
3386 jobctl: 1, /* job running under job control */
3388 waited: 1, /* true if this entry has been waited for */
3389 used: 1, /* true if this entry is in used */
3390 changed: 1; /* true if status has changed */
3391 struct job *prev_job; /* previous job */
3394 static struct job *makejob(/*union node *,*/ int);
3395 static int forkshell(struct job *, union node *, int);
3396 static int waitforjob(struct job *);
3399 enum { doing_jobctl = 0 };
3400 #define setjobctl(on) do {} while (0)
3402 static smallint doing_jobctl; //references:8
3403 static void setjobctl(int);
3410 ignoresig(int signo)
3412 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3413 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3414 /* No, need to do it */
3415 signal(signo, SIG_IGN);
3417 sigmode[signo - 1] = S_HARD_IGN;
3421 * Only one usage site - in setsignal()
3424 signal_handler(int signo)
3426 gotsig[signo - 1] = 1;
3428 if (signo == SIGINT && !trap[SIGINT]) {
3429 if (!suppress_int) {
3431 raise_interrupt(); /* does not return */
3435 pending_sig = signo;
3440 * Set the signal handler for the specified signal. The routine figures
3441 * out what it should be set to.
3444 setsignal(int signo)
3447 char cur_act, new_act;
3448 struct sigaction act;
3452 if (t != NULL) { /* trap for this sig is set */
3454 if (t[0] == '\0') /* trap is "": ignore this sig */
3458 if (rootshell && new_act == S_DFL) {
3461 if (iflag || minusc || sflag == 0)
3470 * "In all cases, bash ignores SIGQUIT. Non-builtin
3471 * commands run by bash have signal handlers
3472 * set to the values inherited by the shell
3473 * from its parent". */
3489 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3490 //whereas we have to restore it to what shell got on entry
3491 //from the parent. See comment above
3493 t = &sigmode[signo - 1];
3496 /* current setting is not yet known */
3497 if (sigaction(signo, NULL, &act)) {
3498 /* pretend it worked; maybe we should give a warning,
3499 * but other shells don't. We don't alter sigmode,
3500 * so we retry every time.
3501 * btw, in Linux it never fails. --vda */
3504 if (act.sa_handler == SIG_IGN) {
3505 cur_act = S_HARD_IGN;
3507 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3509 cur_act = S_IGN; /* don't hard ignore these */
3513 if (cur_act == S_HARD_IGN || cur_act == new_act)
3516 act.sa_handler = SIG_DFL;
3519 act.sa_handler = signal_handler;
3522 act.sa_handler = SIG_IGN;
3526 /* flags and mask matter only if !DFL and !IGN, but we do it
3527 * for all cases for more deterministic behavior:
3530 sigfillset(&act.sa_mask);
3532 sigaction_set(signo, &act);
3537 /* mode flags for set_curjob */
3538 #define CUR_DELETE 2
3539 #define CUR_RUNNING 1
3540 #define CUR_STOPPED 0
3542 /* mode flags for dowait */
3543 #define DOWAIT_NONBLOCK WNOHANG
3544 #define DOWAIT_BLOCK 0
3547 /* pgrp of shell on invocation */
3548 static int initialpgrp; //references:2
3549 static int ttyfd = -1; //5
3552 static struct job *jobtab; //5
3554 static unsigned njobs; //4
3556 static struct job *curjob; //lots
3557 /* number of presumed living untracked jobs */
3558 static int jobless; //4
3561 set_curjob(struct job *jp, unsigned mode)
3564 struct job **jpp, **curp;
3566 /* first remove from list */
3567 jpp = curp = &curjob;
3572 jpp = &jp1->prev_job;
3574 *jpp = jp1->prev_job;
3576 /* Then re-insert in correct position */
3584 /* job being deleted */
3587 /* newly created job or backgrounded job,
3588 * put after all stopped jobs.
3593 if (!jp1 || jp1->state != JOBSTOPPED)
3596 jpp = &jp1->prev_job;
3602 /* newly stopped job - becomes curjob */
3603 jp->prev_job = *jpp;
3611 jobno(const struct job *jp)
3613 return jp - jobtab + 1;
3618 * Convert a job name to a job structure.
3621 #define getjob(name, getctl) getjob(name)
3624 getjob(const char *name, int getctl)
3628 const char *err_msg = "%s: no such job";
3632 char *(*match)(const char *, const char *);
3647 if (c == '+' || c == '%') {
3649 err_msg = "No current job";
3655 err_msg = "No previous job";
3665 if (num > 0 && num <= njobs) {
3666 jp = jobtab + num - 1;
3681 if (match(jp->ps[0].ps_cmd, p)) {
3685 err_msg = "%s: ambiguous";
3695 err_msg = "job %s not created under job control";
3696 if (getctl && jp->jobctl == 0)
3701 ash_msg_and_raise_error(err_msg, name);
3705 * Mark a job structure as unused.
3708 freejob(struct job *jp)
3710 struct procstat *ps;
3714 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3715 if (ps->ps_cmd != nullstr)
3718 if (jp->ps != &jp->ps0)
3721 set_curjob(jp, CUR_DELETE);
3727 xtcsetpgrp(int fd, pid_t pgrp)
3729 if (tcsetpgrp(fd, pgrp))
3730 ash_msg_and_raise_error("can't set tty process group (%m)");
3734 * Turn job control on and off.
3736 * Note: This code assumes that the third arg to ioctl is a character
3737 * pointer, which is true on Berkeley systems but not System V. Since
3738 * System V doesn't have job control yet, this isn't a problem now.
3740 * Called with interrupts off.
3748 if (on == doing_jobctl || rootshell == 0)
3752 ofd = fd = open(_PATH_TTY, O_RDWR);
3754 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3755 * That sometimes helps to acquire controlling tty.
3756 * Obviously, a workaround for bugs when someone
3757 * failed to provide a controlling tty to bash! :) */
3763 fd = fcntl(fd, F_DUPFD, 10);
3768 /* fd is a tty at this point */
3769 close_on_exec_on(fd);
3770 while (1) { /* while we are in the background */
3771 pgrp = tcgetpgrp(fd);
3774 ash_msg("can't access tty; job control turned off");
3778 if (pgrp == getpgrp())
3789 xtcsetpgrp(fd, pgrp);
3791 /* turning job control off */
3794 /* was xtcsetpgrp, but this can make exiting ash
3795 * loop forever if pty is already deleted */
3796 tcsetpgrp(fd, pgrp);
3810 static int FAST_FUNC
3811 killcmd(int argc, char **argv)
3813 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3816 if (argv[i][0] == '%') {
3818 * "kill %N" - job kill
3819 * Converting to pgrp / pid kill
3825 jp = getjob(argv[i], 0);
3827 * In jobs started under job control, we signal
3828 * entire process group by kill -PGRP_ID.
3829 * This happens, f.e., in interactive shell.
3831 * Otherwise, we signal each child via
3832 * kill PID1 PID2 PID3.
3834 * sh -c 'sleep 1|sleep 1 & kill %1'
3835 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3836 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3838 n = jp->nprocs; /* can't be 0 (I hope) */
3841 dst = alloca(n * sizeof(int)*4);
3843 for (j = 0; j < n; j++) {
3844 struct procstat *ps = &jp->ps[j];
3845 /* Skip non-running and not-stopped members
3846 * (i.e. dead members) of the job
3848 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3851 * kill_main has matching code to expect
3852 * leading space. Needed to not confuse
3853 * negative pids with "kill -SIGNAL_NO" syntax
3855 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3859 } while (argv[++i]);
3861 return kill_main(argc, argv);
3865 showpipe(struct job *jp /*, FILE *out*/)
3867 struct procstat *ps;
3868 struct procstat *psend;
3870 psend = jp->ps + jp->nprocs;
3871 for (ps = jp->ps + 1; ps < psend; ps++)
3872 printf(" | %s", ps->ps_cmd);
3873 newline_and_flush(stdout);
3874 flush_stdout_stderr();
3879 restartjob(struct job *jp, int mode)
3881 struct procstat *ps;
3887 if (jp->state == JOBDONE)
3889 jp->state = JOBRUNNING;
3890 pgid = jp->ps[0].ps_pid;
3891 if (mode == FORK_FG)
3892 xtcsetpgrp(ttyfd, pgid);
3893 killpg(pgid, SIGCONT);
3897 if (WIFSTOPPED(ps->ps_status)) {
3903 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3908 static int FAST_FUNC
3909 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3915 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3919 jp = getjob(*argv, 1);
3920 if (mode == FORK_BG) {
3921 set_curjob(jp, CUR_RUNNING);
3922 printf("[%d] ", jobno(jp));
3924 out1str(jp->ps[0].ps_cmd);
3925 showpipe(jp /*, stdout*/);
3926 retval = restartjob(jp, mode);
3927 } while (*argv && *++argv);
3933 sprint_status48(char *s, int status, int sigonly)
3939 if (!WIFEXITED(status)) {
3940 if (JOBS && WIFSTOPPED(status))
3941 st = WSTOPSIG(status);
3943 st = WTERMSIG(status);
3945 if (st == SIGINT || st == SIGPIPE)
3947 if (JOBS && WIFSTOPPED(status))
3951 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3952 col = fmtstr(s, 32, strsignal(st));
3953 if (WCOREDUMP(status)) {
3954 strcpy(s + col, " (core dumped)");
3955 col += sizeof(" (core dumped)")-1;
3957 } else if (!sigonly) {
3958 st = WEXITSTATUS(status);
3959 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3966 dowait(int wait_flags, struct job *job)
3971 struct job *thisjob;
3973 TRACE(("dowait(0x%x) called\n", wait_flags));
3975 /* Do a wait system call. If job control is compiled in, we accept
3976 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3977 * NB: _not_ safe_waitpid, we need to detect EINTR */
3979 wait_flags |= WUNTRACED;
3980 pid = waitpid(-1, &status, wait_flags);
3981 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3982 pid, status, errno, strerror(errno)));
3988 for (jp = curjob; jp; jp = jp->prev_job) {
3990 struct procstat *ps;
3991 struct procstat *psend;
3992 if (jp->state == JOBDONE)
3996 psend = ps + jp->nprocs;
3998 if (ps->ps_pid == pid) {
3999 TRACE(("Job %d: changing status of proc %d "
4000 "from 0x%x to 0x%x\n",
4001 jobno(jp), pid, ps->ps_status, status));
4002 ps->ps_status = status;
4005 if (ps->ps_status == -1)
4006 jobstate = JOBRUNNING;
4008 if (jobstate == JOBRUNNING)
4010 if (WIFSTOPPED(ps->ps_status)) {
4011 jp->stopstatus = ps->ps_status;
4012 jobstate = JOBSTOPPED;
4015 } while (++ps < psend);
4019 /* Found the job where one of its processes changed its state.
4020 * Is there at least one live and running process in this job? */
4021 if (jobstate != JOBRUNNING) {
4022 /* No. All live processes in the job are stopped
4023 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4025 thisjob->changed = 1;
4026 if (thisjob->state != jobstate) {
4027 TRACE(("Job %d: changing state from %d to %d\n",
4028 jobno(thisjob), thisjob->state, jobstate));
4029 thisjob->state = jobstate;
4031 if (jobstate == JOBSTOPPED)
4032 set_curjob(thisjob, CUR_STOPPED);
4038 /* The process wasn't found in job list */
4039 if (JOBS && !WIFSTOPPED(status))
4044 if (thisjob && thisjob == job) {
4048 len = sprint_status48(s, status, 1);
4059 blocking_wait_with_raise_on_sig(void)
4061 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4062 if (pid <= 0 && pending_sig)
4063 raise_exception(EXSIG);
4069 showjob(struct job *jp, int mode)
4071 struct procstat *ps;
4072 struct procstat *psend;
4075 char s[16 + 16 + 48];
4076 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4080 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4081 /* just output process (group) id of pipeline */
4082 fprintf(out, "%d\n", ps->ps_pid);
4086 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4091 else if (curjob && jp == curjob->prev_job)
4094 if (mode & SHOW_PIDS)
4095 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4097 psend = ps + jp->nprocs;
4099 if (jp->state == JOBRUNNING) {
4100 strcpy(s + col, "Running");
4101 col += sizeof("Running") - 1;
4103 int status = psend[-1].ps_status;
4104 if (jp->state == JOBSTOPPED)
4105 status = jp->stopstatus;
4106 col += sprint_status48(s + col, status, 0);
4108 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4110 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4111 * or prints several "PID | <cmdN>" lines,
4112 * depending on SHOW_PIDS bit.
4113 * We do not print status of individual processes
4114 * between PID and <cmdN>. bash does it, but not very well:
4115 * first line shows overall job status, not process status,
4116 * making it impossible to know 1st process status.
4120 /* for each process */
4123 if (mode & SHOW_PIDS)
4124 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4126 fprintf(out, "%s%*c%s%s",
4128 33 - col >= 0 ? 33 - col : 0, ' ',
4129 ps == jp->ps ? "" : "| ",
4132 } while (++ps != psend);
4133 newline_and_flush(out);
4137 if (jp->state == JOBDONE) {
4138 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4144 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4145 * statuses have changed since the last call to showjobs.
4152 TRACE(("showjobs(0x%x) called\n", mode));
4154 /* Handle all finished jobs */
4155 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4158 for (jp = curjob; jp; jp = jp->prev_job) {
4159 if (!(mode & SHOW_CHANGED) || jp->changed) {
4165 static int FAST_FUNC
4166 jobscmd(int argc UNUSED_PARAM, char **argv)
4171 while ((m = nextopt("lp")) != '\0') {
4175 mode |= SHOW_ONLY_PGID;
4181 showjob(getjob(*argv, 0), mode);
4191 /* Called only on finished or stopped jobs (no members are running) */
4193 getstatus(struct job *job)
4197 struct procstat *ps;
4199 /* Fetch last member's status */
4200 ps = job->ps + job->nprocs - 1;
4201 status = ps->ps_status;
4203 /* "set -o pipefail" mode: use last _nonzero_ status */
4204 while (status == 0 && --ps >= job->ps)
4205 status = ps->ps_status;
4208 retval = WEXITSTATUS(status);
4209 if (!WIFEXITED(status)) {
4211 retval = WSTOPSIG(status);
4212 if (!WIFSTOPPED(status))
4215 /* XXX: limits number of signals */
4216 retval = WTERMSIG(status);
4218 if (retval == SIGINT)
4224 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4225 jobno(job), job->nprocs, status, retval));
4229 static int FAST_FUNC
4230 waitcmd(int argc UNUSED_PARAM, char **argv)
4237 raise_exception(EXSIG);
4244 /* wait for all jobs */
4248 if (!jp) /* no running procs */
4250 if (jp->state == JOBRUNNING)
4255 blocking_wait_with_raise_on_sig();
4257 * "When bash is waiting for an asynchronous command via
4258 * the wait builtin, the reception of a signal for which a trap
4259 * has been set will cause the wait builtin to return immediately
4260 * with an exit status greater than 128, immediately after which
4261 * the trap is executed."
4263 * blocking_wait_with_raise_on_sig raises signal handlers
4264 * if it gets no pid (pid < 0). However,
4265 * if child sends us a signal *and immediately exits*,
4266 * blocking_wait_with_raise_on_sig gets pid > 0
4267 * and does not handle pending_sig. Check this case: */
4269 raise_exception(EXSIG);
4275 if (**argv != '%') {
4276 pid_t pid = number(*argv);
4281 if (job->ps[job->nprocs - 1].ps_pid == pid)
4283 job = job->prev_job;
4286 job = getjob(*argv, 0);
4288 /* loop until process terminated or stopped */
4289 while (job->state == JOBRUNNING)
4290 blocking_wait_with_raise_on_sig();
4292 retval = getstatus(job);
4305 struct job *jp, *jq;
4307 len = njobs * sizeof(*jp);
4309 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4311 offset = (char *)jp - (char *)jq;
4313 /* Relocate pointers */
4316 jq = (struct job *)((char *)jq + l);
4320 #define joff(p) ((struct job *)((char *)(p) + l))
4321 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4322 if (joff(jp)->ps == &jq->ps0)
4323 jmove(joff(jp)->ps);
4324 if (joff(jp)->prev_job)
4325 jmove(joff(jp)->prev_job);
4335 jp = (struct job *)((char *)jp + len);
4339 } while (--jq >= jp);
4344 * Return a new job structure.
4345 * Called with interrupts off.
4348 makejob(/*union node *node,*/ int nprocs)
4353 for (i = njobs, jp = jobtab; ; jp++) {
4360 if (jp->state != JOBDONE || !jp->waited)
4369 memset(jp, 0, sizeof(*jp));
4371 /* jp->jobctl is a bitfield.
4372 * "jp->jobctl |= jobctl" likely to give awful code */
4376 jp->prev_job = curjob;
4381 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4383 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4390 * Return a string identifying a command (to be printed by the
4393 static char *cmdnextc;
4396 cmdputs(const char *s)
4398 static const char vstype[VSTYPE + 1][3] = {
4399 "", "}", "-", "+", "?", "=",
4400 "%", "%%", "#", "##"
4401 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4404 const char *p, *str;
4408 unsigned char subtype = 0;
4412 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4414 while ((c = *p++) != '\0') {
4422 if ((subtype & VSTYPE) == VSLENGTH)
4428 str = "\"}" + !(quoted & 1);
4435 #if ENABLE_SH_MATH_SUPPORT
4450 if ((subtype & VSTYPE) != VSNORMAL)
4452 str = vstype[subtype & VSTYPE];
4453 if (subtype & VSNUL)
4462 /* These can only happen inside quotes */
4475 while ((c = *str++) != '\0') {
4478 } /* while *p++ not NUL */
4481 USTPUTC('"', nextc);
4487 /* cmdtxt() and cmdlist() call each other */
4488 static void cmdtxt(union node *n);
4491 cmdlist(union node *np, int sep)
4493 for (; np; np = np->narg.next) {
4497 if (sep && np->narg.next)
4503 cmdtxt(union node *n)
4506 struct nodelist *lp;
4517 lp = n->npipe.cmdlist;
4535 cmdtxt(n->nbinary.ch1);
4551 cmdtxt(n->nif.test);
4553 if (n->nif.elsepart) {
4554 cmdtxt(n->nif.ifpart);
4556 n = n->nif.elsepart;
4574 cmdtxt(n->nbinary.ch1);
4584 cmdputs(n->nfor.var);
4586 cmdlist(n->nfor.args, 1);
4591 cmdputs(n->narg.text);
4595 cmdlist(n->ncmd.args, 1);
4596 cmdlist(n->ncmd.redirect, 0);
4609 cmdputs(n->ncase.expr->narg.text);
4611 for (np = n->ncase.cases; np; np = np->nclist.next) {
4612 cmdtxt(np->nclist.pattern);
4614 cmdtxt(np->nclist.body);
4628 #if ENABLE_ASH_BASH_COMPAT
4643 cmdputs(utoa(n->nfile.fd));
4645 if (n->type == NTOFD || n->type == NFROMFD) {
4646 cmdputs(utoa(n->ndup.dupfd));
4655 commandtext(union node *n)
4659 STARTSTACKSTR(cmdnextc);
4661 name = stackblock();
4662 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4663 return ckstrdup(name);
4668 * Fork off a subshell. If we are doing job control, give the subshell its
4669 * own process group. Jp is a job structure that the job is to be added to.
4670 * N is the command that will be evaluated by the child. Both jp and n may
4671 * be NULL. The mode parameter can be one of the following:
4672 * FORK_FG - Fork off a foreground process.
4673 * FORK_BG - Fork off a background process.
4674 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4675 * process group even if job control is on.
4677 * When job control is turned off, background processes have their standard
4678 * input redirected to /dev/null (except for the second and later processes
4681 * Called with interrupts off.
4684 * Clear traps on a fork.
4691 for (tp = trap; tp < &trap[NSIG]; tp++) {
4692 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4694 if (trap_ptr == trap)
4696 /* else: it "belongs" to trap_ptr vector, don't free */
4698 if ((tp - trap) != 0)
4699 setsignal(tp - trap);
4706 /* Lives far away from here, needed for forkchild */
4707 static void closescript(void);
4709 /* Called after fork(), in child */
4710 static NOINLINE void
4711 forkchild(struct job *jp, union node *n, int mode)
4715 TRACE(("Child shell %d\n", getpid()));
4719 /* man bash: "Non-builtin commands run by bash have signal handlers
4720 * set to the values inherited by the shell from its parent".
4721 * Do we do it correctly? */
4725 if (mode == FORK_NOJOB /* is it `xxx` ? */
4726 && n && n->type == NCMD /* is it single cmd? */
4727 /* && n->ncmd.args->type == NARG - always true? */
4728 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4729 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4730 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4732 TRACE(("Trap hack\n"));
4733 /* Awful hack for `trap` or $(trap).
4735 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4736 * contains an example where "trap" is executed in a subshell:
4738 * save_traps=$(trap)
4740 * eval "$save_traps"
4742 * Standard does not say that "trap" in subshell shall print
4743 * parent shell's traps. It only says that its output
4744 * must have suitable form, but then, in the above example
4745 * (which is not supposed to be normative), it implies that.
4747 * bash (and probably other shell) does implement it
4748 * (traps are reset to defaults, but "trap" still shows them),
4749 * but as a result, "trap" logic is hopelessly messed up:
4752 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4753 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4754 * # true | trap <--- trap is in subshell - no output (ditto)
4755 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4756 * trap -- 'echo Ho' SIGWINCH
4757 * # echo `(trap)` <--- in subshell in subshell - output
4758 * trap -- 'echo Ho' SIGWINCH
4759 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4760 * trap -- 'echo Ho' SIGWINCH
4762 * The rules when to forget and when to not forget traps
4763 * get really complex and nonsensical.
4765 * Our solution: ONLY bare $(trap) or `trap` is special.
4767 /* Save trap handler strings for trap builtin to print */
4768 trap_ptr = xmemdup(trap, sizeof(trap));
4769 /* Fall through into clearing traps */
4773 /* do job control only in root shell */
4775 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4778 if (jp->nprocs == 0)
4781 pgrp = jp->ps[0].ps_pid;
4782 /* this can fail because we are doing it in the parent also */
4784 if (mode == FORK_FG)
4785 xtcsetpgrp(ttyfd, pgrp);
4790 if (mode == FORK_BG) {
4791 /* man bash: "When job control is not in effect,
4792 * asynchronous commands ignore SIGINT and SIGQUIT" */
4795 if (jp->nprocs == 0) {
4797 if (open(bb_dev_null, O_RDONLY) != 0)
4798 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4802 if (iflag) { /* why if iflag only? */
4807 * "In all cases, bash ignores SIGQUIT. Non-builtin
4808 * commands run by bash have signal handlers
4809 * set to the values inherited by the shell
4811 * Take care of the second rule: */
4815 if (n && n->type == NCMD
4816 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4818 TRACE(("Job hack\n"));
4819 /* "jobs": we do not want to clear job list for it,
4820 * instead we remove only _its_ own_ job from job list.
4821 * This makes "jobs .... | cat" more useful.
4827 for (jp = curjob; jp; jp = jp->prev_job)
4832 /* Called after fork(), in parent */
4834 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4837 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4839 TRACE(("In parent shell: child = %d\n", pid));
4841 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4847 if (mode != FORK_NOJOB && jp->jobctl) {
4850 if (jp->nprocs == 0)
4853 pgrp = jp->ps[0].ps_pid;
4854 /* This can fail because we are doing it in the child also */
4858 if (mode == FORK_BG) {
4859 backgndpid = pid; /* set $! */
4860 set_curjob(jp, CUR_RUNNING);
4863 struct procstat *ps = &jp->ps[jp->nprocs++];
4866 ps->ps_cmd = nullstr;
4868 if (doing_jobctl && n)
4869 ps->ps_cmd = commandtext(n);
4875 forkshell(struct job *jp, union node *n, int mode)
4879 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4882 TRACE(("Fork failed, errno=%d", errno));
4885 ash_msg_and_raise_error("can't fork");
4888 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4889 forkchild(jp, n, mode);
4891 forkparent(jp, n, mode, pid);
4897 * Wait for job to finish.
4899 * Under job control we have the problem that while a child process
4900 * is running interrupts generated by the user are sent to the child
4901 * but not to the shell. This means that an infinite loop started by
4902 * an interactive user may be hard to kill. With job control turned off,
4903 * an interactive user may place an interactive program inside a loop.
4904 * If the interactive program catches interrupts, the user doesn't want
4905 * these interrupts to also abort the loop. The approach we take here
4906 * is to have the shell ignore interrupt signals while waiting for a
4907 * foreground process to terminate, and then send itself an interrupt
4908 * signal if the child process was terminated by an interrupt signal.
4909 * Unfortunately, some programs want to do a bit of cleanup and then
4910 * exit on interrupt; unless these processes terminate themselves by
4911 * sending a signal to themselves (instead of calling exit) they will
4912 * confuse this approach.
4914 * Called with interrupts off.
4917 waitforjob(struct job *jp)
4921 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4924 while (jp->state == JOBRUNNING) {
4925 /* In non-interactive shells, we _can_ get
4926 * a keyboard signal here and be EINTRed,
4927 * but we just loop back, waiting for command to complete.
4930 * "If bash is waiting for a command to complete and receives
4931 * a signal for which a trap has been set, the trap
4932 * will not be executed until the command completes."
4934 * Reality is that even if trap is not set, bash
4935 * will not act on the signal until command completes.
4936 * Try this. sleep5intoff.c:
4937 * #include <signal.h>
4938 * #include <unistd.h>
4941 * sigemptyset(&set);
4942 * sigaddset(&set, SIGINT);
4943 * sigaddset(&set, SIGQUIT);
4944 * sigprocmask(SIG_BLOCK, &set, NULL);
4948 * $ bash -c './sleep5intoff; echo hi'
4949 * ^C^C^C^C <--- pressing ^C once a second
4951 * $ bash -c './sleep5intoff; echo hi'
4952 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4955 dowait(DOWAIT_BLOCK, jp);
4962 xtcsetpgrp(ttyfd, rootpid);
4964 * This is truly gross.
4965 * If we're doing job control, then we did a TIOCSPGRP which
4966 * caused us (the shell) to no longer be in the controlling
4967 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4968 * intuit from the subprocess exit status whether a SIGINT
4969 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4971 if (jp->sigint) /* TODO: do the same with all signals */
4972 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4974 if (jp->state == JOBDONE)
4981 * return 1 if there are stopped jobs, otherwise 0
4993 if (jp && jp->state == JOBSTOPPED) {
4994 out2str("You have stopped jobs.\n");
5003 /* ============ redir.c
5005 * Code for dealing with input/output redirection.
5010 #define EMPTY -2 /* marks an unused slot in redirtab */
5011 #define CLOSED -3 /* marks a slot of previously-closed fd */
5014 * Open a file in noclobber mode.
5015 * The code was copied from bash.
5018 noclobberopen(const char *fname)
5021 struct stat finfo, finfo2;
5024 * If the file exists and is a regular file, return an error
5027 r = stat(fname, &finfo);
5028 if (r == 0 && S_ISREG(finfo.st_mode)) {
5034 * If the file was not present (r != 0), make sure we open it
5035 * exclusively so that if it is created before we open it, our open
5036 * will fail. Make sure that we do not truncate an existing file.
5037 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5038 * file was not a regular file, we leave O_EXCL off.
5041 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5042 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5044 /* If the open failed, return the file descriptor right away. */
5049 * OK, the open succeeded, but the file may have been changed from a
5050 * non-regular file to a regular file between the stat and the open.
5051 * We are assuming that the O_EXCL open handles the case where FILENAME
5052 * did not exist and is symlinked to an existing file between the stat
5057 * If we can open it and fstat the file descriptor, and neither check
5058 * revealed that it was a regular file, and the file has not been
5059 * replaced, return the file descriptor.
5061 if (fstat(fd, &finfo2) == 0
5062 && !S_ISREG(finfo2.st_mode)
5063 && finfo.st_dev == finfo2.st_dev
5064 && finfo.st_ino == finfo2.st_ino
5069 /* The file has been replaced. badness. */
5076 * Handle here documents. Normally we fork off a process to write the
5077 * data to a pipe. If the document is short, we can stuff the data in
5078 * the pipe without forking.
5080 /* openhere needs this forward reference */
5081 static void expandhere(union node *arg, int fd);
5083 openhere(union node *redir)
5089 ash_msg_and_raise_error("pipe call failed");
5090 if (redir->type == NHERE) {
5091 len = strlen(redir->nhere.doc->narg.text);
5092 if (len <= PIPE_BUF) {
5093 full_write(pip[1], redir->nhere.doc->narg.text, len);
5097 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5100 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5101 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5102 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5103 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5104 signal(SIGPIPE, SIG_DFL);
5105 if (redir->type == NHERE)
5106 full_write(pip[1], redir->nhere.doc->narg.text, len);
5108 expandhere(redir->nhere.doc, pip[1]);
5109 _exit(EXIT_SUCCESS);
5117 openredirect(union node *redir)
5122 switch (redir->nfile.type) {
5123 /* Can't happen, our single caller does this itself */
5129 return openhere(redir);
5132 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5133 * allocated space. Do it only when we know it is safe.
5135 fname = redir->nfile.expfname;
5137 switch (redir->nfile.type) {
5143 f = open(fname, O_RDONLY);
5148 f = open(fname, O_RDWR|O_CREAT, 0666);
5153 #if ENABLE_ASH_BASH_COMPAT
5156 /* Take care of noclobber mode. */
5158 f = noclobberopen(fname);
5165 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5170 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5178 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5180 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5184 * Copy a file descriptor to be >= to. Throws exception on error.
5186 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5187 * old code was doing close(to) prior to copyfd() to achieve the same */
5189 COPYFD_EXACT = (int)~(INT_MAX),
5190 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5193 copyfd(int from, int to)
5197 if (to & COPYFD_EXACT) {
5198 to &= ~COPYFD_EXACT;
5200 newfd = dup2(from, to);
5202 newfd = fcntl(from, F_DUPFD, to);
5205 /* Happens when source fd is not open: try "echo >&99" */
5206 ash_msg_and_raise_error("%d: %m", from);
5211 /* Struct def and variable are moved down to the first usage site */
5216 struct redirtab *next;
5218 struct two_fd_t two_fd[];
5220 #define redirlist (G_var.redirlist)
5223 need_to_remember(struct redirtab *rp, int fd)
5227 if (!rp) /* remembering was not requested */
5230 for (i = 0; i < rp->pair_count; i++) {
5231 if (rp->two_fd[i].orig == fd) {
5232 /* already remembered */
5239 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5241 is_hidden_fd(struct redirtab *rp, int fd)
5244 struct parsefile *pf;
5248 /* Check open scripts' fds */
5251 /* We skip pf_fd == 0 case because of the following case:
5252 * $ ash # running ash interactively
5254 * and in script.sh: "exec 9>&0".
5255 * Even though top-level pf_fd _is_ 0,
5256 * it's still ok to use it: "read" builtin uses it,
5257 * why should we cripple "exec" builtin?
5259 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5267 /* Check saved fds of redirects */
5268 fd |= COPYFD_RESTORE;
5269 for (i = 0; i < rp->pair_count; i++) {
5270 if (rp->two_fd[i].copy == fd) {
5278 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5279 * old file descriptors are stashed away so that the redirection can be
5280 * undone by calling popredir.
5282 /* flags passed to redirect */
5283 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5284 #define REDIR_SAVEFD2 03 /* set preverrout */
5286 redirect(union node *redir, int flags)
5288 struct redirtab *sv;
5293 int copied_fd2 = -1;
5302 if (flags & REDIR_PUSH) {
5303 union node *tmp = redir;
5306 #if ENABLE_ASH_BASH_COMPAT
5307 if (tmp->nfile.type == NTO2)
5310 tmp = tmp->nfile.next;
5312 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5313 sv->next = redirlist;
5314 sv->pair_count = sv_pos;
5316 while (sv_pos > 0) {
5318 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5324 fd = redir->nfile.fd;
5325 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5326 right_fd = redir->ndup.dupfd;
5327 //bb_error_msg("doing %d > %d", fd, right_fd);
5328 /* redirect from/to same file descriptor? */
5331 /* "echo >&10" and 10 is a fd opened to a sh script? */
5332 if (is_hidden_fd(sv, right_fd)) {
5333 errno = EBADF; /* as if it is closed */
5334 ash_msg_and_raise_error("%d: %m", right_fd);
5338 newfd = openredirect(redir); /* always >= 0 */
5340 /* Descriptor wasn't open before redirect.
5341 * Mark it for close in the future */
5342 if (need_to_remember(sv, fd)) {
5343 goto remember_to_close;
5348 #if ENABLE_ASH_BASH_COMPAT
5351 if (need_to_remember(sv, fd)) {
5352 /* Copy old descriptor */
5353 /* Careful to not accidentally "save"
5354 * to the same fd as right side fd in N>&M */
5355 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5356 i = fcntl(fd, F_DUPFD, minfd);
5357 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5358 * are closed in popredir() in the child, preventing them from leaking
5359 * into child. (popredir() also cleans up the mess in case of failures)
5364 /* Strange error (e.g. "too many files" EMFILE?) */
5368 ash_msg_and_raise_error("%d: %m", fd);
5371 /* EBADF: it is not open - good, remember to close it */
5374 } else { /* fd is open, save its copy */
5375 /* "exec fd>&-" should not close fds
5376 * which point to script file(s).
5377 * Force them to be restored afterwards */
5378 if (is_hidden_fd(sv, fd))
5379 i |= COPYFD_RESTORE;
5383 sv->two_fd[sv_pos].orig = fd;
5384 sv->two_fd[sv_pos].copy = i;
5388 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5389 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5390 /* Don't want to trigger debugging */
5394 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5396 } else if (fd != newfd) { /* move newfd to fd */
5397 copyfd(newfd, fd | COPYFD_EXACT);
5398 #if ENABLE_ASH_BASH_COMPAT
5399 if (!(redir->nfile.type == NTO2 && fd == 2))
5403 #if ENABLE_ASH_BASH_COMPAT
5404 if (redir->nfile.type == NTO2 && fd == 1) {
5405 /* We already redirected it to fd 1, now copy it to 2 */
5411 } while ((redir = redir->nfile.next) != NULL);
5414 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5415 preverrout_fd = copied_fd2;
5419 * Undo the effects of the last redirection.
5422 popredir(int drop, int restore)
5424 struct redirtab *rp;
5427 if (redirlist == NULL)
5431 for (i = 0; i < rp->pair_count; i++) {
5432 int fd = rp->two_fd[i].orig;
5433 int copy = rp->two_fd[i].copy;
5434 if (copy == CLOSED) {
5439 if (copy != EMPTY) {
5440 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5441 copy &= ~COPYFD_RESTORE;
5443 copyfd(copy, fd | COPYFD_EXACT);
5445 close(copy & ~COPYFD_RESTORE);
5448 redirlist = rp->next;
5454 * Undo all redirections. Called on error or interrupt.
5458 * Discard all saved file descriptors.
5461 clearredir(int drop)
5464 popredir(drop, /*restore:*/ 0);
5468 redirectsafe(union node *redir, int flags)
5471 volatile int saveint;
5472 struct jmploc *volatile savehandler = exception_handler;
5473 struct jmploc jmploc;
5476 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5477 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5479 exception_handler = &jmploc;
5480 redirect(redir, flags);
5482 exception_handler = savehandler;
5483 if (err && exception_type != EXERROR)
5484 longjmp(exception_handler->loc, 1);
5485 RESTORE_INT(saveint);
5490 /* ============ Routines to expand arguments to commands
5492 * We have to deal with backquotes, shell variables, and file metacharacters.
5495 #if ENABLE_SH_MATH_SUPPORT
5497 ash_arith(const char *s)
5499 arith_state_t math_state;
5502 math_state.lookupvar = lookupvar;
5503 math_state.setvar = setvar0;
5504 //math_state.endofname = endofname;
5507 result = arith(&math_state, s);
5508 if (math_state.errmsg)
5509 ash_msg_and_raise_error(math_state.errmsg);
5519 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5520 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5521 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5522 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5523 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5524 * POSIX says for this case:
5525 * Pathname expansion shall not be performed on the word by a
5526 * non-interactive shell; an interactive shell may perform it, but shall
5527 * do so only when the expansion would result in one word.
5528 * Currently, our code complies to the above rule by never globbing
5529 * redirection filenames.
5530 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5531 * (this means that on a typical Linux distro, bash almost always
5532 * performs globbing, and thus diverges from what we do).
5534 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5535 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5536 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5537 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5538 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5542 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5543 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5544 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5545 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5546 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5548 /* Add CTLESC when necessary. */
5549 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5550 /* Do not skip NUL characters. */
5551 #define QUOTES_KEEPNUL EXP_TILDE
5554 * Structure specifying which parts of the string should be searched
5555 * for IFS characters.
5558 struct ifsregion *next; /* next region in list */
5559 int begoff; /* offset of start of region */
5560 int endoff; /* offset of end of region */
5561 int nulonly; /* search for nul bytes only */
5565 struct strlist *list;
5566 struct strlist **lastp;
5569 /* output of current string */
5570 static char *expdest;
5571 /* list of back quote expressions */
5572 static struct nodelist *argbackq;
5573 /* first struct in list of ifs regions */
5574 static struct ifsregion ifsfirst;
5575 /* last struct in list */
5576 static struct ifsregion *ifslastp;
5577 /* holds expanded arg list */
5578 static struct arglist exparg;
5583 #if !ENABLE_SH_MATH_SUPPORT
5584 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5585 typedef long arith_t;
5586 # define ARITH_FMT "%ld"
5593 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5594 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5595 STADJUST(len, expdest);
5600 esclen(const char *start, const char *p)
5604 while (p > start && (unsigned char)*--p == CTLESC) {
5611 * Remove any CTLESC characters from a string.
5614 rmescapes(char *str, int flag)
5616 static const char qchars[] ALIGN1 = {
5617 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5621 unsigned protect_against_glob;
5623 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5625 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5631 if (flag & RMESCAPE_ALLOC) {
5632 size_t len = p - str;
5633 size_t fulllen = len + strlen(p) + 1;
5635 if (flag & RMESCAPE_GROW) {
5636 int strloc = str - (char *)stackblock();
5637 r = makestrspace(fulllen, expdest);
5638 /* p and str may be invalidated by makestrspace */
5639 str = (char *)stackblock() + strloc;
5641 } else if (flag & RMESCAPE_HEAP) {
5642 r = ckmalloc(fulllen);
5644 r = stalloc(fulllen);
5648 q = (char *)memcpy(q, str, len) + len;
5653 globbing = flag & RMESCAPE_GLOB;
5654 protect_against_glob = globbing;
5656 if ((unsigned char)*p == CTLQUOTEMARK) {
5657 // Note: both inquotes and protect_against_glob only affect whether
5658 inquotes = ~inquotes;
5660 protect_against_glob = globbing;
5663 if ((unsigned char)*p == CTLESC) {
5667 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5669 if (protect_against_glob) {
5672 } else if (*p == '\\' && !inquotes) {
5673 /* naked back slash */
5674 protect_against_glob = 0;
5677 #if ENABLE_ASH_BASH_COMPAT
5678 else if (*p == '/' && slash) {
5679 /* stop handling globbing and mark location of slash */
5680 globbing = slash = 0;
5684 protect_against_glob = globbing;
5689 if (flag & RMESCAPE_GROW) {
5691 STADJUST(q - r + 1, expdest);
5695 #define pmatch(a, b) !fnmatch((a), (b), 0)
5698 * Prepare a pattern for a expmeta (internal glob(3)) call.
5700 * Returns an stalloced string.
5703 preglob(const char *pattern, int flag)
5705 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5709 * Put a string on the stack.
5712 memtodest(const char *p, size_t len, int syntax, int quotes)
5719 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5722 unsigned char c = *p++;
5724 int n = SIT(c, syntax);
5725 if ((quotes & QUOTES_ESC)
5727 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5733 } else if (!(quotes & QUOTES_KEEPNUL))
5742 strtodest(const char *p, int syntax, int quotes)
5744 size_t len = strlen(p);
5745 memtodest(p, len, syntax, quotes);
5750 * Record the fact that we have to scan this region of the
5751 * string for IFS characters.
5754 recordregion(int start, int end, int nulonly)
5756 struct ifsregion *ifsp;
5758 if (ifslastp == NULL) {
5762 ifsp = ckzalloc(sizeof(*ifsp));
5763 /*ifsp->next = NULL; - ckzalloc did it */
5764 ifslastp->next = ifsp;
5768 ifslastp->begoff = start;
5769 ifslastp->endoff = end;
5770 ifslastp->nulonly = nulonly;
5774 removerecordregions(int endoff)
5776 if (ifslastp == NULL)
5779 if (ifsfirst.endoff > endoff) {
5780 while (ifsfirst.next) {
5781 struct ifsregion *ifsp;
5783 ifsp = ifsfirst.next->next;
5784 free(ifsfirst.next);
5785 ifsfirst.next = ifsp;
5788 if (ifsfirst.begoff > endoff) {
5791 ifslastp = &ifsfirst;
5792 ifsfirst.endoff = endoff;
5797 ifslastp = &ifsfirst;
5798 while (ifslastp->next && ifslastp->next->begoff < endoff)
5799 ifslastp = ifslastp->next;
5800 while (ifslastp->next) {
5801 struct ifsregion *ifsp;
5803 ifsp = ifslastp->next->next;
5804 free(ifslastp->next);
5805 ifslastp->next = ifsp;
5808 if (ifslastp->endoff > endoff)
5809 ifslastp->endoff = endoff;
5813 exptilde(char *startp, char *p, int flags)
5819 int quotes = flags & QUOTES_ESC;
5823 while ((c = *++p) != '\0') {
5830 if (flags & EXP_VARTILDE)
5840 if (*name == '\0') {
5841 home = lookupvar("HOME");
5843 pw = getpwnam(name);
5848 if (!home || !*home)
5851 strtodest(home, SQSYNTAX, quotes);
5859 * Execute a command inside back quotes. If it's a builtin command, we
5860 * want to save its output in a block obtained from malloc. Otherwise
5861 * we fork off a subprocess and get the output of the command via a pipe.
5862 * Should be called with interrupts off.
5864 struct backcmd { /* result of evalbackcmd */
5865 int fd; /* file descriptor to read from */
5866 int nleft; /* number of chars in buffer */
5867 char *buf; /* buffer */
5868 struct job *jp; /* job structure for command */
5871 /* These forward decls are needed to use "eval" code for backticks handling: */
5872 #define EV_EXIT 01 /* exit after evaluating tree */
5873 static int evaltree(union node *, int);
5875 static void FAST_FUNC
5876 evalbackcmd(union node *n, struct backcmd *result)
5890 ash_msg_and_raise_error("pipe call failed");
5891 jp = makejob(/*n,*/ 1);
5892 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5897 copyfd(pip[1], 1 | COPYFD_EXACT);
5900 /* TODO: eflag clearing makes the following not abort:
5901 * ash -c 'set -e; z=$(false;echo foo); echo $z'
5902 * which is what bash does (unless it is in POSIX mode).
5903 * dash deleted "eflag = 0" line in the commit
5904 * Date: Mon, 28 Jun 2010 17:11:58 +1000
5905 * [EVAL] Don't clear eflag in evalbackcmd
5906 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
5909 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5913 result->fd = pip[0];
5917 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5918 result->fd, result->buf, result->nleft, result->jp));
5922 * Expand stuff in backwards quotes.
5925 expbackq(union node *cmd, int flag)
5933 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5934 struct stackmark smark;
5937 startloc = expdest - (char *)stackblock();
5938 pushstackmark(&smark, startloc);
5939 evalbackcmd(cmd, &in);
5940 popstackmark(&smark);
5947 memtodest(p, i, syntax, flag & QUOTES_ESC);
5951 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5952 TRACE(("expbackq: read returns %d\n", i));
5961 back_exitstatus = waitforjob(in.jp);
5965 /* Eat all trailing newlines */
5967 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5971 if (!(flag & EXP_QUOTED))
5972 recordregion(startloc, dest - (char *)stackblock(), 0);
5973 TRACE(("evalbackq: size:%d:'%.*s'\n",
5974 (int)((dest - (char *)stackblock()) - startloc),
5975 (int)((dest - (char *)stackblock()) - startloc),
5976 stackblock() + startloc));
5979 #if ENABLE_SH_MATH_SUPPORT
5981 * Expand arithmetic expression. Backup to start of expression,
5982 * evaluate, place result in (backed up) result, adjust string position.
5994 * This routine is slightly over-complicated for
5995 * efficiency. Next we scan backwards looking for the
5996 * start of arithmetic.
5998 start = stackblock();
6005 while ((unsigned char)*p != CTLARI) {
6009 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6014 esc = esclen(start, p);
6024 removerecordregions(begoff);
6028 if (flag & QUOTES_ESC)
6029 rmescapes(p + 1, 0);
6031 len = cvtnum(ash_arith(p + 1));
6033 if (!(flag & EXP_QUOTED))
6034 recordregion(begoff, begoff + len, 0);
6038 /* argstr needs it */
6039 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6042 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6043 * characters to allow for further processing. Otherwise treat
6044 * $@ like $* since no splitting will be performed.
6046 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6047 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6048 * for correct expansion of "B=$A" word.
6051 argstr(char *p, int flags, struct strlist *var_str_list)
6053 static const char spclchars[] ALIGN1 = {
6061 #if ENABLE_SH_MATH_SUPPORT
6066 const char *reject = spclchars;
6067 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6072 if (!(flags & EXP_VARTILDE)) {
6074 } else if (flags & EXP_VARTILDE2) {
6079 if (flags & EXP_TILDE) {
6082 flags &= ~EXP_TILDE;
6086 p = exptilde(p, q, flags);
6089 startloc = expdest - (char *)stackblock();
6093 length += strcspn(p + length, reject);
6097 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6099 /* c == '=' || c == ':' || c == CTLENDARI */
6105 expdest = stack_nputstr(p, length, expdest);
6106 newloc = expdest - (char *)stackblock();
6107 if (breakall && !inquotes && newloc > startloc) {
6108 recordregion(startloc, newloc, 0);
6119 if (flags & EXP_VARTILDE2) {
6123 flags |= EXP_VARTILDE2;
6128 * sort of a hack - expand tildes in variable
6129 * assignments (after the first '=' and after ':'s).
6138 case CTLENDVAR: /* ??? */
6141 inquotes ^= EXP_QUOTED;
6142 /* "$@" syntax adherence hack */
6143 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6144 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6148 if (flags & QUOTES_ESC) {
6159 * Quoted parameter expansion pattern: remove quote
6160 * unless inside inner quotes or we have a literal
6163 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6164 EXP_QPAT && *p != '\\')
6169 TRACE(("argstr: evalvar('%s')\n", p));
6170 p = evalvar(p, flags | inquotes, var_str_list);
6171 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6174 expbackq(argbackq->n, flags | inquotes);
6175 argbackq = argbackq->next;
6177 #if ENABLE_SH_MATH_SUPPORT
6180 expari(flags | inquotes);
6189 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6190 char *pattern, int quotes, int zero)
6199 const char *s = loc2;
6206 match = pmatch(pattern, s);
6211 if (quotes && (unsigned char)*loc == CTLESC)
6220 scanright(char *startp, char *rmesc, char *rmescend,
6221 char *pattern, int quotes, int match_at_start)
6223 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6224 int try2optimize = match_at_start;
6230 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6231 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6232 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6234 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6235 * and on each iteration they go back two/one char until they reach the beginning.
6236 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6238 /* TODO: document in what other circumstances we are called. */
6240 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6243 const char *s = loc2;
6244 if (match_at_start) {
6248 match = pmatch(pattern, s);
6249 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6253 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6255 /* Maybe we can optimize this:
6256 * if pattern ends with unescaped *, we can avoid checking
6257 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6258 * it wont match truncated "raw_value_of_" strings too.
6260 unsigned plen = strlen(pattern);
6261 /* Does it end with "*"? */
6262 if (plen != 0 && pattern[--plen] == '*') {
6263 /* "xxxx*" is not escaped */
6264 /* "xxx\*" is escaped */
6265 /* "xx\\*" is not escaped */
6266 /* "x\\\*" is escaped */
6268 while (plen != 0 && pattern[--plen] == '\\')
6271 break; /* ends with unescaped "*" */
6279 esc = esclen(startp, loc);
6290 static void varunset(const char *, const char *, const char *, int) NORETURN;
6292 varunset(const char *end, const char *var, const char *umsg, int varflags)
6298 msg = "parameter not set";
6300 if ((unsigned char)*end == CTLENDVAR) {
6301 if (varflags & VSNUL)
6307 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6311 subevalvar(char *p, char *varname, int strloc, int subtype,
6312 int startloc, int varflags, int flag, struct strlist *var_str_list)
6314 struct nodelist *saveargbackq = argbackq;
6315 int quotes = flag & QUOTES_ESC;
6318 char *rmesc, *rmescend;
6320 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6321 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6322 int amount, resetloc;
6323 IF_ASH_BASH_COMPAT(int workloc;)
6325 char *(*scan)(char*, char*, char*, char*, int, int);
6327 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6328 // p, varname, strloc, subtype, startloc, varflags, quotes);
6330 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6331 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6333 STPUTC('\0', expdest);
6334 argbackq = saveargbackq;
6335 startp = (char *)stackblock() + startloc;
6339 setvar0(varname, startp);
6340 amount = startp - expdest;
6341 STADJUST(amount, expdest);
6345 varunset(p, varname, startp, varflags);
6348 #if ENABLE_ASH_BASH_COMPAT
6350 //TODO: support more general format ${v:EXPR:EXPR},
6351 // where EXPR follows $(()) rules
6352 loc = str = stackblock() + strloc;
6353 /* Read POS in ${var:POS:LEN} */
6354 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6355 len = str - startp - 1;
6357 /* *loc != '\0', guaranteed by parser */
6361 /* Adjust the length by the number of escapes */
6362 for (ptr = startp; ptr < (str - 1); ptr++) {
6363 if ((unsigned char)*ptr == CTLESC) {
6371 if (*loc++ == ':') {
6375 /* Skip POS in ${var:POS:LEN} */
6377 while (*loc && *loc != ':') {
6379 * bash complains on: var=qwe; echo ${var:1a:123}
6381 ash_msg_and_raise_error(msg_illnum, str);
6385 if (*loc++ == ':') {
6390 /* ${VAR:$((-n)):l} starts n chars from the end */
6391 pos = orig_len + pos;
6393 if ((unsigned)pos >= orig_len) {
6394 /* apart from obvious ${VAR:999999:l},
6395 * covers ${VAR:$((-9999999)):l} - result is ""
6401 if (len > (orig_len - pos))
6402 len = orig_len - pos;
6404 for (str = startp; pos; str++, pos--) {
6405 if (quotes && (unsigned char)*str == CTLESC)
6408 for (loc = startp; len; len--) {
6409 if (quotes && (unsigned char)*str == CTLESC)
6414 amount = loc - expdest;
6415 STADJUST(amount, expdest);
6420 resetloc = expdest - (char *)stackblock();
6422 /* We'll comeback here if we grow the stack while handling
6423 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6424 * stack will need rebasing, and we'll need to remove our work
6427 IF_ASH_BASH_COMPAT(restart:)
6429 amount = expdest - ((char *)stackblock() + resetloc);
6430 STADJUST(-amount, expdest);
6431 startp = (char *)stackblock() + startloc;
6434 rmescend = (char *)stackblock() + strloc;
6436 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6437 if (rmesc != startp) {
6439 startp = (char *)stackblock() + startloc;
6443 str = (char *)stackblock() + strloc;
6445 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6446 * The result is a_\_z_c (not a\_\_z_c)!
6448 * The search pattern and replace string treat backslashes differently!
6449 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6450 * and string. It's only used on the first call.
6452 preglob(str, IF_ASH_BASH_COMPAT(
6453 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6454 RMESCAPE_SLASH :) 0);
6456 #if ENABLE_ASH_BASH_COMPAT
6457 workloc = expdest - (char *)stackblock();
6458 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6462 repl = strchr(str, CTLESC);
6468 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6470 /* If there's no pattern to match, return the expansion unmolested */
6479 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6480 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6482 /* No match, advance */
6483 char *restart_detect = stackblock();
6485 STPUTC(*idx, expdest);
6486 if (quotes && (unsigned char)*idx == CTLESC) {
6489 STPUTC(*idx, expdest);
6491 if (stackblock() != restart_detect)
6496 /* continue; - prone to quadratic behavior, smarter code: */
6499 if (str[0] == '*') {
6500 /* Pattern is "*foo". If "*foo" does not match "long_string",
6501 * it would never match "ong_string" etc, no point in trying.
6508 if (subtype == VSREPLACEALL) {
6510 if (quotes && (unsigned char)*idx == CTLESC)
6519 //bb_error_msg("repl:'%s'", repl);
6520 for (loc = (char*)repl; *loc; loc++) {
6521 char *restart_detect = stackblock();
6522 if (quotes && *loc == '\\') {
6523 STPUTC(CTLESC, expdest);
6526 STPUTC(*loc, expdest);
6527 if (stackblock() != restart_detect)
6532 if (subtype == VSREPLACE) {
6533 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6535 char *restart_detect = stackblock();
6536 STPUTC(*idx, expdest);
6537 if (stackblock() != restart_detect)
6546 /* We've put the replaced text into a buffer at workloc, now
6547 * move it to the right place and adjust the stack.
6549 STPUTC('\0', expdest);
6550 startp = (char *)stackblock() + startloc;
6551 memmove(startp, (char *)stackblock() + workloc, len + 1);
6552 //bb_error_msg("startp:'%s'", startp);
6553 amount = expdest - (startp + len);
6554 STADJUST(-amount, expdest);
6557 #endif /* ENABLE_ASH_BASH_COMPAT */
6559 subtype -= VSTRIMRIGHT;
6561 if (subtype < 0 || subtype > 7)
6564 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6565 zero = subtype >> 1;
6566 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6567 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6569 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6572 memmove(startp, loc, str - loc);
6573 loc = startp + (str - loc) - 1;
6576 amount = loc - expdest;
6577 STADJUST(amount, expdest);
6583 * Add the value of a specialized variable to the stack string.
6584 * name parameter (examples):
6585 * ash -c 'echo $1' name:'1='
6586 * ash -c 'echo $qwe' name:'qwe='
6587 * ash -c 'echo $$' name:'$='
6588 * ash -c 'echo ${$}' name:'$='
6589 * ash -c 'echo ${$##q}' name:'$=q'
6590 * ash -c 'echo ${#$}' name:'$='
6591 * note: examples with bad shell syntax:
6592 * ash -c 'echo ${#$1}' name:'$=1'
6593 * ash -c 'echo ${#1#}' name:'1=#'
6595 static NOINLINE ssize_t
6596 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6603 int quoted = *quotedp;
6604 int subtype = varflags & VSTYPE;
6605 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6606 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6609 sep = (flags & EXP_FULL) << CHAR_BIT;
6610 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6620 num = shellparam.nparam;
6628 goto check_1char_name;
6630 expdest = makestrspace(NOPTS, expdest);
6631 for (i = NOPTS - 1; i >= 0; i--) {
6633 USTPUTC(optletters(i), expdest);
6639 /* handles cases similar to ${#$1} */
6640 if (name[2] != '\0')
6641 raise_error_syntax("bad substitution");
6654 sep |= ifsset() ? ifsval()[0] : ' ';
6661 while ((p = *ap++) != NULL) {
6662 len += strtodest(p, syntax, quotes);
6666 memtodest(&sepc, 1, syntax, quotes);
6681 num = atoi(name); /* number(name) fails on ${N#str} etc */
6682 if (num < 0 || num > shellparam.nparam)
6684 p = num ? shellparam.p[num - 1] : arg0;
6687 /* NB: name has form "VAR=..." */
6689 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6690 * which should be considered before we check variables. */
6692 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6696 str = var_str_list->text;
6697 eq = strchr(str, '=');
6698 if (!eq) /* stop at first non-assignment */
6701 if (name_len == (unsigned)(eq - str)
6702 && strncmp(str, name, name_len) == 0
6705 /* goto value; - WRONG! */
6706 /* think "A=1 A=2 B=$A" */
6708 var_str_list = var_str_list->next;
6709 } while (var_str_list);
6713 p = lookupvar(name);
6718 len = strtodest(p, syntax, quotes);
6719 #if ENABLE_UNICODE_SUPPORT
6720 if (subtype == VSLENGTH && len > 0) {
6721 reinit_unicode_for_ash();
6722 if (unicode_status == UNICODE_ON) {
6723 STADJUST(-len, expdest);
6725 len = unicode_strlen(p);
6733 STADJUST(-len, expdest);
6738 * Expand a variable, and return a pointer to the next character in the
6742 evalvar(char *p, int flag, struct strlist *var_str_list)
6753 varflags = (unsigned char) *p++;
6754 subtype = varflags & VSTYPE;
6757 raise_error_syntax("bad substitution");
6759 quoted = flag & EXP_QUOTED;
6761 easy = (!quoted || (*var == '@' && shellparam.nparam));
6762 startloc = expdest - (char *)stackblock();
6763 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6766 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6767 if (varflags & VSNUL)
6770 if (subtype == VSPLUS) {
6771 varlen = -1 - varlen;
6775 if (subtype == VSMINUS) {
6780 flag | EXP_TILDE | EXP_WORD,
6788 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6792 subevalvar(p, var, 0, subtype, startloc, varflags,
6793 flag & ~QUOTES_ESC, var_str_list);
6796 * Remove any recorded regions beyond
6799 removerecordregions(startloc);
6803 if (varlen < 0 && uflag)
6804 varunset(p, var, 0, 0);
6806 if (subtype == VSLENGTH) {
6807 cvtnum(varlen > 0 ? varlen : 0);
6811 if (subtype == VSNORMAL) {
6815 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6824 case VSTRIMRIGHTMAX:
6825 #if ENABLE_ASH_BASH_COMPAT
6838 * Terminate the string and start recording the pattern
6841 STPUTC('\0', expdest);
6842 patloc = expdest - (char *)stackblock();
6843 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6844 startloc, varflags, flag, var_str_list)) {
6845 int amount = expdest - (
6846 (char *)stackblock() + patloc - 1
6848 STADJUST(-amount, expdest);
6850 /* Remove any recorded regions beyond start of variable */
6851 removerecordregions(startloc);
6856 if (subtype != VSNORMAL) { /* skip to end of alternative */
6859 unsigned char c = *p++;
6862 else if (c == CTLBACKQ) {
6864 argbackq = argbackq->next;
6865 } else if (c == CTLVAR) {
6866 if ((*p++ & VSTYPE) != VSNORMAL)
6868 } else if (c == CTLENDVAR) {
6878 * Break the argument string into pieces based upon IFS and add the
6879 * strings to the argument list. The regions of the string to be
6880 * searched for IFS characters have been stored by recordregion.
6883 ifsbreakup(char *string, struct arglist *arglist)
6885 struct ifsregion *ifsp;
6890 const char *ifs, *realifs;
6895 if (ifslastp != NULL) {
6898 realifs = ifsset() ? ifsval() : defifs;
6901 p = string + ifsp->begoff;
6902 nulonly = ifsp->nulonly;
6903 ifs = nulonly ? nullstr : realifs;
6905 while (p < string + ifsp->endoff) {
6907 if ((unsigned char)*p == CTLESC)
6909 if (!strchr(ifs, *p)) {
6914 ifsspc = (strchr(defifs, *p) != NULL);
6915 /* Ignore IFS whitespace at start */
6916 if (q == start && ifsspc) {
6922 sp = stzalloc(sizeof(*sp));
6924 *arglist->lastp = sp;
6925 arglist->lastp = &sp->next;
6929 if (p >= string + ifsp->endoff) {
6933 if ((unsigned char)*p == CTLESC)
6935 if (strchr(ifs, *p) == NULL) {
6939 if (strchr(defifs, *p) == NULL) {
6954 } while (ifsp != NULL);
6963 sp = stzalloc(sizeof(*sp));
6965 *arglist->lastp = sp;
6966 arglist->lastp = &sp->next;
6972 struct ifsregion *p;
6977 struct ifsregion *ifsp;
6983 ifsfirst.next = NULL;
6988 * Add a file name to the list.
6991 addfname(const char *name)
6995 sp = stzalloc(sizeof(*sp));
6996 sp->text = sstrdup(name);
6998 exparg.lastp = &sp->next;
7001 /* If we want to use glob() from libc... */
7002 #if !ENABLE_ASH_INTERNAL_GLOB
7004 /* Add the result of glob() to the list */
7006 addglob(const glob_t *pglob)
7008 char **p = pglob->gl_pathv;
7015 expandmeta(struct strlist *str /*, int flag*/)
7017 /* TODO - EXP_REDIR */
7027 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7028 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7029 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7031 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7032 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7033 // Which means you need to unescape the string, right? Not so fast:
7034 // if there _is_ a file named "file\?" (with backslash), it is returned
7035 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7036 // You DONT KNOW by looking at the result whether you need to unescape it.
7038 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7039 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7040 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7041 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7042 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7043 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7044 i = glob(p, 0, NULL, &pglob);
7045 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7050 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7051 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7052 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7064 *exparg.lastp = str;
7065 rmescapes(str->text, 0);
7066 exparg.lastp = &str->next;
7068 default: /* GLOB_NOSPACE */
7071 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7078 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7081 * Do metacharacter (i.e. *, ?, [...]) expansion.
7084 expmeta(char *expdir, char *enddir, char *name)
7100 for (p = name; esc = 0, *p; p += esc + 1) {
7101 if (*p == '*' || *p == '?')
7103 else if (*p == '[') {
7110 if (*q == '/' || *q == '\0')
7120 if (p[esc] == '/') {
7123 start = p + esc + 1;
7127 if (metaflag == 0) { /* we've reached the end of the file name */
7128 if (enddir != expdir)
7136 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7147 } while (p < start);
7149 if (enddir == expdir) {
7151 } else if (enddir == expdir + 1 && *expdir == '/') {
7160 if (enddir != expdir)
7162 if (*endname == 0) {
7175 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7176 if (dp->d_name[0] == '.' && !matchdot)
7178 if (pmatch(start, dp->d_name)) {
7180 strcpy(enddir, dp->d_name);
7183 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7186 expmeta(expdir, p, endname);
7192 endname[-esc - 1] = esc ? '\\' : '/';
7195 static struct strlist *
7196 msort(struct strlist *list, int len)
7198 struct strlist *p, *q = NULL;
7199 struct strlist **lpp;
7207 for (n = half; --n >= 0;) {
7211 q->next = NULL; /* terminate first half of list */
7212 q = msort(list, half); /* sort first half of list */
7213 p = msort(p, len - half); /* sort second half */
7216 #if ENABLE_LOCALE_SUPPORT
7217 if (strcoll(p->text, q->text) < 0)
7219 if (strcmp(p->text, q->text) < 0)
7243 * Sort the results of file name expansion. It calculates the number of
7244 * strings to sort and then calls msort (short for merge sort) to do the
7247 static struct strlist *
7248 expsort(struct strlist *str)
7254 for (sp = str; sp; sp = sp->next)
7256 return msort(str, len);
7260 expandmeta(struct strlist *str /*, int flag*/)
7262 static const char metachars[] ALIGN1 = {
7265 /* TODO - EXP_REDIR */
7269 struct strlist **savelastp;
7275 if (!strpbrk(str->text, metachars))
7277 savelastp = exparg.lastp;
7280 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7282 int i = strlen(str->text);
7283 //BUGGY estimation of how long expanded name can be
7284 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7286 expmeta(expdir, expdir, p);
7291 if (exparg.lastp == savelastp) {
7296 *exparg.lastp = str;
7297 rmescapes(str->text, 0);
7298 exparg.lastp = &str->next;
7300 *exparg.lastp = NULL;
7301 *savelastp = sp = expsort(*savelastp);
7302 while (sp->next != NULL)
7304 exparg.lastp = &sp->next;
7309 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7312 * Perform variable substitution and command substitution on an argument,
7313 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7314 * perform splitting and file name expansion. When arglist is NULL, perform
7315 * here document expansion.
7318 expandarg(union node *arg, struct arglist *arglist, int flag)
7323 argbackq = arg->narg.backquote;
7324 STARTSTACKSTR(expdest);
7325 ifsfirst.next = NULL;
7327 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7328 argstr(arg->narg.text, flag,
7329 /* var_str_list: */ arglist ? arglist->list : NULL);
7330 p = _STPUTC('\0', expdest);
7332 if (arglist == NULL) {
7333 return; /* here document expanded */
7335 p = grabstackstr(p);
7336 TRACE(("expandarg: p:'%s'\n", p));
7337 exparg.lastp = &exparg.list;
7341 if (flag & EXP_FULL) {
7342 ifsbreakup(p, &exparg);
7343 *exparg.lastp = NULL;
7344 exparg.lastp = &exparg.list;
7345 expandmeta(exparg.list /*, flag*/);
7347 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7349 TRACE(("expandarg: rmescapes:'%s'\n", p));
7351 sp = stzalloc(sizeof(*sp));
7354 exparg.lastp = &sp->next;
7358 *exparg.lastp = NULL;
7360 *arglist->lastp = exparg.list;
7361 arglist->lastp = exparg.lastp;
7366 * Expand shell variables and backquotes inside a here document.
7369 expandhere(union node *arg, int fd)
7371 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7372 full_write(fd, stackblock(), expdest - (char *)stackblock());
7376 * Returns true if the pattern matches the string.
7379 patmatch(char *pattern, const char *string)
7381 return pmatch(preglob(pattern, 0), string);
7385 * See if a pattern matches in a case statement.
7388 casematch(union node *pattern, char *val)
7390 struct stackmark smark;
7393 setstackmark(&smark);
7394 argbackq = pattern->narg.backquote;
7395 STARTSTACKSTR(expdest);
7397 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7398 /* var_str_list: */ NULL);
7399 STACKSTRNUL(expdest);
7400 result = patmatch(stackblock(), val);
7401 popstackmark(&smark);
7406 /* ============ find_command */
7410 int (*builtin)(int, char **) FAST_FUNC;
7411 /* unsigned flags; */
7413 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7414 /* "regular" builtins always take precedence over commands,
7415 * regardless of PATH=....%builtin... position */
7416 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7417 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7420 smallint cmdtype; /* CMDxxx */
7423 /* index >= 0 for commands without path (slashes) */
7424 /* (TODO: what exactly does the value mean? PATH position?) */
7425 /* index == -1 for commands with slashes */
7426 /* index == (-2 - applet_no) for NOFORK applets */
7427 const struct builtincmd *cmd;
7428 struct funcnode *func;
7431 /* values of cmdtype */
7432 #define CMDUNKNOWN -1 /* no entry in table for command */
7433 #define CMDNORMAL 0 /* command is an executable program */
7434 #define CMDFUNCTION 1 /* command is a shell function */
7435 #define CMDBUILTIN 2 /* command is a shell builtin */
7437 /* action to find_command() */
7438 #define DO_ERR 0x01 /* prints errors */
7439 #define DO_ABS 0x02 /* checks absolute paths */
7440 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7441 #define DO_ALTPATH 0x08 /* using alternate path */
7442 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7444 static void find_command(char *, struct cmdentry *, int, const char *);
7447 /* ============ Hashing commands */
7450 * When commands are first encountered, they are entered in a hash table.
7451 * This ensures that a full path search will not have to be done for them
7452 * on each invocation.
7454 * We should investigate converting to a linear search, even though that
7455 * would make the command name "hash" a misnomer.
7459 struct tblentry *next; /* next entry in hash chain */
7460 union param param; /* definition of builtin function */
7461 smallint cmdtype; /* CMDxxx */
7462 char rehash; /* if set, cd done since entry created */
7463 char cmdname[1]; /* name of command */
7466 static struct tblentry **cmdtable;
7467 #define INIT_G_cmdtable() do { \
7468 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7471 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7475 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7477 #if ENABLE_FEATURE_SH_STANDALONE
7478 if (applet_no >= 0) {
7479 if (APPLET_IS_NOEXEC(applet_no)) {
7483 run_applet_no_and_exit(applet_no, argv);
7485 /* re-exec ourselves with the new arguments */
7486 execve(bb_busybox_exec_path, argv, envp);
7487 /* If they called chroot or otherwise made the binary no longer
7488 * executable, fall through */
7495 execve(cmd, argv, envp);
7496 } while (errno == EINTR);
7498 execve(cmd, argv, envp);
7500 if (cmd == (char*) bb_busybox_exec_path) {
7501 /* We already visited ENOEXEC branch below, don't do it again */
7502 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7506 if (errno == ENOEXEC) {
7507 /* Run "cmd" as a shell script:
7508 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7509 * "If the execve() function fails with ENOEXEC, the shell
7510 * shall execute a command equivalent to having a shell invoked
7511 * with the command name as its first operand,
7512 * with any remaining arguments passed to the new shell"
7514 * That is, do not use $SHELL, user's shell, or /bin/sh;
7515 * just call ourselves.
7517 * Note that bash reads ~80 chars of the file, and if it sees
7518 * a zero byte before it sees newline, it doesn't try to
7519 * interpret it, but fails with "cannot execute binary file"
7520 * message and exit code 126. For one, this prevents attempts
7521 * to interpret foreign ELF binaries as shell scripts.
7526 for (ap = argv; *ap; ap++)
7528 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7529 new[0] = (char*) "ash";
7532 while ((*ap++ = *++argv) != NULL)
7534 cmd = (char*) bb_busybox_exec_path;
7541 * Exec a program. Never returns. If you change this routine, you may
7542 * have to change the find_command routine as well.
7544 static void shellexec(char **, const char *, int) NORETURN;
7546 shellexec(char **argv, const char *path, int idx)
7552 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7554 clearredir(/*drop:*/ 1);
7555 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7556 if (strchr(argv[0], '/') != NULL
7557 #if ENABLE_FEATURE_SH_STANDALONE
7558 || (applet_no = find_applet_by_name(argv[0])) >= 0
7561 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7562 if (applet_no >= 0) {
7563 /* We tried execing ourself, but it didn't work.
7564 * Maybe /proc/self/exe doesn't exist?
7573 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7574 if (--idx < 0 && pathopt == NULL) {
7575 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7576 if (errno != ENOENT && errno != ENOTDIR)
7583 /* Map to POSIX errors */
7595 exitstatus = exerrno;
7596 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7597 argv[0], e, suppress_int));
7598 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7603 printentry(struct tblentry *cmdp)
7609 idx = cmdp->param.index;
7612 name = path_advance(&path, cmdp->cmdname);
7614 } while (--idx >= 0);
7615 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7619 * Clear out command entries. The argument specifies the first entry in
7620 * PATH which has changed.
7623 clearcmdentry(int firstchange)
7625 struct tblentry **tblp;
7626 struct tblentry **pp;
7627 struct tblentry *cmdp;
7630 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7632 while ((cmdp = *pp) != NULL) {
7633 if ((cmdp->cmdtype == CMDNORMAL &&
7634 cmdp->param.index >= firstchange)
7635 || (cmdp->cmdtype == CMDBUILTIN &&
7636 builtinloc >= firstchange)
7649 * Locate a command in the command hash table. If "add" is nonzero,
7650 * add the command to the table if it is not already present. The
7651 * variable "lastcmdentry" is set to point to the address of the link
7652 * pointing to the entry, so that delete_cmd_entry can delete the
7655 * Interrupts must be off if called with add != 0.
7657 static struct tblentry **lastcmdentry;
7659 static struct tblentry *
7660 cmdlookup(const char *name, int add)
7662 unsigned int hashval;
7664 struct tblentry *cmdp;
7665 struct tblentry **pp;
7668 hashval = (unsigned char)*p << 4;
7670 hashval += (unsigned char)*p++;
7672 pp = &cmdtable[hashval % CMDTABLESIZE];
7673 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7674 if (strcmp(cmdp->cmdname, name) == 0)
7678 if (add && cmdp == NULL) {
7679 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7681 /* + 1 - already done because
7682 * tblentry::cmdname is char[1] */);
7683 /*cmdp->next = NULL; - ckzalloc did it */
7684 cmdp->cmdtype = CMDUNKNOWN;
7685 strcpy(cmdp->cmdname, name);
7692 * Delete the command entry returned on the last lookup.
7695 delete_cmd_entry(void)
7697 struct tblentry *cmdp;
7700 cmdp = *lastcmdentry;
7701 *lastcmdentry = cmdp->next;
7702 if (cmdp->cmdtype == CMDFUNCTION)
7703 freefunc(cmdp->param.func);
7709 * Add a new command entry, replacing any existing command entry for
7710 * the same name - except special builtins.
7713 addcmdentry(char *name, struct cmdentry *entry)
7715 struct tblentry *cmdp;
7717 cmdp = cmdlookup(name, 1);
7718 if (cmdp->cmdtype == CMDFUNCTION) {
7719 freefunc(cmdp->param.func);
7721 cmdp->cmdtype = entry->cmdtype;
7722 cmdp->param = entry->u;
7726 static int FAST_FUNC
7727 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7729 struct tblentry **pp;
7730 struct tblentry *cmdp;
7732 struct cmdentry entry;
7735 if (nextopt("r") != '\0') {
7740 if (*argptr == NULL) {
7741 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7742 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7743 if (cmdp->cmdtype == CMDNORMAL)
7751 while ((name = *argptr) != NULL) {
7752 cmdp = cmdlookup(name, 0);
7754 && (cmdp->cmdtype == CMDNORMAL
7755 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7759 find_command(name, &entry, DO_ERR, pathval());
7760 if (entry.cmdtype == CMDUNKNOWN)
7768 * Called when a cd is done. Marks all commands so the next time they
7769 * are executed they will be rehashed.
7774 struct tblentry **pp;
7775 struct tblentry *cmdp;
7777 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7778 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7779 if (cmdp->cmdtype == CMDNORMAL
7780 || (cmdp->cmdtype == CMDBUILTIN
7781 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7791 * Fix command hash table when PATH changed.
7792 * Called before PATH is changed. The argument is the new value of PATH;
7793 * pathval() still returns the old value at this point.
7794 * Called with interrupts off.
7796 static void FAST_FUNC
7797 changepath(const char *new)
7805 firstchange = 9999; /* assume no change */
7811 if ((*old == '\0' && *new == ':')
7812 || (*old == ':' && *new == '\0')
7816 old = new; /* ignore subsequent differences */
7820 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7827 if (builtinloc < 0 && idx_bltin >= 0)
7828 builtinloc = idx_bltin; /* zap builtins */
7829 if (builtinloc >= 0 && idx_bltin < 0)
7831 clearcmdentry(firstchange);
7832 builtinloc = idx_bltin;
7857 #if ENABLE_ASH_BASH_COMPAT
7868 typedef smallint token_id_t;
7870 /* Nth bit indicates if token marks the end of a list */
7873 /* 0 */ | (1u << TEOF)
7874 /* 1 */ | (0u << TNL)
7875 /* 2 */ | (0u << TREDIR)
7876 /* 3 */ | (0u << TWORD)
7877 /* 4 */ | (0u << TSEMI)
7878 /* 5 */ | (0u << TBACKGND)
7879 /* 6 */ | (0u << TAND)
7880 /* 7 */ | (0u << TOR)
7881 /* 8 */ | (0u << TPIPE)
7882 /* 9 */ | (0u << TLP)
7883 /* 10 */ | (1u << TRP)
7884 /* 11 */ | (1u << TENDCASE)
7885 /* 12 */ | (1u << TENDBQUOTE)
7886 /* 13 */ | (0u << TNOT)
7887 /* 14 */ | (0u << TCASE)
7888 /* 15 */ | (1u << TDO)
7889 /* 16 */ | (1u << TDONE)
7890 /* 17 */ | (1u << TELIF)
7891 /* 18 */ | (1u << TELSE)
7892 /* 19 */ | (1u << TESAC)
7893 /* 20 */ | (1u << TFI)
7894 /* 21 */ | (0u << TFOR)
7895 #if ENABLE_ASH_BASH_COMPAT
7896 /* 22 */ | (0u << TFUNCTION)
7898 /* 23 */ | (0u << TIF)
7899 /* 24 */ | (0u << TIN)
7900 /* 25 */ | (1u << TTHEN)
7901 /* 26 */ | (0u << TUNTIL)
7902 /* 27 */ | (0u << TWHILE)
7903 /* 28 */ | (0u << TBEGIN)
7904 /* 29 */ | (1u << TEND)
7905 , /* thus far 29 bits used */
7908 static const char *const tokname_array[] = {
7922 #define KWDOFFSET 13
7923 /* the following are keywords */
7933 #if ENABLE_ASH_BASH_COMPAT
7945 /* Wrapper around strcmp for qsort/bsearch/... */
7947 pstrcmp(const void *a, const void *b)
7949 return strcmp((char*)a, *(char**)b);
7952 static const char *const *
7953 findkwd(const char *s)
7955 return bsearch(s, tokname_array + KWDOFFSET,
7956 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7957 sizeof(tokname_array[0]), pstrcmp);
7961 * Locate and print what a word is...
7964 describe_command(char *command, const char *path, int describe_command_verbose)
7966 struct cmdentry entry;
7967 struct tblentry *cmdp;
7968 #if ENABLE_ASH_ALIAS
7969 const struct alias *ap;
7972 path = path ? path : pathval();
7974 if (describe_command_verbose) {
7978 /* First look at the keywords */
7979 if (findkwd(command)) {
7980 out1str(describe_command_verbose ? " is a shell keyword" : command);
7984 #if ENABLE_ASH_ALIAS
7985 /* Then look at the aliases */
7986 ap = lookupalias(command, 0);
7988 if (!describe_command_verbose) {
7993 out1fmt(" is an alias for %s", ap->val);
7997 /* Then check if it is a tracked alias */
7998 cmdp = cmdlookup(command, 0);
8000 entry.cmdtype = cmdp->cmdtype;
8001 entry.u = cmdp->param;
8003 /* Finally use brute force */
8004 find_command(command, &entry, DO_ABS, path);
8007 switch (entry.cmdtype) {
8009 int j = entry.u.index;
8015 p = path_advance(&path, command);
8019 if (describe_command_verbose) {
8021 (cmdp ? " a tracked alias for" : nullstr), p
8030 if (describe_command_verbose) {
8031 out1str(" is a shell function");
8038 if (describe_command_verbose) {
8039 out1fmt(" is a %sshell builtin",
8040 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8041 "special " : nullstr
8049 if (describe_command_verbose) {
8050 out1str(": not found\n");
8059 static int FAST_FUNC
8060 typecmd(int argc UNUSED_PARAM, char **argv)
8066 /* type -p ... ? (we don't bother checking for 'p') */
8067 if (argv[1] && argv[1][0] == '-') {
8072 err |= describe_command(argv[i++], NULL, verbose);
8077 #if ENABLE_ASH_CMDCMD
8078 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8080 parse_command_args(char **argv, const char **path)
8093 if (c == '-' && !*cp) {
8101 *path = bb_default_path;
8104 /* run 'typecmd' for other options */
8113 static int FAST_FUNC
8114 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8122 const char *path = NULL;
8124 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8125 * never reaches this function.
8128 while ((c = nextopt("pvV")) != '\0')
8130 verify |= VERIFY_VERBOSE;
8132 /*verify |= VERIFY_BRIEF*/;
8138 path = bb_default_path;
8140 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8142 if (/*verify && */ cmd)
8143 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8150 /*static int funcblocksize; // size of structures in function */
8151 /*static int funcstringsize; // size of strings in node */
8152 static void *funcblock; /* block to allocate function from */
8153 static char *funcstring_end; /* end of block to allocate strings from */
8155 /* flags in argument to evaltree */
8156 #define EV_EXIT 01 /* exit after evaluating tree */
8157 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8159 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8160 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8161 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8162 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8163 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8164 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8165 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8166 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8167 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8168 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8169 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8170 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8171 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8172 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8173 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8174 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8175 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8176 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8177 #if ENABLE_ASH_BASH_COMPAT
8178 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8180 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8181 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8182 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8183 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8184 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8185 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8186 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8187 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8188 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8191 static int calcsize(int funcblocksize, union node *n);
8194 sizenodelist(int funcblocksize, struct nodelist *lp)
8197 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8198 funcblocksize = calcsize(funcblocksize, lp->n);
8201 return funcblocksize;
8205 calcsize(int funcblocksize, union node *n)
8208 return funcblocksize;
8209 funcblocksize += nodesize[n->type];
8212 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8213 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8214 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8217 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8222 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8223 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8230 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8231 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8234 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8235 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8236 funcblocksize = calcsize(funcblocksize, n->nif.test);
8239 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8240 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8241 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8244 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8245 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8248 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8249 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8250 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8254 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8255 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8256 funcblocksize = calcsize(funcblocksize, n->narg.next);
8259 #if ENABLE_ASH_BASH_COMPAT
8266 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8267 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8271 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8272 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8276 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8277 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8280 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8283 return funcblocksize;
8287 nodeckstrdup(char *s)
8289 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8290 return strcpy(funcstring_end, s);
8293 static union node *copynode(union node *);
8295 static struct nodelist *
8296 copynodelist(struct nodelist *lp)
8298 struct nodelist *start;
8299 struct nodelist **lpp;
8304 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8305 (*lpp)->n = copynode(lp->n);
8307 lpp = &(*lpp)->next;
8314 copynode(union node *n)
8321 funcblock = (char *) funcblock + nodesize[n->type];
8325 new->ncmd.redirect = copynode(n->ncmd.redirect);
8326 new->ncmd.args = copynode(n->ncmd.args);
8327 new->ncmd.assign = copynode(n->ncmd.assign);
8330 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8331 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8336 new->nredir.redirect = copynode(n->nredir.redirect);
8337 new->nredir.n = copynode(n->nredir.n);
8344 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8345 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8348 new->nif.elsepart = copynode(n->nif.elsepart);
8349 new->nif.ifpart = copynode(n->nif.ifpart);
8350 new->nif.test = copynode(n->nif.test);
8353 new->nfor.var = nodeckstrdup(n->nfor.var);
8354 new->nfor.body = copynode(n->nfor.body);
8355 new->nfor.args = copynode(n->nfor.args);
8358 new->ncase.cases = copynode(n->ncase.cases);
8359 new->ncase.expr = copynode(n->ncase.expr);
8362 new->nclist.body = copynode(n->nclist.body);
8363 new->nclist.pattern = copynode(n->nclist.pattern);
8364 new->nclist.next = copynode(n->nclist.next);
8368 new->narg.backquote = copynodelist(n->narg.backquote);
8369 new->narg.text = nodeckstrdup(n->narg.text);
8370 new->narg.next = copynode(n->narg.next);
8373 #if ENABLE_ASH_BASH_COMPAT
8380 new->nfile.fname = copynode(n->nfile.fname);
8381 new->nfile.fd = n->nfile.fd;
8382 new->nfile.next = copynode(n->nfile.next);
8386 new->ndup.vname = copynode(n->ndup.vname);
8387 new->ndup.dupfd = n->ndup.dupfd;
8388 new->ndup.fd = n->ndup.fd;
8389 new->ndup.next = copynode(n->ndup.next);
8393 new->nhere.doc = copynode(n->nhere.doc);
8394 new->nhere.fd = n->nhere.fd;
8395 new->nhere.next = copynode(n->nhere.next);
8398 new->nnot.com = copynode(n->nnot.com);
8401 new->type = n->type;
8406 * Make a copy of a parse tree.
8408 static struct funcnode *
8409 copyfunc(union node *n)
8414 /*funcstringsize = 0;*/
8415 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8416 f = ckzalloc(blocksize /* + funcstringsize */);
8417 funcblock = (char *) f + offsetof(struct funcnode, n);
8418 funcstring_end = (char *) f + blocksize;
8420 /* f->count = 0; - ckzalloc did it */
8425 * Define a shell function.
8428 defun(union node *func)
8430 struct cmdentry entry;
8433 entry.cmdtype = CMDFUNCTION;
8434 entry.u.func = copyfunc(func);
8435 addcmdentry(func->narg.text, &entry);
8439 /* Reasons for skipping commands (see comment on breakcmd routine) */
8440 #define SKIPBREAK (1 << 0)
8441 #define SKIPCONT (1 << 1)
8442 #define SKIPFUNC (1 << 2)
8443 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8444 static int skipcount; /* number of levels to skip */
8445 static int funcnest; /* depth of function calls */
8446 static int loopnest; /* current loop nesting level */
8448 /* Forward decl way out to parsing code - dotrap needs it */
8449 static int evalstring(char *s, int flags);
8451 /* Called to execute a trap.
8452 * Single callsite - at the end of evaltree().
8453 * If we return non-zero, evaltree raises EXEXIT exception.
8455 * Perhaps we should avoid entering new trap handlers
8456 * while we are executing a trap handler. [is it a TODO?]
8463 uint8_t last_status;
8468 last_status = exitstatus;
8472 TRACE(("dotrap entered\n"));
8473 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8485 /* non-trapped SIGINT is handled separately by raise_interrupt,
8486 * don't upset it by resetting gotsig[SIGINT-1] */
8487 if (sig == SIGINT && !p)
8490 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8496 exitstatus = last_status;
8497 TRACE(("dotrap returns\n"));
8500 /* forward declarations - evaluation is fairly recursive business... */
8501 static int evalloop(union node *, int);
8502 static int evalfor(union node *, int);
8503 static int evalcase(union node *, int);
8504 static int evalsubshell(union node *, int);
8505 static void expredir(union node *);
8506 static int evalpipe(union node *, int);
8507 static int evalcommand(union node *, int);
8508 static int evalbltin(const struct builtincmd *, int, char **, int);
8509 static void prehash(union node *);
8512 * Evaluate a parse tree. The value is left in the global variable
8516 evaltree(union node *n, int flags)
8518 struct jmploc *volatile savehandler = exception_handler;
8519 struct jmploc jmploc;
8521 int (*evalfn)(union node *, int);
8525 SAVE_INT(int_level);
8528 TRACE(("evaltree(NULL) called\n"));
8531 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8535 exception_handler = &jmploc;
8537 int err = setjmp(jmploc.loc);
8539 /* if it was a signal, check for trap handlers */
8540 if (exception_type == EXSIG) {
8541 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8542 exception_type, err));
8545 /* continue on the way out */
8546 TRACE(("exception %d in evaltree, propagating err=%d\n",
8547 exception_type, err));
8548 exception_handler = savehandler;
8549 longjmp(exception_handler->loc, err);
8556 out1fmt("Node type = %d\n", n->type);
8561 status = !evaltree(n->nnot.com, EV_TESTED);
8564 expredir(n->nredir.redirect);
8565 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8567 status = evaltree(n->nredir.n, flags & EV_TESTED);
8569 if (n->nredir.redirect)
8570 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8573 evalfn = evalcommand;
8575 if (eflag && !(flags & EV_TESTED))
8587 evalfn = evalsubshell;
8600 #error NAND + 1 != NOR
8602 #if NOR + 1 != NSEMI
8603 #error NOR + 1 != NSEMI
8605 unsigned is_or = n->type - NAND;
8608 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8610 if ((!status) == is_or || evalskip)
8616 status = evalfn(n, flags);
8620 status = evaltree(n->nif.test, EV_TESTED);
8627 if (n->nif.elsepart) {
8628 n = n->nif.elsepart;
8635 /* Not necessary. To test it:
8636 * "false; f() { qwerty; }; echo $?" should print 0.
8640 exitstatus = status;
8645 exception_handler = savehandler;
8648 /* Order of checks below is important:
8649 * signal handlers trigger before exit caused by "set -e".
8653 if (checkexit & status)
8654 raise_exception(EXEXIT);
8655 if (flags & EV_EXIT)
8656 raise_exception(EXEXIT);
8658 RESTORE_INT(int_level);
8659 TRACE(("leaving evaltree (no interrupts)\n"));
8664 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8667 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8672 int skip = evalskip;
8679 if (--skipcount <= 0) {
8690 evalloop(union node *n, int flags)
8701 i = evaltree(n->nbinary.ch1, EV_TESTED);
8703 if (skip == SKIPFUNC)
8707 if (n->type != NWHILE)
8711 status = evaltree(n->nbinary.ch2, flags);
8713 } while (!(skip & ~SKIPCONT));
8720 evalfor(union node *n, int flags)
8722 struct arglist arglist;
8725 struct stackmark smark;
8728 setstackmark(&smark);
8729 arglist.list = NULL;
8730 arglist.lastp = &arglist.list;
8731 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8732 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8734 *arglist.lastp = NULL;
8738 for (sp = arglist.list; sp; sp = sp->next) {
8739 setvar0(n->nfor.var, sp->text);
8740 status = evaltree(n->nfor.body, flags);
8741 if (skiploop() & ~SKIPCONT)
8745 popstackmark(&smark);
8751 evalcase(union node *n, int flags)
8755 struct arglist arglist;
8756 struct stackmark smark;
8759 setstackmark(&smark);
8760 arglist.list = NULL;
8761 arglist.lastp = &arglist.list;
8762 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8763 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8764 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8765 if (casematch(patp, arglist.list->text)) {
8766 /* Ensure body is non-empty as otherwise
8767 * EV_EXIT may prevent us from setting the
8770 if (evalskip == 0 && cp->nclist.body) {
8771 status = evaltree(cp->nclist.body, flags);
8778 popstackmark(&smark);
8784 * Kick off a subshell to evaluate a tree.
8787 evalsubshell(union node *n, int flags)
8790 int backgnd = (n->type == NBACKGND);
8793 expredir(n->nredir.redirect);
8794 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8797 jp = makejob(/*n,*/ 1);
8798 if (forkshell(jp, n, backgnd) == 0) {
8803 flags &= ~EV_TESTED;
8805 redirect(n->nredir.redirect, 0);
8806 evaltreenr(n->nredir.n, flags);
8811 status = waitforjob(jp);
8817 * Compute the names of the files in a redirection list.
8819 static void fixredir(union node *, const char *, int);
8821 expredir(union node *n)
8825 for (redir = n; redir; redir = redir->nfile.next) {
8829 fn.lastp = &fn.list;
8830 switch (redir->type) {
8834 #if ENABLE_ASH_BASH_COMPAT
8839 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8840 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8841 #if ENABLE_ASH_BASH_COMPAT
8845 // By the design of stack allocator, the loop of this kind:
8846 // while true; do while true; do break; done </dev/null; done
8847 // will look like a memory leak: ash plans to free expfname's
8848 // of "/dev/null" as soon as it finishes running the loop
8849 // (in this case, never).
8850 // This "fix" is wrong:
8851 if (redir->nfile.expfname)
8852 stunalloc(redir->nfile.expfname);
8853 // It results in corrupted state of stacked allocations.
8855 redir->nfile.expfname = fn.list->text;
8858 case NTOFD: /* >& */
8859 if (redir->ndup.vname) {
8860 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8861 if (fn.list == NULL)
8862 ash_msg_and_raise_error("redir error");
8863 #if ENABLE_ASH_BASH_COMPAT
8864 //FIXME: we used expandarg with different args!
8865 if (!isdigit_str9(fn.list->text)) {
8866 /* >&file, not >&fd */
8867 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8868 ash_msg_and_raise_error("redir error");
8870 goto store_expfname;
8873 fixredir(redir, fn.list->text, 1);
8881 * Evaluate a pipeline. All the processes in the pipeline are children
8882 * of the process creating the pipeline. (This differs from some versions
8883 * of the shell, which make the last process in a pipeline the parent
8887 evalpipe(union node *n, int flags)
8890 struct nodelist *lp;
8896 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8898 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8902 jp = makejob(/*n,*/ pipelen);
8904 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8908 if (pipe(pip) < 0) {
8910 ash_msg_and_raise_error("pipe call failed");
8913 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8926 evaltreenr(lp->n, flags);
8932 /* Don't want to trigger debugging */
8936 if (n->npipe.pipe_backgnd == 0) {
8937 status = waitforjob(jp);
8938 TRACE(("evalpipe: job done exit status %d\n", status));
8946 * Controls whether the shell is interactive or not.
8949 setinteractive(int on)
8951 static smallint is_interactive;
8953 if (++on == is_interactive)
8955 is_interactive = on;
8959 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8960 if (is_interactive > 1) {
8961 /* Looks like they want an interactive shell */
8962 static smallint did_banner;
8965 /* note: ash and hush share this string */
8966 out1fmt("\n\n%s %s\n"
8967 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8970 "built-in shell (ash)"
8984 setinteractive(iflag);
8986 #if ENABLE_FEATURE_EDITING_VI
8988 line_input_state->flags |= VI_MODE;
8990 line_input_state->flags &= ~VI_MODE;
8992 viflag = 0; /* forcibly keep the option off */
8996 static struct localvar *localvars;
8999 * Called after a function returns.
9000 * Interrupts must be off.
9005 struct localvar *lvp;
9008 while ((lvp = localvars) != NULL) {
9009 localvars = lvp->next;
9011 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9012 if (vp == NULL) { /* $- saved */
9013 memcpy(optlist, lvp->text, sizeof(optlist));
9014 free((char*)lvp->text);
9016 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9017 unsetvar(vp->var_text);
9020 vp->var_func(var_end(lvp->text));
9021 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9022 free((char*)vp->var_text);
9023 vp->flags = lvp->flags;
9024 vp->var_text = lvp->text;
9031 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9033 volatile struct shparam saveparam;
9034 struct localvar *volatile savelocalvars;
9035 struct jmploc *volatile savehandler;
9036 struct jmploc jmploc;
9039 saveparam = shellparam;
9040 savelocalvars = localvars;
9041 savehandler = exception_handler;
9042 e = setjmp(jmploc.loc);
9047 exception_handler = &jmploc;
9049 shellparam.malloced = 0;
9053 shellparam.nparam = argc - 1;
9054 shellparam.p = argv + 1;
9055 #if ENABLE_ASH_GETOPTS
9056 shellparam.optind = 1;
9057 shellparam.optoff = -1;
9059 evaltree(func->n.narg.next, flags & EV_TESTED);
9065 localvars = savelocalvars;
9066 freeparam(&shellparam);
9067 shellparam = saveparam;
9068 exception_handler = savehandler;
9070 evalskip &= ~SKIPFUNC;
9075 * Make a variable a local variable. When a variable is made local, it's
9076 * value and flags are saved in a localvar structure. The saved values
9077 * will be restored when the shell function returns. We handle the name
9078 * "-" as a special case: it makes changes to "set +-options" local
9079 * (options will be restored on return from the function).
9084 struct localvar *lvp;
9087 char *eq = strchr(name, '=');
9090 /* Cater for duplicate "local". Examples:
9091 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9092 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9096 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9100 * it's a duplicate "local VAR" declaration, do nothing
9107 lvp = ckzalloc(sizeof(*lvp));
9108 if (LONE_DASH(name)) {
9110 p = ckmalloc(sizeof(optlist));
9111 lvp->text = memcpy(p, optlist, sizeof(optlist));
9114 vpp = hashvar(name);
9115 vp = *findvar(vpp, name);
9117 /* variable did not exist yet */
9119 setvareq(name, VSTRFIXED);
9121 setvar(name, NULL, VSTRFIXED);
9122 vp = *vpp; /* the new variable */
9123 lvp->flags = VUNSET;
9125 lvp->text = vp->var_text;
9126 lvp->flags = vp->flags;
9127 /* make sure neither "struct var" nor string gets freed
9128 * during (un)setting:
9130 vp->flags |= VSTRFIXED|VTEXTFIXED;
9134 /* "local VAR" unsets VAR: */
9135 setvar0(name, NULL);
9139 lvp->next = localvars;
9145 * The "local" command.
9147 static int FAST_FUNC
9148 localcmd(int argc UNUSED_PARAM, char **argv)
9153 ash_msg_and_raise_error("not in a function");
9156 while ((name = *argv++) != NULL) {
9162 static int FAST_FUNC
9163 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9168 static int FAST_FUNC
9169 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9174 static int FAST_FUNC
9175 execcmd(int argc UNUSED_PARAM, char **argv)
9178 iflag = 0; /* exit on error */
9181 /* We should set up signals for "exec CMD"
9182 * the same way as for "CMD" without "exec".
9183 * But optschanged->setinteractive->setsignal
9184 * still thought we are a root shell. Therefore, for example,
9185 * SIGQUIT is still set to IGN. Fix it:
9189 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9190 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9191 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9193 shellexec(argv + 1, pathval(), 0);
9200 * The return command.
9202 static int FAST_FUNC
9203 returncmd(int argc UNUSED_PARAM, char **argv)
9206 * If called outside a function, do what ksh does;
9207 * skip the rest of the file.
9209 evalskip = SKIPFUNC;
9210 return argv[1] ? number(argv[1]) : exitstatus;
9213 /* Forward declarations for builtintab[] */
9214 static int breakcmd(int, char **) FAST_FUNC;
9215 static int dotcmd(int, char **) FAST_FUNC;
9216 static int evalcmd(int, char **, int) FAST_FUNC;
9217 static int exitcmd(int, char **) FAST_FUNC;
9218 static int exportcmd(int, char **) FAST_FUNC;
9219 #if ENABLE_ASH_GETOPTS
9220 static int getoptscmd(int, char **) FAST_FUNC;
9223 static int helpcmd(int, char **) FAST_FUNC;
9226 static int historycmd(int, char **) FAST_FUNC;
9228 #if ENABLE_SH_MATH_SUPPORT
9229 static int letcmd(int, char **) FAST_FUNC;
9231 static int readcmd(int, char **) FAST_FUNC;
9232 static int setcmd(int, char **) FAST_FUNC;
9233 static int shiftcmd(int, char **) FAST_FUNC;
9234 static int timescmd(int, char **) FAST_FUNC;
9235 static int trapcmd(int, char **) FAST_FUNC;
9236 static int umaskcmd(int, char **) FAST_FUNC;
9237 static int unsetcmd(int, char **) FAST_FUNC;
9238 static int ulimitcmd(int, char **) FAST_FUNC;
9240 #define BUILTIN_NOSPEC "0"
9241 #define BUILTIN_SPECIAL "1"
9242 #define BUILTIN_REGULAR "2"
9243 #define BUILTIN_SPEC_REG "3"
9244 #define BUILTIN_ASSIGN "4"
9245 #define BUILTIN_SPEC_ASSG "5"
9246 #define BUILTIN_REG_ASSG "6"
9247 #define BUILTIN_SPEC_REG_ASSG "7"
9249 /* Stubs for calling non-FAST_FUNC's */
9250 #if ENABLE_ASH_BUILTIN_ECHO
9251 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9253 #if ENABLE_ASH_BUILTIN_PRINTF
9254 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9256 #if ENABLE_ASH_BUILTIN_TEST
9257 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9260 /* Keep these in proper order since it is searched via bsearch() */
9261 static const struct builtincmd builtintab[] = {
9262 { BUILTIN_SPEC_REG "." , dotcmd },
9263 { BUILTIN_SPEC_REG ":" , truecmd },
9264 #if ENABLE_ASH_BUILTIN_TEST
9265 { BUILTIN_REGULAR "[" , testcmd },
9266 #if ENABLE_ASH_BASH_COMPAT
9267 { BUILTIN_REGULAR "[[" , testcmd },
9270 #if ENABLE_ASH_ALIAS
9271 { BUILTIN_REG_ASSG "alias" , aliascmd },
9274 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9276 { BUILTIN_SPEC_REG "break" , breakcmd },
9277 { BUILTIN_REGULAR "cd" , cdcmd },
9278 { BUILTIN_NOSPEC "chdir" , cdcmd },
9279 #if ENABLE_ASH_CMDCMD
9280 { BUILTIN_REGULAR "command" , commandcmd },
9282 { BUILTIN_SPEC_REG "continue", breakcmd },
9283 #if ENABLE_ASH_BUILTIN_ECHO
9284 { BUILTIN_REGULAR "echo" , echocmd },
9286 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9287 { BUILTIN_SPEC_REG "exec" , execcmd },
9288 { BUILTIN_SPEC_REG "exit" , exitcmd },
9289 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9290 { BUILTIN_REGULAR "false" , falsecmd },
9292 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9294 #if ENABLE_ASH_GETOPTS
9295 { BUILTIN_REGULAR "getopts" , getoptscmd },
9297 { BUILTIN_NOSPEC "hash" , hashcmd },
9299 { BUILTIN_NOSPEC "help" , helpcmd },
9302 { BUILTIN_NOSPEC "history" , historycmd },
9305 { BUILTIN_REGULAR "jobs" , jobscmd },
9306 { BUILTIN_REGULAR "kill" , killcmd },
9308 #if ENABLE_SH_MATH_SUPPORT
9309 { BUILTIN_NOSPEC "let" , letcmd },
9311 { BUILTIN_ASSIGN "local" , localcmd },
9312 #if ENABLE_ASH_BUILTIN_PRINTF
9313 { BUILTIN_REGULAR "printf" , printfcmd },
9315 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9316 { BUILTIN_REGULAR "read" , readcmd },
9317 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9318 { BUILTIN_SPEC_REG "return" , returncmd },
9319 { BUILTIN_SPEC_REG "set" , setcmd },
9320 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9321 #if ENABLE_ASH_BASH_COMPAT
9322 { BUILTIN_SPEC_REG "source" , dotcmd },
9324 #if ENABLE_ASH_BUILTIN_TEST
9325 { BUILTIN_REGULAR "test" , testcmd },
9327 { BUILTIN_SPEC_REG "times" , timescmd },
9328 { BUILTIN_SPEC_REG "trap" , trapcmd },
9329 { BUILTIN_REGULAR "true" , truecmd },
9330 { BUILTIN_NOSPEC "type" , typecmd },
9331 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9332 { BUILTIN_REGULAR "umask" , umaskcmd },
9333 #if ENABLE_ASH_ALIAS
9334 { BUILTIN_REGULAR "unalias" , unaliascmd },
9336 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9337 { BUILTIN_REGULAR "wait" , waitcmd },
9340 /* Should match the above table! */
9341 #define COMMANDCMD (builtintab + \
9343 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9344 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9345 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9346 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9347 /* break cd cddir */ 3)
9348 #define EVALCMD (COMMANDCMD + \
9349 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9350 /* continue */ 1 + \
9351 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9353 #define EXECCMD (EVALCMD + \
9357 * Search the table of builtin commands.
9360 pstrcmp1(const void *a, const void *b)
9362 return strcmp((char*)a, *(char**)b + 1);
9364 static struct builtincmd *
9365 find_builtin(const char *name)
9367 struct builtincmd *bp;
9370 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9377 * Execute a simple command.
9380 isassignment(const char *p)
9382 const char *q = endofname(p);
9387 static int FAST_FUNC
9388 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9390 /* Preserve exitstatus of a previous possible redirection
9391 * as POSIX mandates */
9392 return back_exitstatus;
9395 evalcommand(union node *cmd, int flags)
9397 static const struct builtincmd null_bltin = {
9398 "\0\0", bltincmd /* why three NULs? */
9400 struct stackmark smark;
9402 struct arglist arglist;
9403 struct arglist varlist;
9406 const struct strlist *sp;
9407 struct cmdentry cmdentry;
9414 struct builtincmd *bcmd;
9415 smallint cmd_is_exec;
9416 smallint pseudovarflag = 0;
9418 /* First expand the arguments. */
9419 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9420 setstackmark(&smark);
9421 back_exitstatus = 0;
9423 cmdentry.cmdtype = CMDBUILTIN;
9424 cmdentry.u.cmd = &null_bltin;
9425 varlist.lastp = &varlist.list;
9426 *varlist.lastp = NULL;
9427 arglist.lastp = &arglist.list;
9428 *arglist.lastp = NULL;
9431 if (cmd->ncmd.args) {
9432 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9433 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9436 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9437 struct strlist **spp;
9439 spp = arglist.lastp;
9440 if (pseudovarflag && isassignment(argp->narg.text))
9441 expandarg(argp, &arglist, EXP_VARTILDE);
9443 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9445 for (sp = *spp; sp; sp = sp->next)
9449 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9450 for (sp = arglist.list; sp; sp = sp->next) {
9451 TRACE(("evalcommand arg: %s\n", sp->text));
9452 *nargv++ = sp->text;
9457 if (iflag && funcnest == 0 && argc > 0)
9458 lastarg = nargv[-1];
9461 expredir(cmd->ncmd.redirect);
9462 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9464 path = vpath.var_text;
9465 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9466 struct strlist **spp;
9469 spp = varlist.lastp;
9470 expandarg(argp, &varlist, EXP_VARTILDE);
9473 * Modify the command lookup path, if a PATH= assignment
9477 if (varcmp(p, path) == 0)
9481 /* Print the command if xflag is set. */
9484 const char *p = " %s" + 1;
9486 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9488 for (n = 0; n < 2; n++) {
9490 fdprintf(preverrout_fd, p, sp->text);
9496 safe_write(preverrout_fd, "\n", 1);
9502 /* Now locate the command. */
9504 int cmd_flag = DO_ERR;
9505 #if ENABLE_ASH_CMDCMD
9506 const char *oldpath = path + 5;
9510 find_command(argv[0], &cmdentry, cmd_flag, path);
9511 if (cmdentry.cmdtype == CMDUNKNOWN) {
9512 flush_stdout_stderr();
9517 /* implement bltin and command here */
9518 if (cmdentry.cmdtype != CMDBUILTIN)
9521 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9522 if (cmdentry.u.cmd == EXECCMD)
9524 #if ENABLE_ASH_CMDCMD
9525 if (cmdentry.u.cmd == COMMANDCMD) {
9527 nargv = parse_command_args(argv, &path);
9530 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9531 * nargv => "PROG". path is updated if -p.
9533 argc -= nargv - argv;
9535 cmd_flag |= DO_NOFUNC;
9543 /* We have a redirection error. */
9545 raise_exception(EXERROR);
9547 exitstatus = status;
9551 /* Execute the command. */
9552 switch (cmdentry.cmdtype) {
9555 #if ENABLE_FEATURE_SH_NOFORK
9556 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9557 * around run_nofork_applet() call.
9558 * (2) Should this check also be done in forkshell()?
9559 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9561 /* find_command() encodes applet_no as (-2 - applet_no) */
9562 int applet_no = (- cmdentry.u.index - 2);
9563 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9564 listsetvar(varlist.list, VEXPORT|VSTACK);
9565 /* run <applet>_main() */
9566 status = run_nofork_applet(applet_no, argv);
9570 /* Can we avoid forking off? For example, very last command
9571 * in a script or a subshell does not need forking,
9572 * we can just exec it.
9574 if (!(flags & EV_EXIT) || may_have_traps) {
9575 /* No, forking off a child is necessary */
9577 jp = makejob(/*cmd,*/ 1);
9578 if (forkshell(jp, cmd, FORK_FG) != 0) {
9580 status = waitforjob(jp);
9582 TRACE(("forked child exited with %d\n", status));
9587 /* fall through to exec'ing external program */
9589 listsetvar(varlist.list, VEXPORT|VSTACK);
9590 shellexec(argv, path, cmdentry.u.index);
9594 cmdenviron = varlist.list;
9596 struct strlist *list = cmdenviron;
9598 if (spclbltin > 0 || argc == 0) {
9600 if (cmd_is_exec && argc > 1)
9603 listsetvar(list, i);
9605 /* Tight loop with builtins only:
9606 * "while kill -0 $child; do true; done"
9607 * will never exit even if $child died, unless we do this
9608 * to reap the zombie and make kill detect that it's gone: */
9609 dowait(DOWAIT_NONBLOCK, NULL);
9611 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9613 int i = exception_type;
9618 exit_status = 128 + SIGINT;
9620 exit_status = 128 + pending_sig;
9621 exitstatus = exit_status;
9622 if (i == EXINT || spclbltin > 0) {
9624 longjmp(exception_handler->loc, 1);
9631 listsetvar(varlist.list, 0);
9632 /* See above for the rationale */
9633 dowait(DOWAIT_NONBLOCK, NULL);
9634 if (evalfun(cmdentry.u.func, argc, argv, flags))
9637 status = exitstatus;
9642 if (cmd->ncmd.redirect)
9643 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9645 /* dsl: I think this is intended to be used to support
9646 * '_' in 'vi' command mode during line editing...
9647 * However I implemented that within libedit itself.
9649 setvar0("_", lastarg);
9651 popstackmark(&smark);
9657 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9659 char *volatile savecmdname;
9660 struct jmploc *volatile savehandler;
9661 struct jmploc jmploc;
9665 savecmdname = commandname;
9666 savehandler = exception_handler;
9667 i = setjmp(jmploc.loc);
9670 exception_handler = &jmploc;
9671 commandname = argv[0];
9673 optptr = NULL; /* initialize nextopt */
9675 status = evalcmd(argc, argv, flags);
9677 status = (*cmd->builtin)(argc, argv);
9678 flush_stdout_stderr();
9679 status |= ferror(stdout);
9680 exitstatus = status;
9683 commandname = savecmdname;
9684 exception_handler = savehandler;
9690 goodname(const char *p)
9692 return endofname(p)[0] == '\0';
9697 * Search for a command. This is called before we fork so that the
9698 * location of the command will be available in the parent as well as
9699 * the child. The check for "goodname" is an overly conservative
9700 * check that the name will not be subject to expansion.
9703 prehash(union node *n)
9705 struct cmdentry entry;
9707 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9708 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9712 /* ============ Builtin commands
9714 * Builtin commands whose functions are closely tied to evaluation
9715 * are implemented here.
9719 * Handle break and continue commands. Break, continue, and return are
9720 * all handled by setting the evalskip flag. The evaluation routines
9721 * above all check this flag, and if it is set they start skipping
9722 * commands rather than executing them. The variable skipcount is
9723 * the number of loops to break/continue, or the number of function
9724 * levels to return. (The latter is always 1.) It should probably
9725 * be an error to break out of more loops than exist, but it isn't
9726 * in the standard shell so we don't make it one here.
9728 static int FAST_FUNC
9729 breakcmd(int argc UNUSED_PARAM, char **argv)
9731 int n = argv[1] ? number(argv[1]) : 1;
9734 ash_msg_and_raise_error(msg_illnum, argv[1]);
9738 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9745 /* ============ input.c
9747 * This implements the input routines used by the parser.
9751 INPUT_PUSH_FILE = 1,
9752 INPUT_NOFILE_OK = 2,
9755 static smallint checkkwd;
9756 /* values of checkkwd variable */
9757 #define CHKALIAS 0x1
9762 * Push a string back onto the input at this current parsefile level.
9763 * We handle aliases this way.
9765 #if !ENABLE_ASH_ALIAS
9766 #define pushstring(s, ap) pushstring(s)
9769 pushstring(char *s, struct alias *ap)
9776 if (g_parsefile->strpush) {
9777 sp = ckzalloc(sizeof(*sp));
9778 sp->prev = g_parsefile->strpush;
9780 sp = &(g_parsefile->basestrpush);
9782 g_parsefile->strpush = sp;
9783 sp->prev_string = g_parsefile->next_to_pgetc;
9784 sp->prev_left_in_line = g_parsefile->left_in_line;
9785 sp->unget = g_parsefile->unget;
9786 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9787 #if ENABLE_ASH_ALIAS
9790 ap->flag |= ALIASINUSE;
9794 g_parsefile->next_to_pgetc = s;
9795 g_parsefile->left_in_line = len;
9796 g_parsefile->unget = 0;
9803 struct strpush *sp = g_parsefile->strpush;
9806 #if ENABLE_ASH_ALIAS
9808 if (g_parsefile->next_to_pgetc[-1] == ' '
9809 || g_parsefile->next_to_pgetc[-1] == '\t'
9811 checkkwd |= CHKALIAS;
9813 if (sp->string != sp->ap->val) {
9816 sp->ap->flag &= ~ALIASINUSE;
9817 if (sp->ap->flag & ALIASDEAD) {
9818 unalias(sp->ap->name);
9822 g_parsefile->next_to_pgetc = sp->prev_string;
9823 g_parsefile->left_in_line = sp->prev_left_in_line;
9824 g_parsefile->unget = sp->unget;
9825 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9826 g_parsefile->strpush = sp->prev;
9827 if (sp != &(g_parsefile->basestrpush))
9836 char *buf = g_parsefile->buf;
9838 g_parsefile->next_to_pgetc = buf;
9839 #if ENABLE_FEATURE_EDITING
9841 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9842 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9845 # if ENABLE_ASH_IDLE_TIMEOUT
9847 const char *tmout_var = lookupvar("TMOUT");
9849 timeout = atoi(tmout_var) * 1000;
9855 # if ENABLE_FEATURE_TAB_COMPLETION
9856 line_input_state->path_lookup = pathval();
9858 reinit_unicode_for_ash();
9859 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9861 /* Ctrl+C pressed */
9872 /* Ctrl+D pressed */
9875 # if ENABLE_ASH_IDLE_TIMEOUT
9876 else if (errno == EAGAIN && timeout > 0) {
9877 puts("\007timed out waiting for input: auto-logout");
9884 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9887 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9889 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9890 int flags = fcntl(0, F_GETFL);
9891 if (flags >= 0 && (flags & O_NONBLOCK)) {
9892 flags &= ~O_NONBLOCK;
9893 if (fcntl(0, F_SETFL, flags) >= 0) {
9894 out2str("sh: turning off NDELAY mode\n");
9905 * Refill the input buffer and return the next input character:
9907 * 1) If a string was pushed back on the input, pop it;
9908 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9909 * or we are reading from a string so we can't refill the buffer,
9911 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9912 * 4) Process input up to the next newline, deleting nul characters.
9914 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9915 #define pgetc_debug(...) ((void)0)
9916 static int pgetc(void);
9923 if (g_parsefile->strpush) {
9924 #if ENABLE_ASH_ALIAS
9925 if (g_parsefile->left_in_line == -1
9926 && g_parsefile->strpush->ap
9927 && g_parsefile->next_to_pgetc[-1] != ' '
9928 && g_parsefile->next_to_pgetc[-1] != '\t'
9930 pgetc_debug("preadbuffer PEOA");
9937 /* on both branches above g_parsefile->left_in_line < 0.
9938 * "pgetc" needs refilling.
9941 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9942 * pungetc() may increment it a few times.
9943 * Assuming it won't increment it to less than -90.
9945 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9946 pgetc_debug("preadbuffer PEOF1");
9947 /* even in failure keep left_in_line and next_to_pgetc
9948 * in lock step, for correct multi-layer pungetc.
9949 * left_in_line was decremented before preadbuffer(),
9950 * must inc next_to_pgetc: */
9951 g_parsefile->next_to_pgetc++;
9955 more = g_parsefile->left_in_buffer;
9957 flush_stdout_stderr();
9961 /* don't try reading again */
9962 g_parsefile->left_in_line = -99;
9963 pgetc_debug("preadbuffer PEOF2");
9964 g_parsefile->next_to_pgetc++;
9969 /* Find out where's the end of line.
9970 * Set g_parsefile->left_in_line
9971 * and g_parsefile->left_in_buffer acordingly.
9972 * NUL chars are deleted.
9974 q = g_parsefile->next_to_pgetc;
9982 memmove(q, q + 1, more);
9986 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9992 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9993 if (g_parsefile->left_in_line < 0)
9998 g_parsefile->left_in_buffer = more;
10003 out2str(g_parsefile->next_to_pgetc);
10007 pgetc_debug("preadbuffer at %d:%p'%s'",
10008 g_parsefile->left_in_line,
10009 g_parsefile->next_to_pgetc,
10010 g_parsefile->next_to_pgetc);
10011 return (unsigned char)*g_parsefile->next_to_pgetc++;
10017 g_parsefile->linno++;
10018 setprompt_if(doprompt, 2);
10023 g_parsefile->linno++;
10024 needprompt = doprompt;
10032 pgetc_debug("pgetc at %d:%p'%s'",
10033 g_parsefile->left_in_line,
10034 g_parsefile->next_to_pgetc,
10035 g_parsefile->next_to_pgetc);
10036 if (g_parsefile->unget)
10037 return g_parsefile->lastc[--g_parsefile->unget];
10039 if (--g_parsefile->left_in_line >= 0)
10040 c = (signed char)*g_parsefile->next_to_pgetc++;
10044 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10045 g_parsefile->lastc[0] = c;
10050 #if ENABLE_ASH_ALIAS
10052 pgetc_without_PEOA(void)
10056 pgetc_debug("pgetc at %d:%p'%s'",
10057 g_parsefile->left_in_line,
10058 g_parsefile->next_to_pgetc,
10059 g_parsefile->next_to_pgetc);
10061 } while (c == PEOA);
10065 # define pgetc_without_PEOA() pgetc()
10069 * Read a line from the script.
10072 pfgets(char *line, int len)
10078 while (--nleft > 0) {
10079 c = pgetc_without_PEOA();
10094 * Undo a call to pgetc. Only two characters may be pushed back.
10095 * PEOF may be pushed back.
10100 g_parsefile->unget++;
10103 /* This one eats backslash+newline */
10109 while ((c = pgetc()) == '\\') {
10110 if (pgetc() != '\n') {
10122 * To handle the "." command, a stack of input files is used. Pushfile
10123 * adds a new entry to the stack and popfile restores the previous level.
10128 struct parsefile *pf;
10130 pf = ckzalloc(sizeof(*pf));
10131 pf->prev = g_parsefile;
10133 /*pf->strpush = NULL; - ckzalloc did it */
10134 /*pf->basestrpush.prev = NULL;*/
10142 struct parsefile *pf = g_parsefile;
10145 if (pf->pf_fd >= 0)
10148 while (pf->strpush)
10150 g_parsefile = pf->prev;
10156 * Return to top level.
10161 while (g_parsefile != &basepf)
10166 * Close the file(s) that the shell is reading commands from. Called
10167 * after a fork is done.
10173 if (g_parsefile->pf_fd > 0) {
10174 close(g_parsefile->pf_fd);
10175 g_parsefile->pf_fd = 0;
10180 * Like setinputfile, but takes an open file descriptor. Call this with
10184 setinputfd(int fd, int push)
10186 close_on_exec_on(fd);
10189 g_parsefile->buf = NULL;
10191 g_parsefile->pf_fd = fd;
10192 if (g_parsefile->buf == NULL)
10193 g_parsefile->buf = ckmalloc(IBUFSIZ);
10194 g_parsefile->left_in_buffer = 0;
10195 g_parsefile->left_in_line = 0;
10196 g_parsefile->linno = 1;
10200 * Set the input to take input from a file. If push is set, push the
10201 * old input onto the stack first.
10204 setinputfile(const char *fname, int flags)
10210 fd = open(fname, O_RDONLY);
10212 if (flags & INPUT_NOFILE_OK)
10215 ash_msg_and_raise_error("can't open '%s'", fname);
10218 fd2 = copyfd(fd, 10);
10222 setinputfd(fd, flags & INPUT_PUSH_FILE);
10229 * Like setinputfile, but takes input from a string.
10232 setinputstring(char *string)
10236 g_parsefile->next_to_pgetc = string;
10237 g_parsefile->left_in_line = strlen(string);
10238 g_parsefile->buf = NULL;
10239 g_parsefile->linno = 1;
10244 /* ============ mail.c
10246 * Routines to check for mail.
10249 #if ENABLE_ASH_MAIL
10251 /* Hash of mtimes of mailboxes */
10252 static unsigned mailtime_hash;
10253 /* Set if MAIL or MAILPATH is changed. */
10254 static smallint mail_var_path_changed;
10257 * Print appropriate message(s) if mail has arrived.
10258 * If mail_var_path_changed is set,
10259 * then the value of MAIL has mail_var_path_changed,
10260 * so we just update the values.
10269 struct stackmark smark;
10272 setstackmark(&smark);
10273 mpath = mpathset() ? mpathval() : mailval();
10276 p = path_advance(&mpath, nullstr);
10281 for (q = p; *q; q++)
10287 q[-1] = '\0'; /* delete trailing '/' */
10288 if (stat(p, &statb) < 0) {
10291 /* Very simplistic "hash": just a sum of all mtimes */
10292 new_hash += (unsigned)statb.st_mtime;
10294 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10295 if (mailtime_hash != 0)
10296 out2str("you have mail\n");
10297 mailtime_hash = new_hash;
10299 mail_var_path_changed = 0;
10300 popstackmark(&smark);
10303 static void FAST_FUNC
10304 changemail(const char *val UNUSED_PARAM)
10306 mail_var_path_changed = 1;
10309 #endif /* ASH_MAIL */
10312 /* ============ ??? */
10315 * Set the shell parameters.
10318 setparam(char **argv)
10324 for (nparam = 0; argv[nparam]; nparam++)
10326 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10328 *ap++ = ckstrdup(*argv++);
10331 freeparam(&shellparam);
10332 shellparam.malloced = 1;
10333 shellparam.nparam = nparam;
10334 shellparam.p = newparam;
10335 #if ENABLE_ASH_GETOPTS
10336 shellparam.optind = 1;
10337 shellparam.optoff = -1;
10342 * Process shell options. The global variable argptr contains a pointer
10343 * to the argument list; we advance it past the options.
10345 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10346 * For a non-interactive shell, an error condition encountered
10347 * by a special built-in ... shall cause the shell to write a diagnostic message
10348 * to standard error and exit as shown in the following table:
10349 * Error Special Built-In
10351 * Utility syntax error (option or operand error) Shall exit
10353 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10354 * we see that bash does not do that (set "finishes" with error code 1 instead,
10355 * and shell continues), and people rely on this behavior!
10357 * set -o barfoo 2>/dev/null
10360 * Oh well. Let's mimic that.
10363 plus_minus_o(char *name, int val)
10368 for (i = 0; i < NOPTS; i++) {
10369 if (strcmp(name, optnames(i)) == 0) {
10374 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10377 for (i = 0; i < NOPTS; i++) {
10379 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10381 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10387 setoption(int flag, int val)
10391 for (i = 0; i < NOPTS; i++) {
10392 if (optletters(i) == flag) {
10397 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10401 options(int cmdline)
10409 while ((p = *argptr) != NULL) {
10411 if (c != '-' && c != '+')
10414 val = 0; /* val = 0 if c == '+' */
10417 if (p[0] == '\0' || LONE_DASH(p)) {
10419 /* "-" means turn off -x and -v */
10422 /* "--" means reset params */
10423 else if (*argptr == NULL)
10426 break; /* "-" or "--" terminates options */
10429 /* first char was + or - */
10430 while ((c = *p++) != '\0') {
10431 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10432 if (c == 'c' && cmdline) {
10433 minusc = p; /* command is after shell args */
10434 } else if (c == 'o') {
10435 if (plus_minus_o(*argptr, val)) {
10436 /* it already printed err message */
10437 return 1; /* error */
10441 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10443 /* bash does not accept +-login, we also won't */
10444 } else if (cmdline && val && (c == '-')) { /* long options */
10445 if (strcmp(p, "login") == 0)
10457 * The shift builtin command.
10459 static int FAST_FUNC
10460 shiftcmd(int argc UNUSED_PARAM, char **argv)
10467 n = number(argv[1]);
10468 if (n > shellparam.nparam)
10469 n = 0; /* bash compat, was = shellparam.nparam; */
10471 shellparam.nparam -= n;
10472 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10473 if (shellparam.malloced)
10476 ap2 = shellparam.p;
10477 while ((*ap2++ = *ap1++) != NULL)
10479 #if ENABLE_ASH_GETOPTS
10480 shellparam.optind = 1;
10481 shellparam.optoff = -1;
10488 * POSIX requires that 'set' (but not export or readonly) output the
10489 * variables in lexicographic order - by the locale's collating order (sigh).
10490 * Maybe we could keep them in an ordered balanced binary tree
10491 * instead of hashed lists.
10492 * For now just roll 'em through qsort for printing...
10495 showvars(const char *sep_prefix, int on, int off)
10498 char **ep, **epend;
10500 ep = listvars(on, off, &epend);
10501 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10503 sep = *sep_prefix ? " " : sep_prefix;
10505 for (; ep < epend; ep++) {
10509 p = strchrnul(*ep, '=');
10512 q = single_quote(++p);
10513 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10519 * The set command builtin.
10521 static int FAST_FUNC
10522 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10527 return showvars(nullstr, 0, VUNSET);
10530 retval = options(/*cmdline:*/ 0);
10531 if (retval == 0) { /* if no parse error... */
10533 if (*argptr != NULL) {
10541 #if ENABLE_ASH_RANDOM_SUPPORT
10542 static void FAST_FUNC
10543 change_random(const char *value)
10547 if (value == NULL) {
10548 /* "get", generate */
10549 t = next_random(&random_gen);
10550 /* set without recursion */
10551 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10552 vrandom.flags &= ~VNOFUNC;
10555 t = strtoul(value, NULL, 10);
10556 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10561 #if ENABLE_ASH_GETOPTS
10563 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10574 if (*param_optind < 1)
10576 optnext = optfirst + *param_optind - 1;
10578 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10581 p = optnext[-1] + *optoff;
10582 if (p == NULL || *p == '\0') {
10583 /* Current word is done, advance */
10585 if (p == NULL || *p != '-' || *++p == '\0') {
10592 if (LONE_DASH(p)) /* check for "--" */
10597 for (q = optstr; *q != c;) {
10599 if (optstr[0] == ':') {
10601 /*sbuf[1] = '\0'; - already is */
10602 err |= setvarsafe("OPTARG", sbuf, 0);
10604 fprintf(stderr, "Illegal option -%c\n", c);
10605 unsetvar("OPTARG");
10615 if (*p == '\0' && (p = *optnext) == NULL) {
10616 if (optstr[0] == ':') {
10618 /*sbuf[1] = '\0'; - already is */
10619 err |= setvarsafe("OPTARG", sbuf, 0);
10622 fprintf(stderr, "No arg for -%c option\n", c);
10623 unsetvar("OPTARG");
10631 err |= setvarsafe("OPTARG", p, 0);
10634 err |= setvarsafe("OPTARG", nullstr, 0);
10636 *optoff = p ? p - *(optnext - 1) : -1;
10637 *param_optind = optnext - optfirst + 1;
10638 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10640 /*sbuf[1] = '\0'; - already is */
10641 err |= setvarsafe(optvar, sbuf, 0);
10645 flush_stdout_stderr();
10646 raise_exception(EXERROR);
10652 * The getopts builtin. Shellparam.optnext points to the next argument
10653 * to be processed. Shellparam.optptr points to the next character to
10654 * be processed in the current argument. If shellparam.optnext is NULL,
10655 * then it's the first time getopts has been called.
10657 static int FAST_FUNC
10658 getoptscmd(int argc, char **argv)
10663 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10665 optbase = shellparam.p;
10666 if (shellparam.optind > shellparam.nparam + 1) {
10667 shellparam.optind = 1;
10668 shellparam.optoff = -1;
10671 optbase = &argv[3];
10672 if (shellparam.optind > argc - 2) {
10673 shellparam.optind = 1;
10674 shellparam.optoff = -1;
10678 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10679 &shellparam.optoff);
10681 #endif /* ASH_GETOPTS */
10684 /* ============ Shell parser */
10687 struct heredoc *next; /* next here document in list */
10688 union node *here; /* redirection node */
10689 char *eofmark; /* string indicating end of input */
10690 smallint striptabs; /* if set, strip leading tabs */
10693 static smallint tokpushback; /* last token pushed back */
10694 static smallint quoteflag; /* set if (part of) last token was quoted */
10695 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10696 static struct heredoc *heredoclist; /* list of here documents to read */
10697 static char *wordtext; /* text of last word returned by readtoken */
10698 static struct nodelist *backquotelist;
10699 static union node *redirnode;
10700 static struct heredoc *heredoc;
10702 static const char *
10703 tokname(char *buf, int tok)
10706 return tokname_array[tok];
10707 sprintf(buf, "\"%s\"", tokname_array[tok]);
10711 /* raise_error_unexpected_syntax:
10712 * Called when an unexpected token is read during the parse. The argument
10713 * is the token that is expected, or -1 if more than one type of token can
10714 * occur at this point.
10716 static void raise_error_unexpected_syntax(int) NORETURN;
10718 raise_error_unexpected_syntax(int token)
10724 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10726 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10727 raise_error_syntax(msg);
10731 #define EOFMARKLEN 79
10733 /* parsing is heavily cross-recursive, need these forward decls */
10734 static union node *andor(void);
10735 static union node *pipeline(void);
10736 static union node *parse_command(void);
10737 static void parseheredoc(void);
10738 static int peektoken(void);
10739 static int readtoken(void);
10741 static union node *
10744 union node *n1, *n2, *n3;
10749 switch (peektoken()) {
10757 if (!n1 && (nlflag & 1))
10763 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10764 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10770 if (tok == TBACKGND) {
10771 if (n2->type == NPIPE) {
10772 n2->npipe.pipe_backgnd = 1;
10774 if (n2->type != NREDIR) {
10775 n3 = stzalloc(sizeof(struct nredir));
10777 /*n3->nredir.redirect = NULL; - stzalloc did it */
10780 n2->type = NBACKGND;
10786 n3 = stzalloc(sizeof(struct nbinary));
10788 n3->nbinary.ch1 = n1;
10789 n3->nbinary.ch2 = n2;
10802 raise_error_unexpected_syntax(-1);
10809 static union node *
10812 union node *n1, *n2, *n3;
10820 } else if (t == TOR) {
10826 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10828 n3 = stzalloc(sizeof(struct nbinary));
10830 n3->nbinary.ch1 = n1;
10831 n3->nbinary.ch2 = n2;
10836 static union node *
10839 union node *n1, *n2, *pipenode;
10840 struct nodelist *lp, *prev;
10844 TRACE(("pipeline: entered\n"));
10845 if (readtoken() == TNOT) {
10847 checkkwd = CHKKWD | CHKALIAS;
10850 n1 = parse_command();
10851 if (readtoken() == TPIPE) {
10852 pipenode = stzalloc(sizeof(struct npipe));
10853 pipenode->type = NPIPE;
10854 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10855 lp = stzalloc(sizeof(struct nodelist));
10856 pipenode->npipe.cmdlist = lp;
10860 lp = stzalloc(sizeof(struct nodelist));
10861 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10862 lp->n = parse_command();
10864 } while (readtoken() == TPIPE);
10870 n2 = stzalloc(sizeof(struct nnot));
10878 static union node *
10883 n = stzalloc(sizeof(struct narg));
10885 /*n->narg.next = NULL; - stzalloc did it */
10886 n->narg.text = wordtext;
10887 n->narg.backquote = backquotelist;
10892 fixredir(union node *n, const char *text, int err)
10896 TRACE(("Fix redir %s %d\n", text, err));
10898 n->ndup.vname = NULL;
10900 fd = bb_strtou(text, NULL, 10);
10901 if (!errno && fd >= 0)
10902 n->ndup.dupfd = fd;
10903 else if (LONE_DASH(text))
10904 n->ndup.dupfd = -1;
10907 raise_error_syntax("bad fd number");
10908 n->ndup.vname = makename();
10913 * Returns true if the text contains nothing to expand (no dollar signs
10917 noexpand(const char *text)
10921 while ((c = *text++) != '\0') {
10922 if (c == CTLQUOTEMARK)
10926 else if (SIT(c, BASESYNTAX) == CCTL)
10935 union node *n = redirnode;
10937 if (readtoken() != TWORD)
10938 raise_error_unexpected_syntax(-1);
10939 if (n->type == NHERE) {
10940 struct heredoc *here = heredoc;
10944 if (quoteflag == 0)
10946 TRACE(("Here document %d\n", n->type));
10947 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10948 raise_error_syntax("illegal eof marker for << redirection");
10949 rmescapes(wordtext, 0);
10950 here->eofmark = wordtext;
10952 if (heredoclist == NULL)
10953 heredoclist = here;
10955 for (p = heredoclist; p->next; p = p->next)
10959 } else if (n->type == NTOFD || n->type == NFROMFD) {
10960 fixredir(n, wordtext, 0);
10962 n->nfile.fname = makename();
10966 static union node *
10969 union node *args, **app;
10970 union node *n = NULL;
10971 union node *vars, **vpp;
10972 union node **rpp, *redir;
10974 #if ENABLE_ASH_BASH_COMPAT
10975 smallint double_brackets_flag = 0;
10976 smallint function_flag = 0;
10986 savecheckkwd = CHKALIAS;
10989 checkkwd = savecheckkwd;
10992 #if ENABLE_ASH_BASH_COMPAT
10994 if (peektoken() != TWORD)
10995 raise_error_unexpected_syntax(TWORD);
10998 case TAND: /* "&&" */
10999 case TOR: /* "||" */
11000 if (!double_brackets_flag) {
11004 wordtext = (char *) (t == TAND ? "-a" : "-o");
11007 n = stzalloc(sizeof(struct narg));
11009 /*n->narg.next = NULL; - stzalloc did it */
11010 n->narg.text = wordtext;
11011 #if ENABLE_ASH_BASH_COMPAT
11012 if (strcmp("[[", wordtext) == 0)
11013 double_brackets_flag = 1;
11014 else if (strcmp("]]", wordtext) == 0)
11015 double_brackets_flag = 0;
11017 n->narg.backquote = backquotelist;
11018 if (savecheckkwd && isassignment(wordtext)) {
11020 vpp = &n->narg.next;
11023 app = &n->narg.next;
11026 #if ENABLE_ASH_BASH_COMPAT
11027 if (function_flag) {
11028 checkkwd = CHKNL | CHKKWD;
11029 switch (peektoken()) {
11041 if (strcmp("[[", wordtext) == 0)
11045 raise_error_unexpected_syntax(-1);
11051 *rpp = n = redirnode;
11052 rpp = &n->nfile.next;
11053 parsefname(); /* read name of redirection file */
11056 IF_ASH_BASH_COMPAT(do_func:)
11057 if (args && app == &args->narg.next
11060 struct builtincmd *bcmd;
11063 /* We have a function */
11064 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11065 raise_error_unexpected_syntax(TRP);
11066 name = n->narg.text;
11067 if (!goodname(name)
11068 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11070 raise_error_syntax("bad function name");
11073 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11074 n->narg.next = parse_command();
11077 IF_ASH_BASH_COMPAT(function_flag = 0;)
11088 n = stzalloc(sizeof(struct ncmd));
11090 n->ncmd.args = args;
11091 n->ncmd.assign = vars;
11092 n->ncmd.redirect = redir;
11096 static union node *
11097 parse_command(void)
11099 union node *n1, *n2;
11100 union node *ap, **app;
11101 union node *cp, **cpp;
11102 union node *redir, **rpp;
11109 switch (readtoken()) {
11111 raise_error_unexpected_syntax(-1);
11114 n1 = stzalloc(sizeof(struct nif));
11116 n1->nif.test = list(0);
11117 if (readtoken() != TTHEN)
11118 raise_error_unexpected_syntax(TTHEN);
11119 n1->nif.ifpart = list(0);
11121 while (readtoken() == TELIF) {
11122 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11123 n2 = n2->nif.elsepart;
11125 n2->nif.test = list(0);
11126 if (readtoken() != TTHEN)
11127 raise_error_unexpected_syntax(TTHEN);
11128 n2->nif.ifpart = list(0);
11130 if (lasttoken == TELSE)
11131 n2->nif.elsepart = list(0);
11133 n2->nif.elsepart = NULL;
11141 n1 = stzalloc(sizeof(struct nbinary));
11142 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11143 n1->nbinary.ch1 = list(0);
11146 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11147 got == TWORD ? wordtext : ""));
11148 raise_error_unexpected_syntax(TDO);
11150 n1->nbinary.ch2 = list(0);
11155 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11156 raise_error_syntax("bad for loop variable");
11157 n1 = stzalloc(sizeof(struct nfor));
11159 n1->nfor.var = wordtext;
11160 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11161 if (readtoken() == TIN) {
11163 while (readtoken() == TWORD) {
11164 n2 = stzalloc(sizeof(struct narg));
11166 /*n2->narg.next = NULL; - stzalloc did it */
11167 n2->narg.text = wordtext;
11168 n2->narg.backquote = backquotelist;
11170 app = &n2->narg.next;
11173 n1->nfor.args = ap;
11174 if (lasttoken != TNL && lasttoken != TSEMI)
11175 raise_error_unexpected_syntax(-1);
11177 n2 = stzalloc(sizeof(struct narg));
11179 /*n2->narg.next = NULL; - stzalloc did it */
11180 n2->narg.text = (char *)dolatstr;
11181 /*n2->narg.backquote = NULL;*/
11182 n1->nfor.args = n2;
11184 * Newline or semicolon here is optional (but note
11185 * that the original Bourne shell only allowed NL).
11187 if (lasttoken != TSEMI)
11190 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11191 if (readtoken() != TDO)
11192 raise_error_unexpected_syntax(TDO);
11193 n1->nfor.body = list(0);
11197 n1 = stzalloc(sizeof(struct ncase));
11199 if (readtoken() != TWORD)
11200 raise_error_unexpected_syntax(TWORD);
11201 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11203 /*n2->narg.next = NULL; - stzalloc did it */
11204 n2->narg.text = wordtext;
11205 n2->narg.backquote = backquotelist;
11206 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11207 if (readtoken() != TIN)
11208 raise_error_unexpected_syntax(TIN);
11209 cpp = &n1->ncase.cases;
11211 checkkwd = CHKNL | CHKKWD;
11213 while (t != TESAC) {
11214 if (lasttoken == TLP)
11216 *cpp = cp = stzalloc(sizeof(struct nclist));
11218 app = &cp->nclist.pattern;
11220 *app = ap = stzalloc(sizeof(struct narg));
11222 /*ap->narg.next = NULL; - stzalloc did it */
11223 ap->narg.text = wordtext;
11224 ap->narg.backquote = backquotelist;
11225 if (readtoken() != TPIPE)
11227 app = &ap->narg.next;
11230 //ap->narg.next = NULL;
11231 if (lasttoken != TRP)
11232 raise_error_unexpected_syntax(TRP);
11233 cp->nclist.body = list(2);
11235 cpp = &cp->nclist.next;
11237 checkkwd = CHKNL | CHKKWD;
11241 raise_error_unexpected_syntax(TENDCASE);
11248 n1 = stzalloc(sizeof(struct nredir));
11249 n1->type = NSUBSHELL;
11250 n1->nredir.n = list(0);
11251 /*n1->nredir.redirect = NULL; - stzalloc did it */
11258 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11262 return simplecmd();
11265 if (readtoken() != t)
11266 raise_error_unexpected_syntax(t);
11269 /* Now check for redirection which may follow command */
11270 checkkwd = CHKKWD | CHKALIAS;
11272 while (readtoken() == TREDIR) {
11273 *rpp = n2 = redirnode;
11274 rpp = &n2->nfile.next;
11280 if (n1->type != NSUBSHELL) {
11281 n2 = stzalloc(sizeof(struct nredir));
11286 n1->nredir.redirect = redir;
11291 #if ENABLE_ASH_BASH_COMPAT
11293 decode_dollar_squote(void)
11295 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11301 p = strchr(C_escapes, c);
11306 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11310 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11312 } else if (c == 'x') { /* \xHH */
11316 } while (isxdigit(c) && --cnt);
11318 if (cnt == 3) { /* \x but next char is "bad" */
11322 } else { /* simple seq like \\ or \t */
11327 c = bb_process_escape_sequence((void*)&p);
11328 } else { /* unrecognized "\z": print both chars unless ' or " */
11329 if (c != '\'' && c != '"') {
11331 c |= 0x100; /* "please encode \, then me" */
11339 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11340 * is not NULL, read a here document. In the latter case, eofmark is the
11341 * word which marks the end of the document and striptabs is true if
11342 * leading tabs should be stripped from the document. The argument c
11343 * is the first character of the input token or document.
11345 * Because C does not have internal subroutines, I have simulated them
11346 * using goto's to implement the subroutine linkage. The following macros
11347 * will run code that appears at the end of readtoken1.
11349 #define CHECKEND() {goto checkend; checkend_return:;}
11350 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11351 #define PARSESUB() {goto parsesub; parsesub_return:;}
11352 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11353 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11354 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11356 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11358 /* NB: syntax parameter fits into smallint */
11359 /* c parameter is an unsigned char or PEOF or PEOA */
11362 char line[EOFMARKLEN + 1];
11363 struct nodelist *bqlist;
11367 smallint prevsyntax; /* syntax before arithmetic */
11368 #if ENABLE_ASH_EXPAND_PRMT
11369 smallint pssyntax; /* we are expanding a prompt string */
11371 int varnest; /* levels of variables expansion */
11372 int arinest; /* levels of arithmetic expansion */
11373 int parenlevel; /* levels of parens in arithmetic */
11374 int dqvarnest; /* levels of variables expansion within double quotes */
11376 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11378 startlinno = g_parsefile->linno;
11382 #if ENABLE_ASH_EXPAND_PRMT
11383 pssyntax = (syntax == PSSYNTAX);
11387 dblquote = (syntax == DQSYNTAX);
11393 STARTSTACKSTR(out);
11395 /* For each line, until end of word */
11396 CHECKEND(); /* set c to PEOF if at end of here document */
11397 for (;;) { /* until end of line or end of word */
11398 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11399 switch (SIT(c, syntax)) {
11400 case CNL: /* '\n' */
11401 if (syntax == BASESYNTAX)
11402 goto endword; /* exit outer loop */
11406 goto loop; /* continue outer loop */
11411 #if ENABLE_ASH_BASH_COMPAT
11412 if (c == '\\' && bash_dollar_squote) {
11413 c = decode_dollar_squote();
11415 /* skip $'\000', $'\x00' (like bash) */
11419 /* Unknown escape. Encode as '\z' */
11420 c = (unsigned char)c;
11421 if (eofmark == NULL || dblquote)
11422 USTPUTC(CTLESC, out);
11423 USTPUTC('\\', out);
11427 if (eofmark == NULL || dblquote)
11428 USTPUTC(CTLESC, out);
11431 case CBACK: /* backslash */
11432 c = pgetc_without_PEOA();
11434 USTPUTC(CTLESC, out);
11435 USTPUTC('\\', out);
11437 } else if (c == '\n') {
11440 #if ENABLE_ASH_EXPAND_PRMT
11441 if (c == '$' && pssyntax) {
11442 USTPUTC(CTLESC, out);
11443 USTPUTC('\\', out);
11446 /* Backslash is retained if we are in "str" and next char isn't special */
11451 && (c != '"' || eofmark != NULL)
11453 USTPUTC('\\', out);
11455 USTPUTC(CTLESC, out);
11463 if (eofmark == NULL) {
11464 USTPUTC(CTLQUOTEMARK, out);
11472 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11473 if (eofmark != NULL && varnest == 0) {
11476 if (dqvarnest == 0) {
11477 syntax = BASESYNTAX;
11484 case CVAR: /* '$' */
11485 PARSESUB(); /* parse substitution */
11487 case CENDVAR: /* '}' */
11490 if (dqvarnest > 0) {
11497 #if ENABLE_SH_MATH_SUPPORT
11498 case CLP: /* '(' in arithmetic */
11502 case CRP: /* ')' in arithmetic */
11503 if (parenlevel > 0) {
11506 if (pgetc_eatbnl() == ')') {
11508 if (--arinest == 0) {
11509 syntax = prevsyntax;
11513 * unbalanced parens
11514 * (don't 2nd guess - no error)
11522 case CBQUOTE: /* '`' */
11526 goto endword; /* exit outer loop */
11530 if (varnest == 0) {
11531 #if ENABLE_ASH_BASH_COMPAT
11533 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11534 if (pgetc() == '>')
11535 c = 0x100 + '>'; /* flag &> */
11539 goto endword; /* exit outer loop */
11541 IF_ASH_ALIAS(if (c != PEOA))
11548 #if ENABLE_SH_MATH_SUPPORT
11549 if (syntax == ARISYNTAX)
11550 raise_error_syntax("missing '))'");
11552 if (syntax != BASESYNTAX && eofmark == NULL)
11553 raise_error_syntax("unterminated quoted string");
11554 if (varnest != 0) {
11555 startlinno = g_parsefile->linno;
11557 raise_error_syntax("missing '}'");
11559 USTPUTC('\0', out);
11560 len = out - (char *)stackblock();
11561 out = stackblock();
11562 if (eofmark == NULL) {
11563 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11566 if (isdigit_str9(out)) {
11567 PARSEREDIR(); /* passed as params: out, c */
11568 lasttoken = TREDIR;
11571 /* else: non-number X seen, interpret it
11572 * as "NNNX>file" = "NNNX >file" */
11576 quoteflag = quotef;
11577 backquotelist = bqlist;
11578 grabstackblock(len);
11582 /* end of readtoken routine */
11585 * Check to see whether we are at the end of the here document. When this
11586 * is called, c is set to the first character of the next input line. If
11587 * we are at the end of the here document, this routine sets the c to PEOF.
11591 #if ENABLE_ASH_ALIAS
11593 c = pgetc_without_PEOA();
11596 while (c == '\t') {
11597 c = pgetc_without_PEOA();
11600 if (c == *eofmark) {
11601 if (pfgets(line, sizeof(line)) != NULL) {
11605 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11607 if (*p == '\n' && *q == '\0') {
11611 pushstring(line, NULL);
11616 goto checkend_return;
11620 * Parse a redirection operator. The variable "out" points to a string
11621 * specifying the fd to be redirected. The variable "c" contains the
11622 * first character of the redirection operator.
11625 /* out is already checked to be a valid number or "" */
11626 int fd = (*out == '\0' ? -1 : atoi(out));
11629 np = stzalloc(sizeof(struct nfile));
11634 np->type = NAPPEND;
11636 np->type = NCLOBBER;
11639 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11645 #if ENABLE_ASH_BASH_COMPAT
11646 else if (c == 0x100 + '>') { /* this flags &> redirection */
11648 pgetc(); /* this is '>', no need to check */
11652 else { /* c == '<' */
11653 /*np->nfile.fd = 0; - stzalloc did it */
11657 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11658 np = stzalloc(sizeof(struct nhere));
11659 /*np->nfile.fd = 0; - stzalloc did it */
11662 heredoc = stzalloc(sizeof(struct heredoc));
11663 heredoc->here = np;
11666 heredoc->striptabs = 1;
11668 /*heredoc->striptabs = 0; - stzalloc did it */
11674 np->type = NFROMFD;
11678 np->type = NFROMTO;
11690 goto parseredir_return;
11694 * Parse a substitution. At this point, we have read the dollar sign
11695 * and nothing else.
11698 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11699 * (assuming ascii char codes, as the original implementation did) */
11700 #define is_special(c) \
11701 (((unsigned)(c) - 33 < 32) \
11702 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11704 unsigned char subtype;
11708 c = pgetc_eatbnl();
11709 if (c > 255 /* PEOA or PEOF */
11710 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11712 #if ENABLE_ASH_BASH_COMPAT
11713 if (syntax != DQSYNTAX && c == '\'')
11714 bash_dollar_squote = 1;
11719 } else if (c == '(') {
11720 /* $(command) or $((arith)) */
11721 if (pgetc_eatbnl() == '(') {
11722 #if ENABLE_SH_MATH_SUPPORT
11725 raise_error_syntax("you disabled math support for $((arith)) syntax");
11732 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11733 USTPUTC(CTLVAR, out);
11734 typeloc = out - (char *)stackblock();
11735 USTPUTC(VSNORMAL, out);
11736 subtype = VSNORMAL;
11738 c = pgetc_eatbnl();
11740 c = pgetc_eatbnl();
11742 c = '#'; /* ${#} - same as $# */
11744 subtype = VSLENGTH; /* ${#VAR} */
11749 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11750 /* $[{[#]]NAME[}] */
11753 c = pgetc_eatbnl();
11754 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11755 } else if (isdigit(c)) {
11756 /* $[{[#]]NUM[}] */
11759 c = pgetc_eatbnl();
11760 } while (isdigit(c));
11761 } else if (is_special(c)) {
11762 /* $[{[#]]<specialchar>[}] */
11764 c = pgetc_eatbnl();
11768 if (c != '}' && subtype == VSLENGTH) {
11769 /* ${#VAR didn't end with } */
11774 if (subtype == 0) {
11775 static const char types[] ALIGN1 = "}-+?=";
11776 /* ${VAR...} but not $VAR or ${#VAR} */
11777 /* c == first char after VAR */
11780 c = pgetc_eatbnl();
11781 #if ENABLE_ASH_BASH_COMPAT
11782 /* This check is only needed to not misinterpret
11783 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11786 if (!strchr(types, c)) {
11787 subtype = VSSUBSTR;
11789 break; /* "goto badsub" is bigger (!) */
11795 const char *p = strchr(types, c);
11798 subtype = p - types + VSNORMAL;
11804 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11805 c = pgetc_eatbnl();
11811 #if ENABLE_ASH_BASH_COMPAT
11813 /* ${v/[/]pattern/repl} */
11814 //TODO: encode pattern and repl separately.
11815 // Currently ${v/$var_with_slash/repl} is horribly broken
11816 subtype = VSREPLACE;
11817 c = pgetc_eatbnl();
11820 subtype++; /* VSREPLACEALL */
11828 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11829 if (subtype != VSNORMAL) {
11837 goto parsesub_return;
11841 * Called to parse command substitutions. Newstyle is set if the command
11842 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11843 * list of commands (passed by reference), and savelen is the number of
11844 * characters on the top of the stack which must be preserved.
11847 struct nodelist **nlpp;
11851 smallint saveprompt = 0;
11854 savelen = out - (char *)stackblock();
11857 * FIXME: this can allocate very large block on stack and SEGV.
11859 * echo "..<100kbytes>..`true` $(true) `true` ..."
11860 * allocates 100kb for every command subst. With about
11861 * a hundred command substitutions stack overflows.
11862 * With larger prepended string, SEGV happens sooner.
11864 str = alloca(savelen);
11865 memcpy(str, stackblock(), savelen);
11869 /* We must read until the closing backquote, giving special
11870 * treatment to some slashes, and then push the string and
11871 * reread it as input, interpreting it normally.
11877 STARTSTACKSTR(pout);
11881 setprompt_if(needprompt, 2);
11892 * If eating a newline, avoid putting
11893 * the newline into the new character
11894 * stream (via the STPUTC after the
11899 if (pc != '\\' && pc != '`' && pc != '$'
11900 && (!dblquote || pc != '"')
11902 STPUTC('\\', pout);
11904 if (pc <= 255 /* not PEOA or PEOF */) {
11910 IF_ASH_ALIAS(case PEOA:)
11911 startlinno = g_parsefile->linno;
11912 raise_error_syntax("EOF in backquote substitution");
11924 STPUTC('\0', pout);
11925 psavelen = pout - (char *)stackblock();
11926 if (psavelen > 0) {
11927 pstr = grabstackstr(pout);
11928 setinputstring(pstr);
11933 nlpp = &(*nlpp)->next;
11934 *nlpp = stzalloc(sizeof(**nlpp));
11935 /* (*nlpp)->next = NULL; - stzalloc did it */
11938 saveprompt = doprompt;
11945 doprompt = saveprompt;
11946 else if (readtoken() != TRP)
11947 raise_error_unexpected_syntax(TRP);
11952 * Start reading from old file again, ignoring any pushed back
11953 * tokens left from the backquote parsing
11958 while (stackblocksize() <= savelen)
11960 STARTSTACKSTR(out);
11962 memcpy(out, str, savelen);
11963 STADJUST(savelen, out);
11965 USTPUTC(CTLBACKQ, out);
11967 goto parsebackq_oldreturn;
11968 goto parsebackq_newreturn;
11971 #if ENABLE_SH_MATH_SUPPORT
11973 * Parse an arithmetic expansion (indicate start of one and set state)
11976 if (++arinest == 1) {
11977 prevsyntax = syntax;
11978 syntax = ARISYNTAX;
11980 USTPUTC(CTLARI, out);
11981 goto parsearith_return;
11984 } /* end of readtoken */
11987 * Read the next input token.
11988 * If the token is a word, we set backquotelist to the list of cmds in
11989 * backquotes. We set quoteflag to true if any part of the word was
11991 * If the token is TREDIR, then we set redirnode to a structure containing
11993 * In all cases, the variable startlinno is set to the number of the line
11994 * on which the token starts.
11996 * [Change comment: here documents and internal procedures]
11997 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11998 * word parsing code into a separate routine. In this case, readtoken
11999 * doesn't need to have any internal procedures, but parseword does.
12000 * We could also make parseoperator in essence the main routine, and
12001 * have parseword (readtoken1?) handle both words and redirection.]
12003 #define NEW_xxreadtoken
12004 #ifdef NEW_xxreadtoken
12005 /* singles must be first! */
12006 static const char xxreadtoken_chars[7] ALIGN1 = {
12007 '\n', '(', ')', /* singles */
12008 '&', '|', ';', /* doubles */
12012 #define xxreadtoken_singles 3
12013 #define xxreadtoken_doubles 3
12015 static const char xxreadtoken_tokens[] ALIGN1 = {
12016 TNL, TLP, TRP, /* only single occurrence allowed */
12017 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12018 TEOF, /* corresponds to trailing nul */
12019 TAND, TOR, TENDCASE /* if double occurrence */
12031 setprompt_if(needprompt, 2);
12032 startlinno = g_parsefile->linno;
12033 for (;;) { /* until token or start of word found */
12035 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12039 while ((c = pgetc()) != '\n' && c != PEOF)
12042 } else if (c == '\\') {
12043 if (pgetc() != '\n') {
12045 break; /* return readtoken1(...) */
12051 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12057 p = strchr(xxreadtoken_chars, c);
12059 break; /* return readtoken1(...) */
12061 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12063 if (cc == c) { /* double occurrence? */
12064 p += xxreadtoken_doubles + 1;
12067 #if ENABLE_ASH_BASH_COMPAT
12068 if (c == '&' && cc == '>') /* &> */
12069 break; /* return readtoken1(...) */
12074 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12079 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12081 #else /* old xxreadtoken */
12082 #define RETURN(token) return lasttoken = token
12092 setprompt_if(needprompt, 2);
12093 startlinno = g_parsefile->linno;
12094 for (;;) { /* until token or start of word found */
12097 case ' ': case '\t':
12098 IF_ASH_ALIAS(case PEOA:)
12101 while ((c = pgetc()) != '\n' && c != PEOF)
12106 if (pgetc() == '\n') {
12118 if (pgetc() == '&')
12123 if (pgetc() == '|')
12128 if (pgetc() == ';')
12141 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12144 #endif /* old xxreadtoken */
12150 int kwd = checkkwd;
12152 smallint alreadyseen = tokpushback;
12155 #if ENABLE_ASH_ALIAS
12171 if (t != TWORD || quoteflag) {
12176 * check for keywords
12178 if (kwd & CHKKWD) {
12179 const char *const *pp;
12181 pp = findkwd(wordtext);
12183 lasttoken = t = pp - tokname_array;
12184 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12189 if (checkkwd & CHKALIAS) {
12190 #if ENABLE_ASH_ALIAS
12192 ap = lookupalias(wordtext, 1);
12195 pushstring(ap->val, ap);
12205 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12207 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12223 * Read and parse a command. Returns NODE_EOF on end of file.
12224 * (NULL is a valid parse tree indicating a blank line.)
12226 static union node *
12227 parsecmd(int interact)
12232 doprompt = interact;
12233 setprompt_if(doprompt, doprompt);
12239 * Input any here documents.
12244 struct heredoc *here;
12247 here = heredoclist;
12248 heredoclist = NULL;
12251 setprompt_if(needprompt, 2);
12252 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12253 here->eofmark, here->striptabs);
12254 n = stzalloc(sizeof(struct narg));
12255 n->narg.type = NARG;
12256 /*n->narg.next = NULL; - stzalloc did it */
12257 n->narg.text = wordtext;
12258 n->narg.backquote = backquotelist;
12259 here->here->nhere.doc = n;
12266 * called by editline -- any expansions to the prompt should be added here.
12268 #if ENABLE_ASH_EXPAND_PRMT
12269 static const char *
12270 expandstr(const char *ps)
12275 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12276 * and token processing _can_ alter it (delete NULs etc). */
12277 setinputstring((char *)ps);
12279 saveprompt = doprompt;
12281 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12282 doprompt = saveprompt;
12286 n.narg.type = NARG;
12287 n.narg.next = NULL;
12288 n.narg.text = wordtext;
12289 n.narg.backquote = backquotelist;
12291 expandarg(&n, NULL, EXP_QUOTED);
12292 return stackblock();
12297 * Execute a command or commands contained in a string.
12300 evalstring(char *s, int flags)
12303 struct stackmark smark;
12308 setstackmark(&smark);
12311 while ((n = parsecmd(0)) != NODE_EOF) {
12314 i = evaltree(n, flags);
12317 popstackmark(&smark);
12321 popstackmark(&smark);
12329 * The eval command.
12331 static int FAST_FUNC
12332 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12341 STARTSTACKSTR(concat);
12343 concat = stack_putstr(p, concat);
12347 STPUTC(' ', concat);
12349 STPUTC('\0', concat);
12350 p = grabstackstr(concat);
12352 return evalstring(p, flags & EV_TESTED);
12358 * Read and execute commands.
12359 * "Top" is nonzero for the top level command loop;
12360 * it turns on prompting if the shell is interactive.
12366 struct stackmark smark;
12371 TRACE(("cmdloop(%d) called\n", top));
12375 setstackmark(&smark);
12378 showjobs(SHOW_CHANGED|SHOW_STDERR);
12381 if (iflag && top) {
12385 n = parsecmd(inter);
12387 if (DEBUG > 2 && debug && (n != NODE_EOF))
12390 if (n == NODE_EOF) {
12391 if (!top || numeof >= 50)
12393 if (!stoppedjobs()) {
12396 out2str("\nUse \"exit\" to leave shell.\n");
12399 } else if (nflag == 0) {
12402 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12405 i = evaltree(n, 0);
12409 popstackmark(&smark);
12413 evalskip &= ~SKIPFUNC;
12421 * Take commands from a file. To be compatible we should do a path
12422 * search for the file, which is necessary to find sub-commands.
12425 find_dot_file(char *name)
12428 const char *path = pathval();
12431 /* don't try this for absolute or relative paths */
12432 if (strchr(name, '/'))
12435 /* IIRC standards do not say whether . is to be searched.
12436 * And it is even smaller this way, making it unconditional for now:
12438 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12443 while ((fullname = path_advance(&path, name)) != NULL) {
12445 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12447 * Don't bother freeing here, since it will
12448 * be freed by the caller.
12452 if (fullname != name)
12453 stunalloc(fullname);
12456 /* not found in the PATH */
12457 ash_msg_and_raise_error("%s: not found", name);
12461 static int FAST_FUNC
12462 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12464 /* "false; . empty_file; echo $?" should print 0, not 1: */
12468 struct strlist *sp;
12469 volatile struct shparam saveparam;
12471 for (sp = cmdenviron; sp; sp = sp->next)
12472 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12474 nextopt(nullstr); /* handle possible "--" */
12478 /* bash says: "bash: .: filename argument required" */
12479 return 2; /* bash compat */
12482 /* This aborts if file isn't found, which is POSIXly correct.
12483 * bash returns exitcode 1 instead.
12485 fullname = find_dot_file(argv[0]);
12487 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12489 saveparam = shellparam;
12490 shellparam.malloced = 0;
12494 shellparam.nparam = argc;
12495 shellparam.p = argv;
12498 /* This aborts if file can't be opened, which is POSIXly correct.
12499 * bash returns exitcode 1 instead.
12501 setinputfile(fullname, INPUT_PUSH_FILE);
12502 commandname = fullname;
12503 status = cmdloop(0);
12507 freeparam(&shellparam);
12508 shellparam = saveparam;
12514 static int FAST_FUNC
12515 exitcmd(int argc UNUSED_PARAM, char **argv)
12520 exitstatus = number(argv[1]);
12521 raise_exception(EXEXIT);
12526 * Read a file containing shell functions.
12529 readcmdfile(char *name)
12531 setinputfile(name, INPUT_PUSH_FILE);
12537 /* ============ find_command inplementation */
12540 * Resolve a command name. If you change this routine, you may have to
12541 * change the shellexec routine as well.
12544 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12546 struct tblentry *cmdp;
12553 struct builtincmd *bcmd;
12555 /* If name contains a slash, don't use PATH or hash table */
12556 if (strchr(name, '/') != NULL) {
12557 entry->u.index = -1;
12558 if (act & DO_ABS) {
12559 while (stat(name, &statb) < 0) {
12561 if (errno == EINTR)
12564 entry->cmdtype = CMDUNKNOWN;
12568 entry->cmdtype = CMDNORMAL;
12572 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12574 updatetbl = (path == pathval());
12577 if (strstr(path, "%builtin") != NULL)
12578 act |= DO_ALTBLTIN;
12581 /* If name is in the table, check answer will be ok */
12582 cmdp = cmdlookup(name, 0);
12583 if (cmdp != NULL) {
12586 switch (cmdp->cmdtype) {
12604 } else if (cmdp->rehash == 0)
12605 /* if not invalidated by cd, we're done */
12609 /* If %builtin not in path, check for builtin next */
12610 bcmd = find_builtin(name);
12612 if (IS_BUILTIN_REGULAR(bcmd))
12613 goto builtin_success;
12614 if (act & DO_ALTPATH) {
12615 if (!(act & DO_ALTBLTIN))
12616 goto builtin_success;
12617 } else if (builtinloc <= 0) {
12618 goto builtin_success;
12622 #if ENABLE_FEATURE_SH_STANDALONE
12624 int applet_no = find_applet_by_name(name);
12625 if (applet_no >= 0) {
12626 entry->cmdtype = CMDNORMAL;
12627 entry->u.index = -2 - applet_no;
12633 /* We have to search path. */
12634 prev = -1; /* where to start */
12635 if (cmdp && cmdp->rehash) { /* doing a rehash */
12636 if (cmdp->cmdtype == CMDBUILTIN)
12639 prev = cmdp->param.index;
12645 while ((fullname = path_advance(&path, name)) != NULL) {
12646 stunalloc(fullname);
12647 /* NB: code below will still use fullname
12648 * despite it being "unallocated" */
12651 if (prefix(pathopt, "builtin")) {
12653 goto builtin_success;
12656 if ((act & DO_NOFUNC)
12657 || !prefix(pathopt, "func")
12658 ) { /* ignore unimplemented options */
12662 /* if rehash, don't redo absolute path names */
12663 if (fullname[0] == '/' && idx <= prev) {
12666 TRACE(("searchexec \"%s\": no change\n", name));
12669 while (stat(fullname, &statb) < 0) {
12671 if (errno == EINTR)
12674 if (errno != ENOENT && errno != ENOTDIR)
12678 e = EACCES; /* if we fail, this will be the error */
12679 if (!S_ISREG(statb.st_mode))
12681 if (pathopt) { /* this is a %func directory */
12682 stalloc(strlen(fullname) + 1);
12683 /* NB: stalloc will return space pointed by fullname
12684 * (because we don't have any intervening allocations
12685 * between stunalloc above and this stalloc) */
12686 readcmdfile(fullname);
12687 cmdp = cmdlookup(name, 0);
12688 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12689 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12690 stunalloc(fullname);
12693 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12695 entry->cmdtype = CMDNORMAL;
12696 entry->u.index = idx;
12700 cmdp = cmdlookup(name, 1);
12701 cmdp->cmdtype = CMDNORMAL;
12702 cmdp->param.index = idx;
12707 /* We failed. If there was an entry for this command, delete it */
12708 if (cmdp && updatetbl)
12709 delete_cmd_entry();
12711 ash_msg("%s: %s", name, errmsg(e, "not found"));
12712 entry->cmdtype = CMDUNKNOWN;
12717 entry->cmdtype = CMDBUILTIN;
12718 entry->u.cmd = bcmd;
12722 cmdp = cmdlookup(name, 1);
12723 cmdp->cmdtype = CMDBUILTIN;
12724 cmdp->param.cmd = bcmd;
12728 entry->cmdtype = cmdp->cmdtype;
12729 entry->u = cmdp->param;
12734 * The trap builtin.
12736 static int FAST_FUNC
12737 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12741 int signo, exitcode;
12746 for (signo = 0; signo < NSIG; signo++) {
12747 char *tr = trap_ptr[signo];
12749 /* note: bash adds "SIG", but only if invoked
12750 * as "bash". If called as "sh", or if set -o posix,
12751 * then it prints short signal names.
12752 * We are printing short names: */
12753 out1fmt("trap -- %s %s\n",
12755 get_signame(signo));
12756 /* trap_ptr != trap only if we are in special-cased `trap` code.
12757 * In this case, we will exit very soon, no need to free(). */
12758 /* if (trap_ptr != trap && tp[0]) */
12763 if (trap_ptr != trap) {
12776 signo = get_signum(*ap);
12778 /* Mimic bash message exactly */
12779 ash_msg("%s: invalid signal specification", *ap);
12785 if (LONE_DASH(action))
12788 action = ckstrdup(action);
12792 may_have_traps = 1;
12793 trap[signo] = action;
12804 /* ============ Builtins */
12806 #if ENABLE_ASH_HELP
12807 static int FAST_FUNC
12808 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12814 "Built-in commands:\n"
12815 "------------------\n");
12816 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12817 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12818 builtintab[i].name + 1);
12824 # if ENABLE_FEATURE_SH_STANDALONE
12826 const char *a = applet_names;
12828 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12833 while (*a++ != '\0')
12838 newline_and_flush(stdout);
12839 return EXIT_SUCCESS;
12844 static int FAST_FUNC
12845 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12847 show_history(line_input_state);
12848 return EXIT_SUCCESS;
12853 * The export and readonly commands.
12855 static int FAST_FUNC
12856 exportcmd(int argc UNUSED_PARAM, char **argv)
12866 /* "readonly" in bash accepts, but ignores -n.
12867 * We do the same: it saves a conditional in nextopt's param.
12870 while ((opt = nextopt("np")) != '\0') {
12872 flag_off = VEXPORT;
12875 if (argv[0][0] == 'r') {
12877 flag_off = 0; /* readonly ignores -n */
12879 flag_off = ~flag_off;
12881 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12887 p = strchr(name, '=');
12891 vp = *findvar(hashvar(name), name);
12893 vp->flags = ((vp->flags | flag) & flag_off);
12897 setvar(name, p, (flag & flag_off));
12898 } while ((name = *++aptr) != NULL);
12903 /* No arguments. Show the list of exported or readonly vars.
12906 showvars(argv[0], flag, 0);
12911 * Delete a function if it exists.
12914 unsetfunc(const char *name)
12916 struct tblentry *cmdp;
12918 cmdp = cmdlookup(name, 0);
12919 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12920 delete_cmd_entry();
12924 * The unset builtin command. We unset the function before we unset the
12925 * variable to allow a function to be unset when there is a readonly variable
12926 * with the same name.
12928 static int FAST_FUNC
12929 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12936 while ((i = nextopt("vf")) != 0) {
12940 for (ap = argptr; *ap; ap++) {
12953 static const unsigned char timescmd_str[] ALIGN1 = {
12954 ' ', offsetof(struct tms, tms_utime),
12955 '\n', offsetof(struct tms, tms_stime),
12956 ' ', offsetof(struct tms, tms_cutime),
12957 '\n', offsetof(struct tms, tms_cstime),
12960 static int FAST_FUNC
12961 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12963 unsigned long clk_tck, s, t;
12964 const unsigned char *p;
12967 clk_tck = bb_clk_tck();
12972 t = *(clock_t *)(((char *) &buf) + p[1]);
12975 out1fmt("%lum%lu.%03lus%c",
12977 (t * 1000) / clk_tck,
12985 #if ENABLE_SH_MATH_SUPPORT
12987 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12988 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12990 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12992 static int FAST_FUNC
12993 letcmd(int argc UNUSED_PARAM, char **argv)
12999 ash_msg_and_raise_error("expression expected");
13001 i = ash_arith(*argv);
13009 * The read builtin. Options:
13010 * -r Do not interpret '\' specially
13011 * -s Turn off echo (tty only)
13012 * -n NCHARS Read NCHARS max
13013 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13014 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13015 * -u FD Read from given FD instead of fd 0
13016 * This uses unbuffered input, which may be avoidable in some cases.
13017 * TODO: bash also has:
13018 * -a ARRAY Read into array[0],[1],etc
13019 * -d DELIM End on DELIM char, not newline
13020 * -e Use line editing (tty only)
13022 static int FAST_FUNC
13023 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13025 char *opt_n = NULL;
13026 char *opt_p = NULL;
13027 char *opt_t = NULL;
13028 char *opt_u = NULL;
13029 int read_flags = 0;
13033 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13042 read_flags |= BUILTIN_READ_SILENT;
13048 read_flags |= BUILTIN_READ_RAW;
13058 /* "read -s" needs to save/restore termios, can't allow ^C
13059 * to jump out of it.
13062 r = shell_builtin_read(setvar0,
13064 bltinlookup("IFS"), /* can be NULL */
13073 if ((uintptr_t)r > 1)
13074 ash_msg_and_raise_error(r);
13076 return (uintptr_t)r;
13079 static int FAST_FUNC
13080 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13082 static const char permuser[3] ALIGN1 = "ogu";
13085 int symbolic_mode = 0;
13087 while (nextopt("S") != '\0') {
13096 if (*argptr == NULL) {
13097 if (symbolic_mode) {
13098 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13105 *p++ = permuser[i];
13107 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13108 if (!(mask & 0400)) *p++ = 'r';
13109 if (!(mask & 0200)) *p++ = 'w';
13110 if (!(mask & 0100)) *p++ = 'x';
13118 out1fmt("%04o\n", mask);
13121 char *modestr = *argptr;
13122 /* numeric umasks are taken as-is */
13123 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13124 if (!isdigit(modestr[0]))
13126 mask = bb_parse_mode(modestr, mask);
13127 if ((unsigned)mask > 0777) {
13128 ash_msg_and_raise_error("illegal mode: %s", modestr);
13130 if (!isdigit(modestr[0]))
13137 static int FAST_FUNC
13138 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13140 return shell_builtin_ulimit(argv);
13143 /* ============ main() and helpers */
13146 * Called to exit the shell.
13155 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13156 save_history(line_input_state);
13158 status = exitstatus;
13159 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13160 if (setjmp(loc.loc)) {
13161 if (exception_type == EXEXIT)
13162 status = exitstatus;
13165 exception_handler = &loc;
13171 /*free(p); - we'll exit soon */
13174 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13175 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13178 flush_stdout_stderr();
13186 /* we will never free this */
13187 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13189 signal(SIGCHLD, SIG_DFL);
13190 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13191 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13193 signal(SIGHUP, SIG_DFL);
13198 struct stat st1, st2;
13201 for (envp = environ; envp && *envp; envp++) {
13202 p = endofname(*envp);
13203 if (p != *envp && *p == '=') {
13204 setvareq(*envp, VEXPORT|VTEXTFIXED);
13208 setvareq((char*)defoptindvar, VTEXTFIXED);
13210 setvar0("PPID", utoa(getppid()));
13211 #if ENABLE_ASH_BASH_COMPAT
13212 p = lookupvar("SHLVL");
13213 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13214 if (!lookupvar("HOSTNAME")) {
13215 struct utsname uts;
13217 setvar0("HOSTNAME", uts.nodename);
13220 p = lookupvar("PWD");
13222 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13223 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13233 //usage:#define ash_trivial_usage
13234 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13235 //usage:#define ash_full_usage "\n\n"
13236 //usage: "Unix shell interpreter"
13238 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13239 //usage:# define sh_trivial_usage ash_trivial_usage
13240 //usage:# define sh_full_usage ash_full_usage
13242 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13243 //usage:# define bash_trivial_usage ash_trivial_usage
13244 //usage:# define bash_full_usage ash_full_usage
13248 * Process the shell command line arguments.
13251 procargs(char **argv)
13254 const char *xminusc;
13259 /* if (xargv[0]) - mmm, this is always true! */
13261 for (i = 0; i < NOPTS; i++)
13264 if (options(/*cmdline:*/ 1)) {
13265 /* it already printed err message */
13266 raise_exception(EXERROR);
13270 if (*xargv == NULL) {
13272 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13275 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13279 for (i = 0; i < NOPTS; i++)
13280 if (optlist[i] == 2)
13285 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13290 } else if (!sflag) {
13291 setinputfile(*xargv, 0);
13294 commandname = arg0;
13297 shellparam.p = xargv;
13298 #if ENABLE_ASH_GETOPTS
13299 shellparam.optind = 1;
13300 shellparam.optoff = -1;
13302 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13304 shellparam.nparam++;
13311 * Read /etc/profile or .profile.
13314 read_profile(const char *name)
13316 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13323 * This routine is called when an error or an interrupt occurs in an
13324 * interactive shell and control is returned to the main command loop.
13332 /* from input.c: */
13333 g_parsefile->left_in_buffer = 0;
13334 g_parsefile->left_in_line = 0; /* clear input buffer */
13336 /* from parser.c: */
13339 /* from redir.c: */
13340 clearredir(/*drop:*/ 0);
13344 static short profile_buf[16384];
13345 extern int etext();
13349 * Main routine. We initialize things, parse the arguments, execute
13350 * profiles if we're a login shell, and then call cmdloop to execute
13351 * commands. The setjmp call sets up the location to jump to when an
13352 * exception occurs. When an exception occurs the variable "state"
13353 * is used to figure out how far we had gotten.
13355 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13356 int ash_main(int argc UNUSED_PARAM, char **argv)
13358 const char *shinit;
13359 volatile smallint state;
13360 struct jmploc jmploc;
13361 struct stackmark smark;
13363 /* Initialize global data */
13367 #if ENABLE_ASH_ALIAS
13373 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13376 #if ENABLE_FEATURE_EDITING
13377 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13380 if (setjmp(jmploc.loc)) {
13386 e = exception_type;
13388 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13392 newline_and_flush(stderr);
13395 popstackmark(&smark);
13396 FORCE_INT_ON; /* enable interrupts */
13405 exception_handler = &jmploc;
13408 TRACE(("Shell args: "));
13409 trace_puts_args(argv);
13411 rootpid = getpid();
13414 setstackmark(&smark);
13417 if (argv[0] && argv[0][0] == '-')
13423 read_profile("/etc/profile");
13426 hp = lookupvar("HOME");
13428 hp = concat_path_file(hp, ".profile");
13437 getuid() == geteuid() && getgid() == getegid() &&
13441 shinit = lookupvar("ENV");
13442 if (shinit != NULL && *shinit != '\0') {
13443 read_profile(shinit);
13449 /* evalstring pushes parsefile stack.
13450 * Ensure we don't falsely claim that 0 (stdin)
13451 * is one of stacked source fds.
13452 * Testcase: ash -c 'exec 1>&0' must not complain. */
13453 // if (!sflag) g_parsefile->pf_fd = -1;
13454 // ^^ not necessary since now we special-case fd 0
13455 // in is_hidden_fd() to not be considered "hidden fd"
13456 evalstring(minusc, 0);
13459 if (sflag || minusc == NULL) {
13460 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13462 const char *hp = lookupvar("HISTFILE");
13464 hp = lookupvar("HOME");
13466 hp = concat_path_file(hp, ".ash_history");
13467 setvar0("HISTFILE", hp);
13469 hp = lookupvar("HISTFILE");
13473 line_input_state->hist_file = hp;
13474 # if ENABLE_FEATURE_SH_HISTFILESIZE
13475 hp = lookupvar("HISTFILESIZE");
13476 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13480 state4: /* XXX ??? - why isn't this before the "if" statement */
13488 extern void _mcleanup(void);
13492 TRACE(("End of main reached\n"));
13499 * Copyright (c) 1989, 1991, 1993, 1994
13500 * The Regents of the University of California. All rights reserved.
13502 * This code is derived from software contributed to Berkeley by
13503 * Kenneth Almquist.
13505 * Redistribution and use in source and binary forms, with or without
13506 * modification, are permitted provided that the following conditions
13508 * 1. Redistributions of source code must retain the above copyright
13509 * notice, this list of conditions and the following disclaimer.
13510 * 2. Redistributions in binary form must reproduce the above copyright
13511 * notice, this list of conditions and the following disclaimer in the
13512 * documentation and/or other materials provided with the distribution.
13513 * 3. Neither the name of the University nor the names of its contributors
13514 * may be used to endorse or promote products derived from this software
13515 * without specific prior written permission.
13517 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13518 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13519 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13520 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13521 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13522 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13523 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13524 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13525 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13526 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF