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 EXSHELLPROC 2 /* execute a shell procedure */
305 #define EXEXEC 3 /* command execution failed */
306 #define EXEXIT 4 /* exit the shell */
307 #define EXSIG 5 /* trapped signal in wait(1) */
310 char nullstr[1]; /* zero length string */
313 #define eflag optlist[0]
314 #define fflag optlist[1]
315 #define Iflag optlist[2]
316 #define iflag optlist[3]
317 #define mflag optlist[4]
318 #define nflag optlist[5]
319 #define sflag optlist[6]
320 #define xflag optlist[7]
321 #define vflag optlist[8]
322 #define Cflag optlist[9]
323 #define aflag optlist[10]
324 #define bflag optlist[11]
325 #define uflag optlist[12]
326 #define viflag optlist[13]
327 #if ENABLE_ASH_BASH_COMPAT
328 # define pipefail optlist[14]
333 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
334 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
337 /* trap handler commands */
339 * Sigmode records the current value of the signal handlers for the various
340 * modes. A value of zero means that the current handler is not known.
341 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
343 char sigmode[NSIG - 1];
344 #define S_DFL 1 /* default signal handling (SIG_DFL) */
345 #define S_CATCH 2 /* signal is caught */
346 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
347 #define S_HARD_IGN 4 /* signal is ignored permanently */
349 /* indicates specified signal received */
350 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
351 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
353 char **trap_ptr; /* used only by "trap hack" */
355 /* Rarely referenced stuff */
356 #if ENABLE_ASH_RANDOM_SUPPORT
359 pid_t backgndpid; /* pid of last background process */
361 extern struct globals_misc *const ash_ptr_to_globals_misc;
362 #define G_misc (*ash_ptr_to_globals_misc)
363 #define exitstatus (G_misc.exitstatus )
364 #define back_exitstatus (G_misc.back_exitstatus )
365 #define job_warning (G_misc.job_warning)
366 #define rootpid (G_misc.rootpid )
367 #define shlvl (G_misc.shlvl )
368 #define minusc (G_misc.minusc )
369 #define curdir (G_misc.curdir )
370 #define physdir (G_misc.physdir )
371 #define arg0 (G_misc.arg0 )
372 #define exception_handler (G_misc.exception_handler)
373 #define exception_type (G_misc.exception_type )
374 #define suppress_int (G_misc.suppress_int )
375 #define pending_int (G_misc.pending_int )
376 #define pending_sig (G_misc.pending_sig )
377 #define isloginsh (G_misc.isloginsh )
378 #define nullstr (G_misc.nullstr )
379 #define optlist (G_misc.optlist )
380 #define sigmode (G_misc.sigmode )
381 #define gotsig (G_misc.gotsig )
382 #define may_have_traps (G_misc.may_have_traps )
383 #define trap (G_misc.trap )
384 #define trap_ptr (G_misc.trap_ptr )
385 #define random_gen (G_misc.random_gen )
386 #define backgndpid (G_misc.backgndpid )
387 #define INIT_G_misc() do { \
388 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
396 /* ============ DEBUG */
398 static void trace_printf(const char *fmt, ...);
399 static void trace_vprintf(const char *fmt, va_list va);
400 # define TRACE(param) trace_printf param
401 # define TRACEV(param) trace_vprintf param
402 # define close(fd) do { \
404 if (close(dfd) < 0) \
405 bb_error_msg("bug on %d: closing %d(0x%x)", \
406 __LINE__, dfd, dfd); \
409 # define TRACE(param)
410 # define TRACEV(param)
414 /* ============ Utility functions */
415 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
416 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
419 isdigit_str9(const char *str)
421 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
422 while (--maxlen && isdigit(*str))
424 return (*str == '\0');
428 var_end(const char *var)
437 /* ============ Interrupts / exceptions */
439 static void exitshell(void) NORETURN;
442 * These macros allow the user to suspend the handling of interrupt signals
443 * over a period of time. This is similar to SIGHOLD or to sigblock, but
444 * much more efficient and portable. (But hacking the kernel is so much
445 * more fun than worrying about efficiency and portability. :-))
447 #define INT_OFF do { \
453 * Called to raise an exception. Since C doesn't include exceptions, we
454 * just do a longjmp to the exception handler. The type of exception is
455 * stored in the global variable "exception_type".
457 static void raise_exception(int) NORETURN;
459 raise_exception(int e)
462 if (exception_handler == NULL)
467 longjmp(exception_handler->loc, 1);
470 #define raise_exception(e) do { \
471 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
472 raise_exception(e); \
477 * Called when a SIGINT is received. (If the user specifies
478 * that SIGINT is to be trapped or ignored using the trap builtin, then
479 * this routine is not called.) Suppressint is nonzero when interrupts
480 * are held using the INT_OFF macro. (The test for iflag is just
481 * defensive programming.)
483 static void raise_interrupt(void) NORETURN;
485 raise_interrupt(void)
490 /* Signal is not automatically unmasked after it is raised,
491 * do it ourself - unmask all signals */
492 sigprocmask_allsigs(SIG_UNBLOCK);
493 /* pending_sig = 0; - now done in signal_handler() */
496 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
497 if (!(rootshell && iflag)) {
498 /* Kill ourself with SIGINT */
499 signal(SIGINT, SIG_DFL);
504 /* bash: ^C even on empty command line sets $? */
505 exitstatus = SIGINT + 128;
506 raise_exception(ex_type);
510 #define raise_interrupt() do { \
511 TRACE(("raising interrupt on line %d\n", __LINE__)); \
516 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
520 if (--suppress_int == 0 && pending_int) {
524 #define INT_ON int_on()
525 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
533 #define FORCE_INT_ON force_int_on()
535 #define SAVE_INT(v) ((v) = suppress_int)
537 #define RESTORE_INT(v) do { \
539 suppress_int = (v); \
540 if (suppress_int == 0 && pending_int) \
545 /* ============ Stdout/stderr output */
548 outstr(const char *p, FILE *file)
556 flush_stdout_stderr(void)
563 /* Was called outcslow(c,FILE*), but c was always '\n' */
565 newline_and_flush(FILE *dest)
573 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
575 out1fmt(const char *fmt, ...)
582 r = vprintf(fmt, ap);
588 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
590 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
597 ret = vsnprintf(outbuf, length, fmt, ap);
604 out1str(const char *p)
610 out2str(const char *p)
613 flush_stdout_stderr();
617 /* ============ Parser structures */
619 /* control characters in argument strings */
620 #define CTL_FIRST CTLESC
621 #define CTLESC ((unsigned char)'\201') /* escape next character */
622 #define CTLVAR ((unsigned char)'\202') /* variable defn */
623 #define CTLENDVAR ((unsigned char)'\203')
624 #define CTLBACKQ ((unsigned char)'\204')
625 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
626 #define CTLENDARI ((unsigned char)'\207')
627 #define CTLQUOTEMARK ((unsigned char)'\210')
628 #define CTL_LAST CTLQUOTEMARK
630 /* variable substitution byte (follows CTLVAR) */
631 #define VSTYPE 0x0f /* type of variable substitution */
632 #define VSNUL 0x10 /* colon--treat the empty string as unset */
634 /* values of VSTYPE field */
635 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
636 #define VSMINUS 0x2 /* ${var-text} */
637 #define VSPLUS 0x3 /* ${var+text} */
638 #define VSQUESTION 0x4 /* ${var?message} */
639 #define VSASSIGN 0x5 /* ${var=text} */
640 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
641 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
642 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
643 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
644 #define VSLENGTH 0xa /* ${#var} */
645 #if ENABLE_ASH_BASH_COMPAT
646 #define VSSUBSTR 0xc /* ${var:position:length} */
647 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
648 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
651 static const char dolatstr[] ALIGN1 = {
652 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
654 #define DOLATSTRLEN 6
673 #if ENABLE_ASH_BASH_COMPAT
690 smallint type; /* Nxxxx */
693 union node *redirect;
698 smallint pipe_backgnd;
699 struct nodelist *cmdlist;
705 union node *redirect;
718 union node *elsepart;
745 struct nodelist *backquote;
748 /* nfile and ndup layout must match!
749 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
750 * that it is actually NTO2 (>&file), and change its type.
767 char *_unused_expfname;
786 struct nredir nredir;
787 struct nbinary nbinary;
791 struct nclist nclist;
800 * NODE_EOF is returned by parsecmd when it encounters an end of file.
801 * It must be distinct from NULL.
803 #define NODE_EOF ((union node *) -1L)
806 struct nodelist *next;
819 freefunc(struct funcnode *f)
821 if (f && --f->count < 0)
826 /* ============ Debugging output */
830 static FILE *tracefile;
833 trace_printf(const char *fmt, ...)
840 fprintf(tracefile, "%u ", (int) time(NULL));
842 fprintf(tracefile, "[%u] ", (int) getpid());
844 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
846 vfprintf(tracefile, fmt, va);
851 trace_vprintf(const char *fmt, va_list va)
856 fprintf(tracefile, "%u ", (int) time(NULL));
858 fprintf(tracefile, "[%u] ", (int) getpid());
860 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
861 vfprintf(tracefile, fmt, va);
865 trace_puts(const char *s)
873 trace_puts_quoted(char *s)
880 putc('"', tracefile);
881 for (p = s; *p; p++) {
882 switch ((unsigned char)*p) {
883 case '\n': c = 'n'; goto backslash;
884 case '\t': c = 't'; goto backslash;
885 case '\r': c = 'r'; goto backslash;
886 case '\"': c = '\"'; goto backslash;
887 case '\\': c = '\\'; goto backslash;
888 case CTLESC: c = 'e'; goto backslash;
889 case CTLVAR: c = 'v'; goto backslash;
890 case CTLBACKQ: c = 'q'; goto backslash;
892 putc('\\', tracefile);
896 if (*p >= ' ' && *p <= '~')
899 putc('\\', tracefile);
900 putc((*p >> 6) & 03, tracefile);
901 putc((*p >> 3) & 07, tracefile);
902 putc(*p & 07, tracefile);
907 putc('"', tracefile);
911 trace_puts_args(char **ap)
918 trace_puts_quoted(*ap);
920 putc('\n', tracefile);
923 putc(' ', tracefile);
938 /* leave open because libedit might be using it */
941 strcpy(s, "./trace");
943 if (!freopen(s, "a", tracefile)) {
944 fprintf(stderr, "Can't re-open %s\n", s);
949 tracefile = fopen(s, "a");
950 if (tracefile == NULL) {
951 fprintf(stderr, "Can't open %s\n", s);
957 flags = fcntl(fileno(tracefile), F_GETFL);
959 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
961 setlinebuf(tracefile);
962 fputs("\nTracing started.\n", tracefile);
966 indent(int amount, char *pfx, FILE *fp)
970 for (i = 0; i < amount; i++) {
971 if (pfx && i == amount - 1)
977 /* little circular references here... */
978 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
981 sharg(union node *arg, FILE *fp)
984 struct nodelist *bqlist;
985 unsigned char subtype;
987 if (arg->type != NARG) {
988 out1fmt("<node type %d>\n", arg->type);
991 bqlist = arg->narg.backquote;
992 for (p = arg->narg.text; *p; p++) {
993 switch ((unsigned char)*p) {
1002 if (subtype == VSLENGTH)
1010 if (subtype & VSNUL)
1013 switch (subtype & VSTYPE) {
1039 case VSTRIMRIGHTMAX:
1046 out1fmt("<subtype %d>", subtype);
1055 shtree(bqlist->n, -1, NULL, fp);
1066 shcmd(union node *cmd, FILE *fp)
1074 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1080 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1084 switch (np->nfile.type) {
1085 case NTO: s = ">>"+1; dftfd = 1; break;
1086 case NCLOBBER: s = ">|"; dftfd = 1; break;
1087 case NAPPEND: s = ">>"; dftfd = 1; break;
1088 #if ENABLE_ASH_BASH_COMPAT
1091 case NTOFD: s = ">&"; dftfd = 1; break;
1092 case NFROM: s = "<"; break;
1093 case NFROMFD: s = "<&"; break;
1094 case NFROMTO: s = "<>"; break;
1095 default: s = "*error*"; break;
1097 if (np->nfile.fd != dftfd)
1098 fprintf(fp, "%d", np->nfile.fd);
1100 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1101 fprintf(fp, "%d", np->ndup.dupfd);
1103 sharg(np->nfile.fname, fp);
1110 shtree(union node *n, int ind, char *pfx, FILE *fp)
1112 struct nodelist *lp;
1118 indent(ind, pfx, fp);
1120 if (n == NODE_EOF) {
1135 shtree(n->nbinary.ch1, ind, NULL, fp);
1138 shtree(n->nbinary.ch2, ind, NULL, fp);
1146 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1147 shtree(lp->n, 0, NULL, fp);
1151 if (n->npipe.pipe_backgnd)
1157 fprintf(fp, "<node type %d>", n->type);
1165 showtree(union node *n)
1167 trace_puts("showtree called\n");
1168 shtree(n, 1, NULL, stderr);
1174 /* ============ Parser data */
1177 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1180 struct strlist *next;
1187 struct strpush *prev; /* preceding string on stack */
1189 int prev_left_in_line;
1190 #if ENABLE_ASH_ALIAS
1191 struct alias *ap; /* if push was associated with an alias */
1193 char *string; /* remember the string since it may change */
1195 /* Remember last two characters for pungetc. */
1198 /* Number of outstanding calls to pungetc. */
1203 struct parsefile *prev; /* preceding file on stack */
1204 int linno; /* current line */
1205 int pf_fd; /* file descriptor (or -1 if string) */
1206 int left_in_line; /* number of chars left in this line */
1207 int left_in_buffer; /* number of chars left in this buffer past the line */
1208 char *next_to_pgetc; /* next char in buffer */
1209 char *buf; /* input buffer */
1210 struct strpush *strpush; /* for pushing strings at this level */
1211 struct strpush basestrpush; /* so pushing one is fast */
1213 /* Remember last two characters for pungetc. */
1216 /* Number of outstanding calls to pungetc. */
1220 static struct parsefile basepf; /* top level input file */
1221 static struct parsefile *g_parsefile = &basepf; /* current input file */
1222 static int startlinno; /* line # where last token started */
1223 static char *commandname; /* currently executing command */
1224 static struct strlist *cmdenviron; /* environment for builtin command */
1227 /* ============ Message printing */
1230 ash_vmsg(const char *msg, va_list ap)
1232 fprintf(stderr, "%s: ", arg0);
1234 if (strcmp(arg0, commandname))
1235 fprintf(stderr, "%s: ", commandname);
1236 if (!iflag || g_parsefile->pf_fd > 0)
1237 fprintf(stderr, "line %d: ", startlinno);
1239 vfprintf(stderr, msg, ap);
1240 newline_and_flush(stderr);
1244 * Exverror is called to raise the error exception. If the second argument
1245 * is not NULL then error prints an error message using printf style
1246 * formatting. It then raises the error exception.
1248 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1250 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1254 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1256 TRACE(("\") pid=%d\n", getpid()));
1258 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1263 flush_stdout_stderr();
1264 raise_exception(cond);
1268 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1270 ash_msg_and_raise_error(const char *msg, ...)
1275 ash_vmsg_and_raise(EXERROR, msg, ap);
1280 static void raise_error_syntax(const char *) NORETURN;
1282 raise_error_syntax(const char *msg)
1284 ash_msg_and_raise_error("syntax error: %s", msg);
1288 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1290 ash_msg_and_raise(int cond, const char *msg, ...)
1295 ash_vmsg_and_raise(cond, msg, ap);
1301 * error/warning routines for external builtins
1304 ash_msg(const char *fmt, ...)
1314 * Return a string describing an error. The returned string may be a
1315 * pointer to a static buffer that will be overwritten on the next call.
1316 * Action describes the operation that got the error.
1319 errmsg(int e, const char *em)
1321 if (e == ENOENT || e == ENOTDIR) {
1328 /* ============ Memory allocation */
1331 /* I consider these wrappers nearly useless:
1332 * ok, they return you to nearest exception handler, but
1333 * how much memory do you leak in the process, making
1334 * memory starvation worse?
1337 ckrealloc(void * p, size_t nbytes)
1339 p = realloc(p, nbytes);
1341 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1346 ckmalloc(size_t nbytes)
1348 return ckrealloc(NULL, nbytes);
1352 ckzalloc(size_t nbytes)
1354 return memset(ckmalloc(nbytes), 0, nbytes);
1358 ckstrdup(const char *s)
1360 char *p = strdup(s);
1362 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1366 /* Using bbox equivalents. They exit if out of memory */
1367 # define ckrealloc xrealloc
1368 # define ckmalloc xmalloc
1369 # define ckzalloc xzalloc
1370 # define ckstrdup xstrdup
1374 * It appears that grabstackstr() will barf with such alignments
1375 * because stalloc() will return a string allocated in a new stackblock.
1377 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1379 /* Most machines require the value returned from malloc to be aligned
1380 * in some way. The following macro will get this right
1381 * on many machines. */
1382 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1383 /* Minimum size of a block */
1384 MINSIZE = SHELL_ALIGN(504),
1387 struct stack_block {
1388 struct stack_block *prev;
1389 char space[MINSIZE];
1393 struct stack_block *stackp;
1399 struct globals_memstack {
1400 struct stack_block *g_stackp; // = &stackbase;
1401 char *g_stacknxt; // = stackbase.space;
1402 char *sstrend; // = stackbase.space + MINSIZE;
1403 size_t g_stacknleft; // = MINSIZE;
1404 int herefd; // = -1;
1405 struct stack_block stackbase;
1407 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1408 #define G_memstack (*ash_ptr_to_globals_memstack)
1409 #define g_stackp (G_memstack.g_stackp )
1410 #define g_stacknxt (G_memstack.g_stacknxt )
1411 #define sstrend (G_memstack.sstrend )
1412 #define g_stacknleft (G_memstack.g_stacknleft)
1413 #define herefd (G_memstack.herefd )
1414 #define stackbase (G_memstack.stackbase )
1415 #define INIT_G_memstack() do { \
1416 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1418 g_stackp = &stackbase; \
1419 g_stacknxt = stackbase.space; \
1420 g_stacknleft = MINSIZE; \
1421 sstrend = stackbase.space + MINSIZE; \
1426 #define stackblock() ((void *)g_stacknxt)
1427 #define stackblocksize() g_stacknleft
1430 * Parse trees for commands are allocated in lifo order, so we use a stack
1431 * to make this more efficient, and also to avoid all sorts of exception
1432 * handling code to handle interrupts in the middle of a parse.
1434 * The size 504 was chosen because the Ultrix malloc handles that size
1438 stalloc(size_t nbytes)
1443 aligned = SHELL_ALIGN(nbytes);
1444 if (aligned > g_stacknleft) {
1447 struct stack_block *sp;
1449 blocksize = aligned;
1450 if (blocksize < MINSIZE)
1451 blocksize = MINSIZE;
1452 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1453 if (len < blocksize)
1454 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1457 sp->prev = g_stackp;
1458 g_stacknxt = sp->space;
1459 g_stacknleft = blocksize;
1460 sstrend = g_stacknxt + blocksize;
1465 g_stacknxt += aligned;
1466 g_stacknleft -= aligned;
1471 stzalloc(size_t nbytes)
1473 return memset(stalloc(nbytes), 0, nbytes);
1480 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1481 write(STDERR_FILENO, "stunalloc\n", 10);
1485 g_stacknleft += g_stacknxt - (char *)p;
1490 * Like strdup but works with the ash stack.
1493 sstrdup(const char *p)
1495 size_t len = strlen(p) + 1;
1496 return memcpy(stalloc(len), p, len);
1500 grabstackblock(size_t len)
1502 len = SHELL_ALIGN(len);
1504 g_stacknleft -= len;
1508 pushstackmark(struct stackmark *mark, size_t len)
1510 mark->stackp = g_stackp;
1511 mark->stacknxt = g_stacknxt;
1512 mark->stacknleft = g_stacknleft;
1513 grabstackblock(len);
1517 setstackmark(struct stackmark *mark)
1519 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1523 popstackmark(struct stackmark *mark)
1525 struct stack_block *sp;
1531 while (g_stackp != mark->stackp) {
1533 g_stackp = sp->prev;
1536 g_stacknxt = mark->stacknxt;
1537 g_stacknleft = mark->stacknleft;
1538 sstrend = mark->stacknxt + mark->stacknleft;
1543 * When the parser reads in a string, it wants to stick the string on the
1544 * stack and only adjust the stack pointer when it knows how big the
1545 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1546 * of space on top of the stack and stackblocklen returns the length of
1547 * this block. Growstackblock will grow this space by at least one byte,
1548 * possibly moving it (like realloc). Grabstackblock actually allocates the
1549 * part of the block that has been used.
1552 growstackblock(void)
1556 newlen = g_stacknleft * 2;
1557 if (newlen < g_stacknleft)
1558 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1562 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1563 struct stack_block *sp;
1564 struct stack_block *prevstackp;
1569 prevstackp = sp->prev;
1570 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1571 sp = ckrealloc(sp, grosslen);
1572 sp->prev = prevstackp;
1574 g_stacknxt = sp->space;
1575 g_stacknleft = newlen;
1576 sstrend = sp->space + newlen;
1579 char *oldspace = g_stacknxt;
1580 size_t oldlen = g_stacknleft;
1581 char *p = stalloc(newlen);
1583 /* free the space we just allocated */
1584 g_stacknxt = memcpy(p, oldspace, oldlen);
1585 g_stacknleft += newlen;
1590 * The following routines are somewhat easier to use than the above.
1591 * The user declares a variable of type STACKSTR, which may be declared
1592 * to be a register. The macro STARTSTACKSTR initializes things. Then
1593 * the user uses the macro STPUTC to add characters to the string. In
1594 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1595 * grown as necessary. When the user is done, she can just leave the
1596 * string there and refer to it using stackblock(). Or she can allocate
1597 * the space for it using grabstackstr(). If it is necessary to allow
1598 * someone else to use the stack temporarily and then continue to grow
1599 * the string, the user should use grabstack to allocate the space, and
1600 * then call ungrabstr(p) to return to the previous mode of operation.
1602 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1603 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1604 * is space for at least one character.
1609 size_t len = stackblocksize();
1610 if (herefd >= 0 && len >= 1024) {
1611 full_write(herefd, stackblock(), len);
1612 return stackblock();
1615 return (char *)stackblock() + len;
1619 * Called from CHECKSTRSPACE.
1622 makestrspace(size_t newlen, char *p)
1624 size_t len = p - g_stacknxt;
1630 size = stackblocksize();
1632 if (nleft >= newlen)
1636 return (char *)stackblock() + len;
1640 stack_nputstr(const char *s, size_t n, char *p)
1642 p = makestrspace(n, p);
1643 p = (char *)memcpy(p, s, n) + n;
1648 stack_putstr(const char *s, char *p)
1650 return stack_nputstr(s, strlen(s), p);
1654 _STPUTC(int c, char *p)
1662 #define STARTSTACKSTR(p) ((p) = stackblock())
1663 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1664 #define CHECKSTRSPACE(n, p) do { \
1667 size_t m = sstrend - q; \
1669 (p) = makestrspace(l, q); \
1671 #define USTPUTC(c, p) (*(p)++ = (c))
1672 #define STACKSTRNUL(p) do { \
1673 if ((p) == sstrend) \
1674 (p) = growstackstr(); \
1677 #define STUNPUTC(p) (--(p))
1678 #define STTOPC(p) ((p)[-1])
1679 #define STADJUST(amount, p) ((p) += (amount))
1681 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1682 #define ungrabstackstr(s, p) stunalloc(s)
1683 #define stackstrend() ((void *)sstrend)
1686 /* ============ String helpers */
1689 * prefix -- see if pfx is a prefix of string.
1692 prefix(const char *string, const char *pfx)
1695 if (*pfx++ != *string++)
1698 return (char *) string;
1702 * Check for a valid number. This should be elsewhere.
1705 is_number(const char *p)
1710 } while (*++p != '\0');
1715 * Convert a string of digits to an integer, printing an error message on
1719 number(const char *s)
1722 ash_msg_and_raise_error(msg_illnum, s);
1727 * Produce a possibly single quoted string suitable as input to the shell.
1728 * The return string is allocated on the stack.
1731 single_quote(const char *s)
1741 len = strchrnul(s, '\'') - s;
1743 q = p = makestrspace(len + 3, p);
1746 q = (char *)memcpy(q, s, len) + len;
1755 do len++; while (*++s == '\'');
1757 q = p = makestrspace(len + 3, p);
1760 q = (char *)memcpy(q, s - len, len) + len;
1768 return stackblock();
1772 /* ============ nextopt */
1774 static char **argptr; /* argument list for builtin commands */
1775 static char *optionarg; /* set by nextopt (like getopt) */
1776 static char *optptr; /* used by nextopt */
1779 * XXX - should get rid of. Have all builtins use getopt(3).
1780 * The library getopt must have the BSD extension static variable
1781 * "optreset", otherwise it can't be used within the shell safely.
1783 * Standard option processing (a la getopt) for builtin routines.
1784 * The only argument that is passed to nextopt is the option string;
1785 * the other arguments are unnecessary. It returns the character,
1786 * or '\0' on end of input.
1789 nextopt(const char *optstring)
1796 if (p == NULL || *p == '\0') {
1797 /* We ate entire "-param", take next one */
1803 if (*++p == '\0') /* just "-" ? */
1806 if (LONE_DASH(p)) /* "--" ? */
1808 /* p => next "-param" */
1810 /* p => some option char in the middle of a "-param" */
1812 for (q = optstring; *q != c;) {
1814 ash_msg_and_raise_error("illegal option -%c", c);
1822 ash_msg_and_raise_error("no arg for -%c option", c);
1832 /* ============ Shell variables */
1835 * The parsefile structure pointed to by the global variable parsefile
1836 * contains information about the current file being read.
1839 int nparam; /* # of positional parameters (without $0) */
1840 #if ENABLE_ASH_GETOPTS
1841 int optind; /* next parameter to be processed by getopts */
1842 int optoff; /* used by getopts */
1844 unsigned char malloced; /* if parameter list dynamically allocated */
1845 char **p; /* parameter list */
1849 * Free the list of positional parameters.
1852 freeparam(volatile struct shparam *param)
1854 if (param->malloced) {
1856 ap = ap1 = param->p;
1863 #if ENABLE_ASH_GETOPTS
1864 static void FAST_FUNC getoptsreset(const char *value);
1868 struct var *next; /* next entry in hash list */
1869 int flags; /* flags are defined above */
1870 const char *var_text; /* name=value */
1871 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1872 /* the variable gets set/unset */
1876 struct localvar *next; /* next local variable in list */
1877 struct var *vp; /* the variable that was made local */
1878 int flags; /* saved flags */
1879 const char *text; /* saved text */
1883 #define VEXPORT 0x01 /* variable is exported */
1884 #define VREADONLY 0x02 /* variable cannot be modified */
1885 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1886 #define VTEXTFIXED 0x08 /* text is statically allocated */
1887 #define VSTACK 0x10 /* text is allocated on the stack */
1888 #define VUNSET 0x20 /* the variable is not set */
1889 #define VNOFUNC 0x40 /* don't call the callback function */
1890 #define VNOSET 0x80 /* do not set variable - just readonly test */
1891 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1892 #if ENABLE_ASH_RANDOM_SUPPORT
1893 # define VDYNAMIC 0x200 /* dynamic variable */
1899 /* Need to be before varinit_data[] */
1900 #if ENABLE_LOCALE_SUPPORT
1901 static void FAST_FUNC
1902 change_lc_all(const char *value)
1904 if (value && *value != '\0')
1905 setlocale(LC_ALL, value);
1907 static void FAST_FUNC
1908 change_lc_ctype(const char *value)
1910 if (value && *value != '\0')
1911 setlocale(LC_CTYPE, value);
1915 static void chkmail(void);
1916 static void changemail(const char *var_value) FAST_FUNC;
1918 # define chkmail() ((void)0)
1920 static void changepath(const char *) FAST_FUNC;
1921 #if ENABLE_ASH_RANDOM_SUPPORT
1922 static void change_random(const char *) FAST_FUNC;
1925 static const struct {
1927 const char *var_text;
1928 void (*var_func)(const char *) FAST_FUNC;
1929 } varinit_data[] = {
1931 * Note: VEXPORT would not work correctly here for NOFORK applets:
1932 * some environment strings may be constant.
1934 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1936 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1937 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1939 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1940 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1941 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1942 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1943 #if ENABLE_ASH_GETOPTS
1944 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1946 #if ENABLE_ASH_RANDOM_SUPPORT
1947 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1949 #if ENABLE_LOCALE_SUPPORT
1950 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1951 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1953 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1960 struct globals_var {
1961 struct shparam shellparam; /* $@ current positional parameters */
1962 struct redirtab *redirlist;
1964 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1965 struct var *vartab[VTABSIZE];
1966 struct var varinit[ARRAY_SIZE(varinit_data)];
1968 extern struct globals_var *const ash_ptr_to_globals_var;
1969 #define G_var (*ash_ptr_to_globals_var)
1970 #define shellparam (G_var.shellparam )
1971 //#define redirlist (G_var.redirlist )
1972 #define g_nullredirs (G_var.g_nullredirs )
1973 #define preverrout_fd (G_var.preverrout_fd)
1974 #define vartab (G_var.vartab )
1975 #define varinit (G_var.varinit )
1976 #define INIT_G_var() do { \
1978 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1980 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1981 varinit[i].flags = varinit_data[i].flags; \
1982 varinit[i].var_text = varinit_data[i].var_text; \
1983 varinit[i].var_func = varinit_data[i].var_func; \
1987 #define vifs varinit[0]
1989 # define vmail (&vifs)[1]
1990 # define vmpath (&vmail)[1]
1991 # define vpath (&vmpath)[1]
1993 # define vpath (&vifs)[1]
1995 #define vps1 (&vpath)[1]
1996 #define vps2 (&vps1)[1]
1997 #define vps4 (&vps2)[1]
1998 #if ENABLE_ASH_GETOPTS
1999 # define voptind (&vps4)[1]
2000 # if ENABLE_ASH_RANDOM_SUPPORT
2001 # define vrandom (&voptind)[1]
2004 # if ENABLE_ASH_RANDOM_SUPPORT
2005 # define vrandom (&vps4)[1]
2010 * The following macros access the values of the above variables.
2011 * They have to skip over the name. They return the null string
2012 * for unset variables.
2014 #define ifsval() (vifs.var_text + 4)
2015 #define ifsset() ((vifs.flags & VUNSET) == 0)
2017 # define mailval() (vmail.var_text + 5)
2018 # define mpathval() (vmpath.var_text + 9)
2019 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2021 #define pathval() (vpath.var_text + 5)
2022 #define ps1val() (vps1.var_text + 4)
2023 #define ps2val() (vps2.var_text + 4)
2024 #define ps4val() (vps4.var_text + 4)
2025 #if ENABLE_ASH_GETOPTS
2026 # define optindval() (voptind.var_text + 7)
2029 #if ENABLE_ASH_GETOPTS
2030 static void FAST_FUNC
2031 getoptsreset(const char *value)
2033 shellparam.optind = number(value);
2034 shellparam.optoff = -1;
2039 * Compares two strings up to the first = or '\0'. The first
2040 * string must be terminated by '='; the second may be terminated by
2041 * either '=' or '\0'.
2044 varcmp(const char *p, const char *q)
2048 while ((c = *p) == (d = *q)) {
2049 if (c == '\0' || c == '=')
2063 * Find the appropriate entry in the hash table from the name.
2065 static struct var **
2066 hashvar(const char *p)
2070 hashval = ((unsigned char) *p) << 4;
2071 while (*p && *p != '=')
2072 hashval += (unsigned char) *p++;
2073 return &vartab[hashval % VTABSIZE];
2077 vpcmp(const void *a, const void *b)
2079 return varcmp(*(const char **)a, *(const char **)b);
2083 * This routine initializes the builtin variables.
2093 * PS1 depends on uid
2095 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2096 vps1.var_text = "PS1=\\w \\$ ";
2099 vps1.var_text = "PS1=# ";
2102 end = vp + ARRAY_SIZE(varinit);
2104 vpp = hashvar(vp->var_text);
2107 } while (++vp < end);
2110 static struct var **
2111 findvar(struct var **vpp, const char *name)
2113 for (; *vpp; vpp = &(*vpp)->next) {
2114 if (varcmp((*vpp)->var_text, name) == 0) {
2122 * Find the value of a variable. Returns NULL if not set.
2124 static const char* FAST_FUNC
2125 lookupvar(const char *name)
2129 v = *findvar(hashvar(name), name);
2131 #if ENABLE_ASH_RANDOM_SUPPORT
2133 * Dynamic variables are implemented roughly the same way they are
2134 * in bash. Namely, they're "special" so long as they aren't unset.
2135 * As soon as they're unset, they're no longer dynamic, and dynamic
2136 * lookup will no longer happen at that point. -- PFM.
2138 if (v->flags & VDYNAMIC)
2141 if (!(v->flags & VUNSET))
2142 return var_end(v->var_text);
2148 reinit_unicode_for_ash(void)
2150 /* Unicode support should be activated even if LANG is set
2151 * _during_ shell execution, not only if it was set when
2152 * shell was started. Therefore, re-check LANG every time:
2154 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2155 || ENABLE_UNICODE_USING_LOCALE
2157 const char *s = lookupvar("LC_ALL");
2158 if (!s) s = lookupvar("LC_CTYPE");
2159 if (!s) s = lookupvar("LANG");
2165 * Search the environment of a builtin command.
2168 bltinlookup(const char *name)
2172 for (sp = cmdenviron; sp; sp = sp->next) {
2173 if (varcmp(sp->text, name) == 0)
2174 return var_end(sp->text);
2176 return lookupvar(name);
2180 * Same as setvar except that the variable and value are passed in
2181 * the first argument as name=value. Since the first argument will
2182 * be actually stored in the table, it should not be a string that
2184 * Called with interrupts off.
2187 setvareq(char *s, int flags)
2189 struct var *vp, **vpp;
2192 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2193 vp = *findvar(vpp, s);
2195 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2198 if (flags & VNOSAVE)
2201 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2207 if (vp->var_func && !(flags & VNOFUNC))
2208 vp->var_func(var_end(s));
2210 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2211 free((char*)vp->var_text);
2213 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2215 /* variable s is not found */
2218 vp = ckzalloc(sizeof(*vp));
2220 /*vp->func = NULL; - ckzalloc did it */
2223 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2230 * Set the value of a variable. The flags argument is ored with the
2231 * flags of the variable. If val is NULL, the variable is unset.
2234 setvar(const char *name, const char *val, int flags)
2242 q = endofname(name);
2243 p = strchrnul(q, '=');
2245 if (!namelen || p != q)
2246 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2251 vallen = strlen(val);
2255 nameeq = ckmalloc(namelen + vallen + 2);
2256 p = memcpy(nameeq, name, namelen) + namelen;
2259 p = memcpy(p, val, vallen) + vallen;
2262 setvareq(nameeq, flags | VNOSAVE);
2266 static void FAST_FUNC
2267 setvar0(const char *name, const char *val)
2269 setvar(name, val, 0);
2272 #if ENABLE_ASH_GETOPTS
2274 * Safe version of setvar, returns 1 on success 0 on failure.
2277 setvarsafe(const char *name, const char *val, int flags)
2280 volatile int saveint;
2281 struct jmploc *volatile savehandler = exception_handler;
2282 struct jmploc jmploc;
2285 if (setjmp(jmploc.loc))
2288 exception_handler = &jmploc;
2289 setvar(name, val, flags);
2292 exception_handler = savehandler;
2293 RESTORE_INT(saveint);
2299 * Unset the specified variable.
2302 unsetvar(const char *s)
2308 vpp = findvar(hashvar(s), s);
2312 int flags = vp->flags;
2315 if (flags & VREADONLY)
2317 #if ENABLE_ASH_RANDOM_SUPPORT
2318 vp->flags &= ~VDYNAMIC;
2322 if ((flags & VSTRFIXED) == 0) {
2324 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2325 free((char*)vp->var_text);
2331 vp->flags &= ~VEXPORT;
2341 * Process a linked list of variable assignments.
2344 listsetvar(struct strlist *list_set_var, int flags)
2346 struct strlist *lp = list_set_var;
2352 setvareq(lp->text, flags);
2359 * Generate a list of variables satisfying the given conditions.
2362 listvars(int on, int off, char ***end)
2373 for (vp = *vpp; vp; vp = vp->next) {
2374 if ((vp->flags & mask) == on) {
2375 if (ep == stackstrend())
2376 ep = growstackstr();
2377 *ep++ = (char*)vp->var_text;
2380 } while (++vpp < vartab + VTABSIZE);
2381 if (ep == stackstrend())
2382 ep = growstackstr();
2386 return grabstackstr(ep);
2390 /* ============ Path search helper
2392 * The variable path (passed by reference) should be set to the start
2393 * of the path before the first call; path_advance will update
2394 * this value as it proceeds. Successive calls to path_advance will return
2395 * the possible path expansions in sequence. If an option (indicated by
2396 * a percent sign) appears in the path entry then the global variable
2397 * pathopt will be set to point to it; otherwise pathopt will be set to
2400 static const char *pathopt; /* set by path_advance */
2403 path_advance(const char **path, const char *name)
2413 for (p = start; *p && *p != ':' && *p != '%'; p++)
2415 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2416 while (stackblocksize() < len)
2420 memcpy(q, start, p - start);
2428 while (*p && *p != ':')
2435 return stalloc(len);
2439 /* ============ Prompt */
2441 static smallint doprompt; /* if set, prompt the user */
2442 static smallint needprompt; /* true if interactive and at start of line */
2444 #if ENABLE_FEATURE_EDITING
2445 static line_input_t *line_input_state;
2446 static const char *cmdedit_prompt;
2448 putprompt(const char *s)
2450 if (ENABLE_ASH_EXPAND_PRMT) {
2451 free((char*)cmdedit_prompt);
2452 cmdedit_prompt = ckstrdup(s);
2459 putprompt(const char *s)
2465 #if ENABLE_ASH_EXPAND_PRMT
2466 /* expandstr() needs parsing machinery, so it is far away ahead... */
2467 static const char *expandstr(const char *ps);
2469 #define expandstr(s) s
2473 setprompt_if(smallint do_set, int whichprompt)
2476 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2483 switch (whichprompt) {
2493 #if ENABLE_ASH_EXPAND_PRMT
2494 pushstackmark(&smark, stackblocksize());
2496 putprompt(expandstr(prompt));
2497 #if ENABLE_ASH_EXPAND_PRMT
2498 popstackmark(&smark);
2503 /* ============ The cd and pwd commands */
2505 #define CD_PHYSICAL 1
2515 while ((i = nextopt("LP")) != '\0') {
2517 flags ^= CD_PHYSICAL;
2526 * Update curdir (the name of the current directory) in response to a
2530 updatepwd(const char *dir)
2537 cdcomppath = sstrdup(dir);
2540 if (curdir == nullstr)
2542 new = stack_putstr(curdir, new);
2544 new = makestrspace(strlen(dir) + 2, new);
2545 lim = (char *)stackblock() + 1;
2549 if (new > lim && *lim == '/')
2554 if (dir[1] == '/' && dir[2] != '/') {
2560 p = strtok(cdcomppath, "/");
2564 if (p[1] == '.' && p[2] == '\0') {
2576 new = stack_putstr(p, new);
2579 p = strtok(NULL, "/");
2584 return stackblock();
2588 * Find out what the current directory is. If we already know the current
2589 * directory, this routine returns immediately.
2594 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2595 return dir ? dir : nullstr;
2599 setpwd(const char *val, int setold)
2603 oldcur = dir = curdir;
2606 setvar("OLDPWD", oldcur, VEXPORT);
2609 if (physdir != nullstr) {
2610 if (physdir != oldcur)
2614 if (oldcur == val || !val) {
2620 dir = ckstrdup(val);
2621 if (oldcur != dir && oldcur != nullstr) {
2626 setvar("PWD", dir, VEXPORT);
2629 static void hashcd(void);
2632 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2633 * know that the current directory has changed.
2636 docd(const char *dest, int flags)
2638 const char *dir = NULL;
2641 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2644 if (!(flags & CD_PHYSICAL)) {
2645 dir = updatepwd(dest);
2659 static int FAST_FUNC
2660 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2672 dest = bltinlookup("HOME");
2673 else if (LONE_DASH(dest)) {
2674 dest = bltinlookup("OLDPWD");
2696 path = bltinlookup("CDPATH");
2705 p = path_advance(&path, dest);
2706 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2710 if (!docd(p, flags))
2715 ash_msg_and_raise_error("can't cd to %s", dest);
2718 if (flags & CD_PRINT)
2719 out1fmt("%s\n", curdir);
2723 static int FAST_FUNC
2724 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2727 const char *dir = curdir;
2731 if (physdir == nullstr)
2735 out1fmt("%s\n", dir);
2740 /* ============ ... */
2743 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2745 /* Syntax classes */
2746 #define CWORD 0 /* character is nothing special */
2747 #define CNL 1 /* newline character */
2748 #define CBACK 2 /* a backslash character */
2749 #define CSQUOTE 3 /* single quote */
2750 #define CDQUOTE 4 /* double quote */
2751 #define CENDQUOTE 5 /* a terminating quote */
2752 #define CBQUOTE 6 /* backwards single quote */
2753 #define CVAR 7 /* a dollar sign */
2754 #define CENDVAR 8 /* a '}' character */
2755 #define CLP 9 /* a left paren in arithmetic */
2756 #define CRP 10 /* a right paren in arithmetic */
2757 #define CENDFILE 11 /* end of file */
2758 #define CCTL 12 /* like CWORD, except it must be escaped */
2759 #define CSPCL 13 /* these terminate a word */
2760 #define CIGN 14 /* character should be ignored */
2763 #if ENABLE_ASH_ALIAS
2767 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2769 #if ENABLE_SH_MATH_SUPPORT
2770 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2772 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2774 static const uint16_t S_I_T[] ALIGN2 = {
2775 #if ENABLE_ASH_ALIAS
2776 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2778 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2779 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2780 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2781 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2782 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2783 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2784 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2785 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2786 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2787 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2788 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2789 #if !USE_SIT_FUNCTION
2790 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2791 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2792 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2796 /* Constants below must match table above */
2798 #if ENABLE_ASH_ALIAS
2799 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2801 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2802 CNL_CNL_CNL_CNL , /* 2 */
2803 CWORD_CCTL_CCTL_CWORD , /* 3 */
2804 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2805 CVAR_CVAR_CWORD_CVAR , /* 5 */
2806 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2807 CSPCL_CWORD_CWORD_CLP , /* 7 */
2808 CSPCL_CWORD_CWORD_CRP , /* 8 */
2809 CBACK_CBACK_CCTL_CBACK , /* 9 */
2810 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2811 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2812 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2813 CWORD_CWORD_CWORD_CWORD , /* 13 */
2814 CCTL_CCTL_CCTL_CCTL , /* 14 */
2817 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2818 * caller must ensure proper cast on it if c is *char_ptr!
2820 /* Values for syntax param */
2821 #define BASESYNTAX 0 /* not in quotes */
2822 #define DQSYNTAX 1 /* in double quotes */
2823 #define SQSYNTAX 2 /* in single quotes */
2824 #define ARISYNTAX 3 /* in arithmetic */
2825 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2827 #if USE_SIT_FUNCTION
2830 SIT(int c, int syntax)
2832 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2833 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2835 * This causes '/' to be prepended with CTLESC in dquoted string,
2836 * making "./file"* treated incorrectly because we feed
2837 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2838 * The "homegrown" glob implementation is okay with that,
2839 * but glibc one isn't. With '/' always treated as CWORD,
2842 # if ENABLE_ASH_ALIAS
2843 static const uint8_t syntax_index_table[] ALIGN1 = {
2844 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2845 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2846 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2850 static const uint8_t syntax_index_table[] ALIGN1 = {
2851 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2852 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2853 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2862 # if ENABLE_ASH_ALIAS
2868 /* Cast is purely for paranoia here,
2869 * just in case someone passed signed char to us */
2870 if ((unsigned char)c >= CTL_FIRST
2871 && (unsigned char)c <= CTL_LAST
2875 s = strchrnul(spec_symbls, c);
2878 indx = syntax_index_table[s - spec_symbls];
2880 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2883 #else /* !USE_SIT_FUNCTION */
2885 static const uint8_t syntax_index_table[] ALIGN1 = {
2886 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2887 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2898 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2920 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2922 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2924 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2927 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2928 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2929 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2932 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2933 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2934 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2935 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2948 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2951 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2952 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2980 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2981 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2982 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2985 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3013 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3014 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3015 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3016 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3018 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3019 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3020 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3021 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3022 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3023 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3024 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3025 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3144 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3145 # if ENABLE_ASH_ALIAS
3146 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3150 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3152 #endif /* !USE_SIT_FUNCTION */
3155 /* ============ Alias handling */
3157 #if ENABLE_ASH_ALIAS
3159 #define ALIASINUSE 1
3170 static struct alias **atab; // [ATABSIZE];
3171 #define INIT_G_alias() do { \
3172 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3176 static struct alias **
3177 __lookupalias(const char *name)
3179 unsigned int hashval;
3186 ch = (unsigned char)*p;
3190 ch = (unsigned char)*++p;
3192 app = &atab[hashval % ATABSIZE];
3194 for (; *app; app = &(*app)->next) {
3195 if (strcmp(name, (*app)->name) == 0) {
3203 static struct alias *
3204 lookupalias(const char *name, int check)
3206 struct alias *ap = *__lookupalias(name);
3208 if (check && ap && (ap->flag & ALIASINUSE))
3213 static struct alias *
3214 freealias(struct alias *ap)
3218 if (ap->flag & ALIASINUSE) {
3219 ap->flag |= ALIASDEAD;
3231 setalias(const char *name, const char *val)
3233 struct alias *ap, **app;
3235 app = __lookupalias(name);
3239 if (!(ap->flag & ALIASINUSE)) {
3242 ap->val = ckstrdup(val);
3243 ap->flag &= ~ALIASDEAD;
3246 ap = ckzalloc(sizeof(struct alias));
3247 ap->name = ckstrdup(name);
3248 ap->val = ckstrdup(val);
3249 /*ap->flag = 0; - ckzalloc did it */
3250 /*ap->next = NULL;*/
3257 unalias(const char *name)
3261 app = __lookupalias(name);
3265 *app = freealias(*app);
3276 struct alias *ap, **app;
3280 for (i = 0; i < ATABSIZE; i++) {
3282 for (ap = *app; ap; ap = *app) {
3283 *app = freealias(*app);
3293 printalias(const struct alias *ap)
3295 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3299 * TODO - sort output
3301 static int FAST_FUNC
3302 aliascmd(int argc UNUSED_PARAM, char **argv)
3311 for (i = 0; i < ATABSIZE; i++) {
3312 for (ap = atab[i]; ap; ap = ap->next) {
3318 while ((n = *++argv) != NULL) {
3319 v = strchr(n+1, '=');
3320 if (v == NULL) { /* n+1: funny ksh stuff */
3321 ap = *__lookupalias(n);
3323 fprintf(stderr, "%s: %s not found\n", "alias", n);
3336 static int FAST_FUNC
3337 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3341 while ((i = nextopt("a")) != '\0') {
3347 for (i = 0; *argptr; argptr++) {
3348 if (unalias(*argptr)) {
3349 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3357 #endif /* ASH_ALIAS */
3360 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3363 #define FORK_NOJOB 2
3365 /* mode flags for showjob(s) */
3366 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3367 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3368 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3369 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3372 * A job structure contains information about a job. A job is either a
3373 * single process or a set of processes contained in a pipeline. In the
3374 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3378 pid_t ps_pid; /* process id */
3379 int ps_status; /* last process status from wait() */
3380 char *ps_cmd; /* text of command being run */
3384 struct procstat ps0; /* status of process */
3385 struct procstat *ps; /* status or processes when more than one */
3387 int stopstatus; /* status of a stopped job */
3390 nprocs: 16, /* number of processes */
3392 #define JOBRUNNING 0 /* at least one proc running */
3393 #define JOBSTOPPED 1 /* all procs are stopped */
3394 #define JOBDONE 2 /* all procs are completed */
3396 sigint: 1, /* job was killed by SIGINT */
3397 jobctl: 1, /* job running under job control */
3399 waited: 1, /* true if this entry has been waited for */
3400 used: 1, /* true if this entry is in used */
3401 changed: 1; /* true if status has changed */
3402 struct job *prev_job; /* previous job */
3405 static struct job *makejob(/*union node *,*/ int);
3406 static int forkshell(struct job *, union node *, int);
3407 static int waitforjob(struct job *);
3410 enum { doing_jobctl = 0 };
3411 #define setjobctl(on) do {} while (0)
3413 static smallint doing_jobctl; //references:8
3414 static void setjobctl(int);
3421 ignoresig(int signo)
3423 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3424 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3425 /* No, need to do it */
3426 signal(signo, SIG_IGN);
3428 sigmode[signo - 1] = S_HARD_IGN;
3432 * Only one usage site - in setsignal()
3435 signal_handler(int signo)
3437 gotsig[signo - 1] = 1;
3439 if (signo == SIGINT && !trap[SIGINT]) {
3440 if (!suppress_int) {
3442 raise_interrupt(); /* does not return */
3446 pending_sig = signo;
3451 * Set the signal handler for the specified signal. The routine figures
3452 * out what it should be set to.
3455 setsignal(int signo)
3458 char cur_act, new_act;
3459 struct sigaction act;
3463 if (t != NULL) { /* trap for this sig is set */
3465 if (t[0] == '\0') /* trap is "": ignore this sig */
3469 if (rootshell && new_act == S_DFL) {
3472 if (iflag || minusc || sflag == 0)
3481 * "In all cases, bash ignores SIGQUIT. Non-builtin
3482 * commands run by bash have signal handlers
3483 * set to the values inherited by the shell
3484 * from its parent". */
3500 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3501 //whereas we have to restore it to what shell got on entry
3502 //from the parent. See comment above
3504 t = &sigmode[signo - 1];
3507 /* current setting is not yet known */
3508 if (sigaction(signo, NULL, &act)) {
3509 /* pretend it worked; maybe we should give a warning,
3510 * but other shells don't. We don't alter sigmode,
3511 * so we retry every time.
3512 * btw, in Linux it never fails. --vda */
3515 if (act.sa_handler == SIG_IGN) {
3516 cur_act = S_HARD_IGN;
3518 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3520 cur_act = S_IGN; /* don't hard ignore these */
3524 if (cur_act == S_HARD_IGN || cur_act == new_act)
3527 act.sa_handler = SIG_DFL;
3530 act.sa_handler = signal_handler;
3533 act.sa_handler = SIG_IGN;
3537 /* flags and mask matter only if !DFL and !IGN, but we do it
3538 * for all cases for more deterministic behavior:
3541 sigfillset(&act.sa_mask);
3543 sigaction_set(signo, &act);
3548 /* mode flags for set_curjob */
3549 #define CUR_DELETE 2
3550 #define CUR_RUNNING 1
3551 #define CUR_STOPPED 0
3553 /* mode flags for dowait */
3554 #define DOWAIT_NONBLOCK WNOHANG
3555 #define DOWAIT_BLOCK 0
3558 /* pgrp of shell on invocation */
3559 static int initialpgrp; //references:2
3560 static int ttyfd = -1; //5
3563 static struct job *jobtab; //5
3565 static unsigned njobs; //4
3567 static struct job *curjob; //lots
3568 /* number of presumed living untracked jobs */
3569 static int jobless; //4
3572 set_curjob(struct job *jp, unsigned mode)
3575 struct job **jpp, **curp;
3577 /* first remove from list */
3578 jpp = curp = &curjob;
3583 jpp = &jp1->prev_job;
3585 *jpp = jp1->prev_job;
3587 /* Then re-insert in correct position */
3595 /* job being deleted */
3598 /* newly created job or backgrounded job,
3599 * put after all stopped jobs.
3604 if (!jp1 || jp1->state != JOBSTOPPED)
3607 jpp = &jp1->prev_job;
3613 /* newly stopped job - becomes curjob */
3614 jp->prev_job = *jpp;
3622 jobno(const struct job *jp)
3624 return jp - jobtab + 1;
3629 * Convert a job name to a job structure.
3632 #define getjob(name, getctl) getjob(name)
3635 getjob(const char *name, int getctl)
3639 const char *err_msg = "%s: no such job";
3643 char *(*match)(const char *, const char *);
3658 if (c == '+' || c == '%') {
3660 err_msg = "No current job";
3666 err_msg = "No previous job";
3676 if (num > 0 && num <= njobs) {
3677 jp = jobtab + num - 1;
3692 if (match(jp->ps[0].ps_cmd, p)) {
3696 err_msg = "%s: ambiguous";
3706 err_msg = "job %s not created under job control";
3707 if (getctl && jp->jobctl == 0)
3712 ash_msg_and_raise_error(err_msg, name);
3716 * Mark a job structure as unused.
3719 freejob(struct job *jp)
3721 struct procstat *ps;
3725 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3726 if (ps->ps_cmd != nullstr)
3729 if (jp->ps != &jp->ps0)
3732 set_curjob(jp, CUR_DELETE);
3738 xtcsetpgrp(int fd, pid_t pgrp)
3740 if (tcsetpgrp(fd, pgrp))
3741 ash_msg_and_raise_error("can't set tty process group (%m)");
3745 * Turn job control on and off.
3747 * Note: This code assumes that the third arg to ioctl is a character
3748 * pointer, which is true on Berkeley systems but not System V. Since
3749 * System V doesn't have job control yet, this isn't a problem now.
3751 * Called with interrupts off.
3759 if (on == doing_jobctl || rootshell == 0)
3763 ofd = fd = open(_PATH_TTY, O_RDWR);
3765 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3766 * That sometimes helps to acquire controlling tty.
3767 * Obviously, a workaround for bugs when someone
3768 * failed to provide a controlling tty to bash! :) */
3774 fd = fcntl(fd, F_DUPFD, 10);
3779 /* fd is a tty at this point */
3780 close_on_exec_on(fd);
3781 while (1) { /* while we are in the background */
3782 pgrp = tcgetpgrp(fd);
3785 ash_msg("can't access tty; job control turned off");
3789 if (pgrp == getpgrp())
3800 xtcsetpgrp(fd, pgrp);
3802 /* turning job control off */
3805 /* was xtcsetpgrp, but this can make exiting ash
3806 * loop forever if pty is already deleted */
3807 tcsetpgrp(fd, pgrp);
3821 static int FAST_FUNC
3822 killcmd(int argc, char **argv)
3824 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3827 if (argv[i][0] == '%') {
3829 * "kill %N" - job kill
3830 * Converting to pgrp / pid kill
3836 jp = getjob(argv[i], 0);
3838 * In jobs started under job control, we signal
3839 * entire process group by kill -PGRP_ID.
3840 * This happens, f.e., in interactive shell.
3842 * Otherwise, we signal each child via
3843 * kill PID1 PID2 PID3.
3845 * sh -c 'sleep 1|sleep 1 & kill %1'
3846 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3847 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3849 n = jp->nprocs; /* can't be 0 (I hope) */
3852 dst = alloca(n * sizeof(int)*4);
3854 for (j = 0; j < n; j++) {
3855 struct procstat *ps = &jp->ps[j];
3856 /* Skip non-running and not-stopped members
3857 * (i.e. dead members) of the job
3859 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3862 * kill_main has matching code to expect
3863 * leading space. Needed to not confuse
3864 * negative pids with "kill -SIGNAL_NO" syntax
3866 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3870 } while (argv[++i]);
3872 return kill_main(argc, argv);
3876 showpipe(struct job *jp /*, FILE *out*/)
3878 struct procstat *ps;
3879 struct procstat *psend;
3881 psend = jp->ps + jp->nprocs;
3882 for (ps = jp->ps + 1; ps < psend; ps++)
3883 printf(" | %s", ps->ps_cmd);
3884 newline_and_flush(stdout);
3885 flush_stdout_stderr();
3890 restartjob(struct job *jp, int mode)
3892 struct procstat *ps;
3898 if (jp->state == JOBDONE)
3900 jp->state = JOBRUNNING;
3901 pgid = jp->ps[0].ps_pid;
3902 if (mode == FORK_FG)
3903 xtcsetpgrp(ttyfd, pgid);
3904 killpg(pgid, SIGCONT);
3908 if (WIFSTOPPED(ps->ps_status)) {
3914 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3919 static int FAST_FUNC
3920 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3926 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3930 jp = getjob(*argv, 1);
3931 if (mode == FORK_BG) {
3932 set_curjob(jp, CUR_RUNNING);
3933 printf("[%d] ", jobno(jp));
3935 out1str(jp->ps[0].ps_cmd);
3936 showpipe(jp /*, stdout*/);
3937 retval = restartjob(jp, mode);
3938 } while (*argv && *++argv);
3944 sprint_status48(char *s, int status, int sigonly)
3950 if (!WIFEXITED(status)) {
3951 if (JOBS && WIFSTOPPED(status))
3952 st = WSTOPSIG(status);
3954 st = WTERMSIG(status);
3956 if (st == SIGINT || st == SIGPIPE)
3958 if (JOBS && WIFSTOPPED(status))
3962 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3963 col = fmtstr(s, 32, strsignal(st));
3964 if (WCOREDUMP(status)) {
3965 strcpy(s + col, " (core dumped)");
3966 col += sizeof(" (core dumped)")-1;
3968 } else if (!sigonly) {
3969 st = WEXITSTATUS(status);
3970 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3977 dowait(int wait_flags, struct job *job)
3982 struct job *thisjob;
3984 TRACE(("dowait(0x%x) called\n", wait_flags));
3986 /* Do a wait system call. If job control is compiled in, we accept
3987 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3988 * NB: _not_ safe_waitpid, we need to detect EINTR */
3990 wait_flags |= WUNTRACED;
3991 pid = waitpid(-1, &status, wait_flags);
3992 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3993 pid, status, errno, strerror(errno)));
3999 for (jp = curjob; jp; jp = jp->prev_job) {
4001 struct procstat *ps;
4002 struct procstat *psend;
4003 if (jp->state == JOBDONE)
4007 psend = ps + jp->nprocs;
4009 if (ps->ps_pid == pid) {
4010 TRACE(("Job %d: changing status of proc %d "
4011 "from 0x%x to 0x%x\n",
4012 jobno(jp), pid, ps->ps_status, status));
4013 ps->ps_status = status;
4016 if (ps->ps_status == -1)
4017 jobstate = JOBRUNNING;
4019 if (jobstate == JOBRUNNING)
4021 if (WIFSTOPPED(ps->ps_status)) {
4022 jp->stopstatus = ps->ps_status;
4023 jobstate = JOBSTOPPED;
4026 } while (++ps < psend);
4030 /* Found the job where one of its processes changed its state.
4031 * Is there at least one live and running process in this job? */
4032 if (jobstate != JOBRUNNING) {
4033 /* No. All live processes in the job are stopped
4034 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4036 thisjob->changed = 1;
4037 if (thisjob->state != jobstate) {
4038 TRACE(("Job %d: changing state from %d to %d\n",
4039 jobno(thisjob), thisjob->state, jobstate));
4040 thisjob->state = jobstate;
4042 if (jobstate == JOBSTOPPED)
4043 set_curjob(thisjob, CUR_STOPPED);
4049 /* The process wasn't found in job list */
4050 if (JOBS && !WIFSTOPPED(status))
4055 if (thisjob && thisjob == job) {
4059 len = sprint_status48(s, status, 1);
4070 blocking_wait_with_raise_on_sig(void)
4072 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4073 if (pid <= 0 && pending_sig)
4074 raise_exception(EXSIG);
4080 showjob(struct job *jp, int mode)
4082 struct procstat *ps;
4083 struct procstat *psend;
4086 char s[16 + 16 + 48];
4087 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4091 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4092 /* just output process (group) id of pipeline */
4093 fprintf(out, "%d\n", ps->ps_pid);
4097 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4102 else if (curjob && jp == curjob->prev_job)
4105 if (mode & SHOW_PIDS)
4106 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4108 psend = ps + jp->nprocs;
4110 if (jp->state == JOBRUNNING) {
4111 strcpy(s + col, "Running");
4112 col += sizeof("Running") - 1;
4114 int status = psend[-1].ps_status;
4115 if (jp->state == JOBSTOPPED)
4116 status = jp->stopstatus;
4117 col += sprint_status48(s + col, status, 0);
4119 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4121 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4122 * or prints several "PID | <cmdN>" lines,
4123 * depending on SHOW_PIDS bit.
4124 * We do not print status of individual processes
4125 * between PID and <cmdN>. bash does it, but not very well:
4126 * first line shows overall job status, not process status,
4127 * making it impossible to know 1st process status.
4131 /* for each process */
4134 if (mode & SHOW_PIDS)
4135 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4137 fprintf(out, "%s%*c%s%s",
4139 33 - col >= 0 ? 33 - col : 0, ' ',
4140 ps == jp->ps ? "" : "| ",
4143 } while (++ps != psend);
4144 newline_and_flush(out);
4148 if (jp->state == JOBDONE) {
4149 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4155 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4156 * statuses have changed since the last call to showjobs.
4163 TRACE(("showjobs(0x%x) called\n", mode));
4165 /* Handle all finished jobs */
4166 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4169 for (jp = curjob; jp; jp = jp->prev_job) {
4170 if (!(mode & SHOW_CHANGED) || jp->changed) {
4176 static int FAST_FUNC
4177 jobscmd(int argc UNUSED_PARAM, char **argv)
4182 while ((m = nextopt("lp")) != '\0') {
4186 mode |= SHOW_ONLY_PGID;
4192 showjob(getjob(*argv, 0), mode);
4202 /* Called only on finished or stopped jobs (no members are running) */
4204 getstatus(struct job *job)
4208 struct procstat *ps;
4210 /* Fetch last member's status */
4211 ps = job->ps + job->nprocs - 1;
4212 status = ps->ps_status;
4214 /* "set -o pipefail" mode: use last _nonzero_ status */
4215 while (status == 0 && --ps >= job->ps)
4216 status = ps->ps_status;
4219 retval = WEXITSTATUS(status);
4220 if (!WIFEXITED(status)) {
4222 retval = WSTOPSIG(status);
4223 if (!WIFSTOPPED(status))
4226 /* XXX: limits number of signals */
4227 retval = WTERMSIG(status);
4229 if (retval == SIGINT)
4235 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4236 jobno(job), job->nprocs, status, retval));
4240 static int FAST_FUNC
4241 waitcmd(int argc UNUSED_PARAM, char **argv)
4248 raise_exception(EXSIG);
4255 /* wait for all jobs */
4259 if (!jp) /* no running procs */
4261 if (jp->state == JOBRUNNING)
4266 blocking_wait_with_raise_on_sig();
4268 * "When bash is waiting for an asynchronous command via
4269 * the wait builtin, the reception of a signal for which a trap
4270 * has been set will cause the wait builtin to return immediately
4271 * with an exit status greater than 128, immediately after which
4272 * the trap is executed."
4274 * blocking_wait_with_raise_on_sig raises signal handlers
4275 * if it gets no pid (pid < 0). However,
4276 * if child sends us a signal *and immediately exits*,
4277 * blocking_wait_with_raise_on_sig gets pid > 0
4278 * and does not handle pending_sig. Check this case: */
4280 raise_exception(EXSIG);
4286 if (**argv != '%') {
4287 pid_t pid = number(*argv);
4292 if (job->ps[job->nprocs - 1].ps_pid == pid)
4294 job = job->prev_job;
4297 job = getjob(*argv, 0);
4299 /* loop until process terminated or stopped */
4300 while (job->state == JOBRUNNING)
4301 blocking_wait_with_raise_on_sig();
4303 retval = getstatus(job);
4316 struct job *jp, *jq;
4318 len = njobs * sizeof(*jp);
4320 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4322 offset = (char *)jp - (char *)jq;
4324 /* Relocate pointers */
4327 jq = (struct job *)((char *)jq + l);
4331 #define joff(p) ((struct job *)((char *)(p) + l))
4332 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4333 if (joff(jp)->ps == &jq->ps0)
4334 jmove(joff(jp)->ps);
4335 if (joff(jp)->prev_job)
4336 jmove(joff(jp)->prev_job);
4346 jp = (struct job *)((char *)jp + len);
4350 } while (--jq >= jp);
4355 * Return a new job structure.
4356 * Called with interrupts off.
4359 makejob(/*union node *node,*/ int nprocs)
4364 for (i = njobs, jp = jobtab; ; jp++) {
4371 if (jp->state != JOBDONE || !jp->waited)
4380 memset(jp, 0, sizeof(*jp));
4382 /* jp->jobctl is a bitfield.
4383 * "jp->jobctl |= jobctl" likely to give awful code */
4387 jp->prev_job = curjob;
4392 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4394 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4401 * Return a string identifying a command (to be printed by the
4404 static char *cmdnextc;
4407 cmdputs(const char *s)
4409 static const char vstype[VSTYPE + 1][3] = {
4410 "", "}", "-", "+", "?", "=",
4411 "%", "%%", "#", "##"
4412 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4415 const char *p, *str;
4419 unsigned char subtype = 0;
4423 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4425 while ((c = *p++) != '\0') {
4433 if ((subtype & VSTYPE) == VSLENGTH)
4439 str = "\"}" + !(quoted & 1);
4446 #if ENABLE_SH_MATH_SUPPORT
4461 if ((subtype & VSTYPE) != VSNORMAL)
4463 str = vstype[subtype & VSTYPE];
4464 if (subtype & VSNUL)
4473 /* These can only happen inside quotes */
4486 while ((c = *str++) != '\0') {
4489 } /* while *p++ not NUL */
4492 USTPUTC('"', nextc);
4498 /* cmdtxt() and cmdlist() call each other */
4499 static void cmdtxt(union node *n);
4502 cmdlist(union node *np, int sep)
4504 for (; np; np = np->narg.next) {
4508 if (sep && np->narg.next)
4514 cmdtxt(union node *n)
4517 struct nodelist *lp;
4528 lp = n->npipe.cmdlist;
4546 cmdtxt(n->nbinary.ch1);
4562 cmdtxt(n->nif.test);
4564 if (n->nif.elsepart) {
4565 cmdtxt(n->nif.ifpart);
4567 n = n->nif.elsepart;
4585 cmdtxt(n->nbinary.ch1);
4595 cmdputs(n->nfor.var);
4597 cmdlist(n->nfor.args, 1);
4602 cmdputs(n->narg.text);
4606 cmdlist(n->ncmd.args, 1);
4607 cmdlist(n->ncmd.redirect, 0);
4620 cmdputs(n->ncase.expr->narg.text);
4622 for (np = n->ncase.cases; np; np = np->nclist.next) {
4623 cmdtxt(np->nclist.pattern);
4625 cmdtxt(np->nclist.body);
4639 #if ENABLE_ASH_BASH_COMPAT
4654 cmdputs(utoa(n->nfile.fd));
4656 if (n->type == NTOFD || n->type == NFROMFD) {
4657 cmdputs(utoa(n->ndup.dupfd));
4666 commandtext(union node *n)
4670 STARTSTACKSTR(cmdnextc);
4672 name = stackblock();
4673 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4674 name, cmdnextc, cmdnextc));
4675 return ckstrdup(name);
4680 * Fork off a subshell. If we are doing job control, give the subshell its
4681 * own process group. Jp is a job structure that the job is to be added to.
4682 * N is the command that will be evaluated by the child. Both jp and n may
4683 * be NULL. The mode parameter can be one of the following:
4684 * FORK_FG - Fork off a foreground process.
4685 * FORK_BG - Fork off a background process.
4686 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4687 * process group even if job control is on.
4689 * When job control is turned off, background processes have their standard
4690 * input redirected to /dev/null (except for the second and later processes
4693 * Called with interrupts off.
4696 * Clear traps on a fork.
4703 for (tp = trap; tp < &trap[NSIG]; tp++) {
4704 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4706 if (trap_ptr == trap)
4708 /* else: it "belongs" to trap_ptr vector, don't free */
4710 if ((tp - trap) != 0)
4711 setsignal(tp - trap);
4718 /* Lives far away from here, needed for forkchild */
4719 static void closescript(void);
4721 /* Called after fork(), in child */
4722 static NOINLINE void
4723 forkchild(struct job *jp, union node *n, int mode)
4727 TRACE(("Child shell %d\n", getpid()));
4731 /* man bash: "Non-builtin commands run by bash have signal handlers
4732 * set to the values inherited by the shell from its parent".
4733 * Do we do it correctly? */
4737 if (mode == FORK_NOJOB /* is it `xxx` ? */
4738 && n && n->type == NCMD /* is it single cmd? */
4739 /* && n->ncmd.args->type == NARG - always true? */
4740 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4741 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4742 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4744 TRACE(("Trap hack\n"));
4745 /* Awful hack for `trap` or $(trap).
4747 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4748 * contains an example where "trap" is executed in a subshell:
4750 * save_traps=$(trap)
4752 * eval "$save_traps"
4754 * Standard does not say that "trap" in subshell shall print
4755 * parent shell's traps. It only says that its output
4756 * must have suitable form, but then, in the above example
4757 * (which is not supposed to be normative), it implies that.
4759 * bash (and probably other shell) does implement it
4760 * (traps are reset to defaults, but "trap" still shows them),
4761 * but as a result, "trap" logic is hopelessly messed up:
4764 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4765 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4766 * # true | trap <--- trap is in subshell - no output (ditto)
4767 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4768 * trap -- 'echo Ho' SIGWINCH
4769 * # echo `(trap)` <--- in subshell in subshell - output
4770 * trap -- 'echo Ho' SIGWINCH
4771 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4772 * trap -- 'echo Ho' SIGWINCH
4774 * The rules when to forget and when to not forget traps
4775 * get really complex and nonsensical.
4777 * Our solution: ONLY bare $(trap) or `trap` is special.
4779 /* Save trap handler strings for trap builtin to print */
4780 trap_ptr = xmemdup(trap, sizeof(trap));
4781 /* Fall through into clearing traps */
4785 /* do job control only in root shell */
4787 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4790 if (jp->nprocs == 0)
4793 pgrp = jp->ps[0].ps_pid;
4794 /* this can fail because we are doing it in the parent also */
4796 if (mode == FORK_FG)
4797 xtcsetpgrp(ttyfd, pgrp);
4802 if (mode == FORK_BG) {
4803 /* man bash: "When job control is not in effect,
4804 * asynchronous commands ignore SIGINT and SIGQUIT" */
4807 if (jp->nprocs == 0) {
4809 if (open(bb_dev_null, O_RDONLY) != 0)
4810 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4814 if (iflag) { /* why if iflag only? */
4819 * "In all cases, bash ignores SIGQUIT. Non-builtin
4820 * commands run by bash have signal handlers
4821 * set to the values inherited by the shell
4823 * Take care of the second rule: */
4827 if (n && n->type == NCMD
4828 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4830 TRACE(("Job hack\n"));
4831 /* "jobs": we do not want to clear job list for it,
4832 * instead we remove only _its_ own_ job from job list.
4833 * This makes "jobs .... | cat" more useful.
4839 for (jp = curjob; jp; jp = jp->prev_job)
4844 /* Called after fork(), in parent */
4846 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4849 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4851 TRACE(("In parent shell: child = %d\n", pid));
4853 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4859 if (mode != FORK_NOJOB && jp->jobctl) {
4862 if (jp->nprocs == 0)
4865 pgrp = jp->ps[0].ps_pid;
4866 /* This can fail because we are doing it in the child also */
4870 if (mode == FORK_BG) {
4871 backgndpid = pid; /* set $! */
4872 set_curjob(jp, CUR_RUNNING);
4875 struct procstat *ps = &jp->ps[jp->nprocs++];
4878 ps->ps_cmd = nullstr;
4880 if (doing_jobctl && n)
4881 ps->ps_cmd = commandtext(n);
4887 forkshell(struct job *jp, union node *n, int mode)
4891 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4894 TRACE(("Fork failed, errno=%d", errno));
4897 ash_msg_and_raise_error("can't fork");
4900 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4901 forkchild(jp, n, mode);
4903 forkparent(jp, n, mode, pid);
4909 * Wait for job to finish.
4911 * Under job control we have the problem that while a child process
4912 * is running interrupts generated by the user are sent to the child
4913 * but not to the shell. This means that an infinite loop started by
4914 * an interactive user may be hard to kill. With job control turned off,
4915 * an interactive user may place an interactive program inside a loop.
4916 * If the interactive program catches interrupts, the user doesn't want
4917 * these interrupts to also abort the loop. The approach we take here
4918 * is to have the shell ignore interrupt signals while waiting for a
4919 * foreground process to terminate, and then send itself an interrupt
4920 * signal if the child process was terminated by an interrupt signal.
4921 * Unfortunately, some programs want to do a bit of cleanup and then
4922 * exit on interrupt; unless these processes terminate themselves by
4923 * sending a signal to themselves (instead of calling exit) they will
4924 * confuse this approach.
4926 * Called with interrupts off.
4929 waitforjob(struct job *jp)
4933 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4936 while (jp->state == JOBRUNNING) {
4937 /* In non-interactive shells, we _can_ get
4938 * a keyboard signal here and be EINTRed,
4939 * but we just loop back, waiting for command to complete.
4942 * "If bash is waiting for a command to complete and receives
4943 * a signal for which a trap has been set, the trap
4944 * will not be executed until the command completes."
4946 * Reality is that even if trap is not set, bash
4947 * will not act on the signal until command completes.
4948 * Try this. sleep5intoff.c:
4949 * #include <signal.h>
4950 * #include <unistd.h>
4953 * sigemptyset(&set);
4954 * sigaddset(&set, SIGINT);
4955 * sigaddset(&set, SIGQUIT);
4956 * sigprocmask(SIG_BLOCK, &set, NULL);
4960 * $ bash -c './sleep5intoff; echo hi'
4961 * ^C^C^C^C <--- pressing ^C once a second
4963 * $ bash -c './sleep5intoff; echo hi'
4964 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4967 dowait(DOWAIT_BLOCK, jp);
4974 xtcsetpgrp(ttyfd, rootpid);
4976 * This is truly gross.
4977 * If we're doing job control, then we did a TIOCSPGRP which
4978 * caused us (the shell) to no longer be in the controlling
4979 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4980 * intuit from the subprocess exit status whether a SIGINT
4981 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4983 if (jp->sigint) /* TODO: do the same with all signals */
4984 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4986 if (jp->state == JOBDONE)
4993 * return 1 if there are stopped jobs, otherwise 0
5005 if (jp && jp->state == JOBSTOPPED) {
5006 out2str("You have stopped jobs.\n");
5015 /* ============ redir.c
5017 * Code for dealing with input/output redirection.
5022 #define EMPTY -2 /* marks an unused slot in redirtab */
5023 #define CLOSED -3 /* marks a slot of previously-closed fd */
5026 * Open a file in noclobber mode.
5027 * The code was copied from bash.
5030 noclobberopen(const char *fname)
5033 struct stat finfo, finfo2;
5036 * If the file exists and is a regular file, return an error
5039 r = stat(fname, &finfo);
5040 if (r == 0 && S_ISREG(finfo.st_mode)) {
5046 * If the file was not present (r != 0), make sure we open it
5047 * exclusively so that if it is created before we open it, our open
5048 * will fail. Make sure that we do not truncate an existing file.
5049 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5050 * file was not a regular file, we leave O_EXCL off.
5053 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5054 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5056 /* If the open failed, return the file descriptor right away. */
5061 * OK, the open succeeded, but the file may have been changed from a
5062 * non-regular file to a regular file between the stat and the open.
5063 * We are assuming that the O_EXCL open handles the case where FILENAME
5064 * did not exist and is symlinked to an existing file between the stat
5069 * If we can open it and fstat the file descriptor, and neither check
5070 * revealed that it was a regular file, and the file has not been
5071 * replaced, return the file descriptor.
5073 if (fstat(fd, &finfo2) == 0
5074 && !S_ISREG(finfo2.st_mode)
5075 && finfo.st_dev == finfo2.st_dev
5076 && finfo.st_ino == finfo2.st_ino
5081 /* The file has been replaced. badness. */
5088 * Handle here documents. Normally we fork off a process to write the
5089 * data to a pipe. If the document is short, we can stuff the data in
5090 * the pipe without forking.
5092 /* openhere needs this forward reference */
5093 static void expandhere(union node *arg, int fd);
5095 openhere(union node *redir)
5101 ash_msg_and_raise_error("pipe call failed");
5102 if (redir->type == NHERE) {
5103 len = strlen(redir->nhere.doc->narg.text);
5104 if (len <= PIPE_BUF) {
5105 full_write(pip[1], redir->nhere.doc->narg.text, len);
5109 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5112 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5113 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5114 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5115 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5116 signal(SIGPIPE, SIG_DFL);
5117 if (redir->type == NHERE)
5118 full_write(pip[1], redir->nhere.doc->narg.text, len);
5120 expandhere(redir->nhere.doc, pip[1]);
5121 _exit(EXIT_SUCCESS);
5129 openredirect(union node *redir)
5134 switch (redir->nfile.type) {
5135 /* Can't happen, our single caller does this itself */
5141 return openhere(redir);
5144 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5145 * allocated space. Do it only when we know it is safe.
5147 fname = redir->nfile.expfname;
5149 switch (redir->nfile.type) {
5155 f = open(fname, O_RDONLY);
5160 f = open(fname, O_RDWR|O_CREAT, 0666);
5165 #if ENABLE_ASH_BASH_COMPAT
5168 /* Take care of noclobber mode. */
5170 f = noclobberopen(fname);
5177 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5182 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5190 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5192 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5196 * Copy a file descriptor to be >= to. Returns -1
5197 * if the source file descriptor is closed, EMPTY if there are no unused
5198 * file descriptors left.
5200 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5201 * old code was doing close(to) prior to copyfd() to achieve the same */
5203 COPYFD_EXACT = (int)~(INT_MAX),
5204 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5207 copyfd(int from, int to)
5211 if (to & COPYFD_EXACT) {
5212 to &= ~COPYFD_EXACT;
5214 newfd = dup2(from, to);
5216 newfd = fcntl(from, F_DUPFD, to);
5219 if (errno == EMFILE)
5221 /* Happens when source fd is not open: try "echo >&99" */
5222 ash_msg_and_raise_error("%d: %m", from);
5227 /* Struct def and variable are moved down to the first usage site */
5232 struct redirtab *next;
5235 struct two_fd_t two_fd[];
5237 #define redirlist (G_var.redirlist)
5240 need_to_remember(struct redirtab *rp, int fd)
5244 if (!rp) /* remembering was not requested */
5247 for (i = 0; i < rp->pair_count; i++) {
5248 if (rp->two_fd[i].orig == fd) {
5249 /* already remembered */
5256 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5258 is_hidden_fd(struct redirtab *rp, int fd)
5261 struct parsefile *pf;
5265 /* Check open scripts' fds */
5268 /* We skip pf_fd == 0 case because of the following case:
5269 * $ ash # running ash interactively
5271 * and in script.sh: "exec 9>&0".
5272 * Even though top-level pf_fd _is_ 0,
5273 * it's still ok to use it: "read" builtin uses it,
5274 * why should we cripple "exec" builtin?
5276 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5284 /* Check saved fds of redirects */
5285 fd |= COPYFD_RESTORE;
5286 for (i = 0; i < rp->pair_count; i++) {
5287 if (rp->two_fd[i].copy == fd) {
5295 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5296 * old file descriptors are stashed away so that the redirection can be
5297 * undone by calling popredir.
5299 /* flags passed to redirect */
5300 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5301 #define REDIR_SAVEFD2 03 /* set preverrout */
5303 redirect(union node *redir, int flags)
5305 struct redirtab *sv;
5310 int copied_fd2 = -1;
5320 if (flags & REDIR_PUSH) {
5321 union node *tmp = redir;
5324 #if ENABLE_ASH_BASH_COMPAT
5325 if (tmp->nfile.type == NTO2)
5328 tmp = tmp->nfile.next;
5330 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5331 sv->next = redirlist;
5332 sv->pair_count = sv_pos;
5334 sv->nullredirs = g_nullredirs - 1;
5336 while (sv_pos > 0) {
5338 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5344 fd = redir->nfile.fd;
5345 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5346 right_fd = redir->ndup.dupfd;
5347 //bb_error_msg("doing %d > %d", fd, right_fd);
5348 /* redirect from/to same file descriptor? */
5351 /* "echo >&10" and 10 is a fd opened to a sh script? */
5352 if (is_hidden_fd(sv, right_fd)) {
5353 errno = EBADF; /* as if it is closed */
5354 ash_msg_and_raise_error("%d: %m", right_fd);
5358 newfd = openredirect(redir); /* always >= 0 */
5360 /* Descriptor wasn't open before redirect.
5361 * Mark it for close in the future */
5362 if (need_to_remember(sv, fd)) {
5363 goto remember_to_close;
5368 #if ENABLE_ASH_BASH_COMPAT
5371 if (need_to_remember(sv, fd)) {
5372 /* Copy old descriptor */
5373 /* Careful to not accidentally "save"
5374 * to the same fd as right side fd in N>&M */
5375 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5376 i = fcntl(fd, F_DUPFD, minfd);
5377 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5378 * are closed in popredir() in the child, preventing them from leaking
5379 * into child. (popredir() also cleans up the mess in case of failures)
5384 /* Strange error (e.g. "too many files" EMFILE?) */
5388 ash_msg_and_raise_error("%d: %m", fd);
5391 /* EBADF: it is not open - good, remember to close it */
5394 } else { /* fd is open, save its copy */
5395 /* "exec fd>&-" should not close fds
5396 * which point to script file(s).
5397 * Force them to be restored afterwards */
5398 if (is_hidden_fd(sv, fd))
5399 i |= COPYFD_RESTORE;
5403 sv->two_fd[sv_pos].orig = fd;
5404 sv->two_fd[sv_pos].copy = i;
5408 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5409 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5410 /* Don't want to trigger debugging */
5414 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5416 } else if (fd != newfd) { /* move newfd to fd */
5417 copyfd(newfd, fd | COPYFD_EXACT);
5418 #if ENABLE_ASH_BASH_COMPAT
5419 if (!(redir->nfile.type == NTO2 && fd == 2))
5423 #if ENABLE_ASH_BASH_COMPAT
5424 if (redir->nfile.type == NTO2 && fd == 1) {
5425 /* We already redirected it to fd 1, now copy it to 2 */
5431 } while ((redir = redir->nfile.next) != NULL);
5434 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5435 preverrout_fd = copied_fd2;
5439 * Undo the effects of the last redirection.
5442 popredir(int drop, int restore)
5444 struct redirtab *rp;
5447 if (--g_nullredirs >= 0 || redirlist == NULL)
5451 for (i = 0; i < rp->pair_count; i++) {
5452 int fd = rp->two_fd[i].orig;
5453 int copy = rp->two_fd[i].copy;
5454 if (copy == CLOSED) {
5459 if (copy != EMPTY) {
5460 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5461 copy &= ~COPYFD_RESTORE;
5463 copyfd(copy, fd | COPYFD_EXACT);
5465 close(copy & ~COPYFD_RESTORE);
5468 redirlist = rp->next;
5469 g_nullredirs = rp->nullredirs;
5475 * Undo all redirections. Called on error or interrupt.
5479 * Discard all saved file descriptors.
5482 clearredir(int drop)
5488 popredir(drop, /*restore:*/ 0);
5493 redirectsafe(union node *redir, int flags)
5496 volatile int saveint;
5497 struct jmploc *volatile savehandler = exception_handler;
5498 struct jmploc jmploc;
5501 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5502 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5504 exception_handler = &jmploc;
5505 redirect(redir, flags);
5507 exception_handler = savehandler;
5508 if (err && exception_type != EXERROR)
5509 longjmp(exception_handler->loc, 1);
5510 RESTORE_INT(saveint);
5515 /* ============ Routines to expand arguments to commands
5517 * We have to deal with backquotes, shell variables, and file metacharacters.
5520 #if ENABLE_SH_MATH_SUPPORT
5522 ash_arith(const char *s)
5524 arith_state_t math_state;
5527 math_state.lookupvar = lookupvar;
5528 math_state.setvar = setvar0;
5529 //math_state.endofname = endofname;
5532 result = arith(&math_state, s);
5533 if (math_state.errmsg)
5534 ash_msg_and_raise_error(math_state.errmsg);
5544 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5545 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5546 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5547 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5548 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5549 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5550 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5551 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5552 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5556 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5557 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5558 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5559 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5560 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5562 /* Add CTLESC when necessary. */
5563 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5564 /* Do not skip NUL characters. */
5565 #define QUOTES_KEEPNUL EXP_TILDE
5568 * Structure specifying which parts of the string should be searched
5569 * for IFS characters.
5572 struct ifsregion *next; /* next region in list */
5573 int begoff; /* offset of start of region */
5574 int endoff; /* offset of end of region */
5575 int nulonly; /* search for nul bytes only */
5579 struct strlist *list;
5580 struct strlist **lastp;
5583 /* output of current string */
5584 static char *expdest;
5585 /* list of back quote expressions */
5586 static struct nodelist *argbackq;
5587 /* first struct in list of ifs regions */
5588 static struct ifsregion ifsfirst;
5589 /* last struct in list */
5590 static struct ifsregion *ifslastp;
5591 /* holds expanded arg list */
5592 static struct arglist exparg;
5597 #if !ENABLE_SH_MATH_SUPPORT
5598 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5599 typedef long arith_t;
5600 # define ARITH_FMT "%ld"
5607 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5608 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5609 STADJUST(len, expdest);
5614 esclen(const char *start, const char *p)
5618 while (p > start && (unsigned char)*--p == CTLESC) {
5625 * Remove any CTLESC characters from a string.
5628 rmescapes(char *str, int flag)
5630 static const char qchars[] ALIGN1 = {
5631 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5635 unsigned protect_against_glob;
5637 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5639 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5645 if (flag & RMESCAPE_ALLOC) {
5646 size_t len = p - str;
5647 size_t fulllen = len + strlen(p) + 1;
5649 if (flag & RMESCAPE_GROW) {
5650 int strloc = str - (char *)stackblock();
5651 r = makestrspace(fulllen, expdest);
5652 /* p and str may be invalidated by makestrspace */
5653 str = (char *)stackblock() + strloc;
5655 } else if (flag & RMESCAPE_HEAP) {
5656 r = ckmalloc(fulllen);
5658 r = stalloc(fulllen);
5662 q = (char *)memcpy(q, str, len) + len;
5667 globbing = flag & RMESCAPE_GLOB;
5668 protect_against_glob = globbing;
5670 if ((unsigned char)*p == CTLQUOTEMARK) {
5671 // Note: both inquotes and protect_against_glob only affect whether
5672 inquotes = ~inquotes;
5674 protect_against_glob = globbing;
5677 if ((unsigned char)*p == CTLESC) {
5681 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5683 if (protect_against_glob) {
5686 } else if (*p == '\\' && !inquotes) {
5687 /* naked back slash */
5688 protect_against_glob = 0;
5691 #if ENABLE_ASH_BASH_COMPAT
5692 else if (*p == '/' && slash) {
5693 /* stop handling globbing and mark location of slash */
5694 globbing = slash = 0;
5698 protect_against_glob = globbing;
5703 if (flag & RMESCAPE_GROW) {
5705 STADJUST(q - r + 1, expdest);
5709 #define pmatch(a, b) !fnmatch((a), (b), 0)
5712 * Prepare a pattern for a expmeta (internal glob(3)) call.
5714 * Returns an stalloced string.
5717 preglob(const char *pattern, int flag)
5719 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5723 * Put a string on the stack.
5726 memtodest(const char *p, size_t len, int syntax, int quotes)
5733 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5736 unsigned char c = *p++;
5738 int n = SIT(c, syntax);
5739 if ((quotes & QUOTES_ESC)
5741 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5747 } else if (!(quotes & QUOTES_KEEPNUL))
5756 strtodest(const char *p, int syntax, int quotes)
5758 size_t len = strlen(p);
5759 memtodest(p, len, syntax, quotes);
5764 * Record the fact that we have to scan this region of the
5765 * string for IFS characters.
5768 recordregion(int start, int end, int nulonly)
5770 struct ifsregion *ifsp;
5772 if (ifslastp == NULL) {
5776 ifsp = ckzalloc(sizeof(*ifsp));
5777 /*ifsp->next = NULL; - ckzalloc did it */
5778 ifslastp->next = ifsp;
5782 ifslastp->begoff = start;
5783 ifslastp->endoff = end;
5784 ifslastp->nulonly = nulonly;
5788 removerecordregions(int endoff)
5790 if (ifslastp == NULL)
5793 if (ifsfirst.endoff > endoff) {
5794 while (ifsfirst.next) {
5795 struct ifsregion *ifsp;
5797 ifsp = ifsfirst.next->next;
5798 free(ifsfirst.next);
5799 ifsfirst.next = ifsp;
5802 if (ifsfirst.begoff > endoff) {
5805 ifslastp = &ifsfirst;
5806 ifsfirst.endoff = endoff;
5811 ifslastp = &ifsfirst;
5812 while (ifslastp->next && ifslastp->next->begoff < endoff)
5813 ifslastp = ifslastp->next;
5814 while (ifslastp->next) {
5815 struct ifsregion *ifsp;
5817 ifsp = ifslastp->next->next;
5818 free(ifslastp->next);
5819 ifslastp->next = ifsp;
5822 if (ifslastp->endoff > endoff)
5823 ifslastp->endoff = endoff;
5827 exptilde(char *startp, char *p, int flags)
5833 int quotes = flags & QUOTES_ESC;
5837 while ((c = *++p) != '\0') {
5844 if (flags & EXP_VARTILDE)
5854 if (*name == '\0') {
5855 home = lookupvar("HOME");
5857 pw = getpwnam(name);
5862 if (!home || !*home)
5865 strtodest(home, SQSYNTAX, quotes);
5873 * Execute a command inside back quotes. If it's a builtin command, we
5874 * want to save its output in a block obtained from malloc. Otherwise
5875 * we fork off a subprocess and get the output of the command via a pipe.
5876 * Should be called with interrupts off.
5878 struct backcmd { /* result of evalbackcmd */
5879 int fd; /* file descriptor to read from */
5880 int nleft; /* number of chars in buffer */
5881 char *buf; /* buffer */
5882 struct job *jp; /* job structure for command */
5885 /* These forward decls are needed to use "eval" code for backticks handling: */
5886 #define EV_EXIT 01 /* exit after evaluating tree */
5887 static int evaltree(union node *, int);
5889 static void FAST_FUNC
5890 evalbackcmd(union node *n, struct backcmd *result)
5901 saveherefd = herefd;
5909 ash_msg_and_raise_error("pipe call failed");
5910 jp = makejob(/*n,*/ 1);
5911 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5916 copyfd(pip[1], 1 | COPYFD_EXACT);
5920 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5924 result->fd = pip[0];
5927 herefd = saveherefd;
5929 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5930 result->fd, result->buf, result->nleft, result->jp));
5934 * Expand stuff in backwards quotes.
5937 expbackq(union node *cmd, int flag)
5945 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5946 struct stackmark smark;
5949 startloc = expdest - (char *)stackblock();
5950 pushstackmark(&smark, startloc);
5951 evalbackcmd(cmd, &in);
5952 popstackmark(&smark);
5959 memtodest(p, i, syntax, flag & QUOTES_ESC);
5963 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5964 TRACE(("expbackq: read returns %d\n", i));
5973 back_exitstatus = waitforjob(in.jp);
5977 /* Eat all trailing newlines */
5979 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5983 if (!(flag & EXP_QUOTED))
5984 recordregion(startloc, dest - (char *)stackblock(), 0);
5985 TRACE(("evalbackq: size:%d:'%.*s'\n",
5986 (int)((dest - (char *)stackblock()) - startloc),
5987 (int)((dest - (char *)stackblock()) - startloc),
5988 stackblock() + startloc));
5991 #if ENABLE_SH_MATH_SUPPORT
5993 * Expand arithmetic expression. Backup to start of expression,
5994 * evaluate, place result in (backed up) result, adjust string position.
6006 * This routine is slightly over-complicated for
6007 * efficiency. Next we scan backwards looking for the
6008 * start of arithmetic.
6010 start = stackblock();
6017 while ((unsigned char)*p != CTLARI) {
6021 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6026 esc = esclen(start, p);
6036 removerecordregions(begoff);
6040 if (flag & QUOTES_ESC)
6041 rmescapes(p + 1, 0);
6043 len = cvtnum(ash_arith(p + 1));
6045 if (!(flag & EXP_QUOTED))
6046 recordregion(begoff, begoff + len, 0);
6050 /* argstr needs it */
6051 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6054 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6055 * characters to allow for further processing. Otherwise treat
6056 * $@ like $* since no splitting will be performed.
6058 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6059 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6060 * for correct expansion of "B=$A" word.
6063 argstr(char *p, int flags, struct strlist *var_str_list)
6065 static const char spclchars[] ALIGN1 = {
6073 #if ENABLE_SH_MATH_SUPPORT
6078 const char *reject = spclchars;
6079 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6084 if (!(flags & EXP_VARTILDE)) {
6086 } else if (flags & EXP_VARTILDE2) {
6091 if (flags & EXP_TILDE) {
6094 flags &= ~EXP_TILDE;
6098 p = exptilde(p, q, flags);
6101 startloc = expdest - (char *)stackblock();
6105 length += strcspn(p + length, reject);
6109 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6111 /* c == '=' || c == ':' || c == CTLENDARI */
6117 expdest = stack_nputstr(p, length, expdest);
6118 newloc = expdest - (char *)stackblock();
6119 if (breakall && !inquotes && newloc > startloc) {
6120 recordregion(startloc, newloc, 0);
6131 if (flags & EXP_VARTILDE2) {
6135 flags |= EXP_VARTILDE2;
6140 * sort of a hack - expand tildes in variable
6141 * assignments (after the first '=' and after ':'s).
6150 case CTLENDVAR: /* ??? */
6153 inquotes ^= EXP_QUOTED;
6154 /* "$@" syntax adherence hack */
6155 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6156 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6160 if (flags & QUOTES_ESC) {
6171 * Quoted parameter expansion pattern: remove quote
6172 * unless inside inner quotes or we have a literal
6175 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6176 EXP_QPAT && *p != '\\')
6181 TRACE(("argstr: evalvar('%s')\n", p));
6182 p = evalvar(p, flags | inquotes, var_str_list);
6183 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6186 expbackq(argbackq->n, flags | inquotes);
6187 argbackq = argbackq->next;
6189 #if ENABLE_SH_MATH_SUPPORT
6192 expari(flags | inquotes);
6201 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6202 char *pattern, int quotes, int zero)
6211 const char *s = loc2;
6218 match = pmatch(pattern, s);
6223 if (quotes && (unsigned char)*loc == CTLESC)
6232 scanright(char *startp, char *rmesc, char *rmescend,
6233 char *pattern, int quotes, int match_at_start)
6235 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6236 int try2optimize = match_at_start;
6242 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6243 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6244 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6246 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6247 * and on each iteration they go back two/one char until they reach the beginning.
6248 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6250 /* TODO: document in what other circumstances we are called. */
6252 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6255 const char *s = loc2;
6256 if (match_at_start) {
6260 match = pmatch(pattern, s);
6261 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6265 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6267 /* Maybe we can optimize this:
6268 * if pattern ends with unescaped *, we can avoid checking
6269 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6270 * it wont match truncated "raw_value_of_" strings too.
6272 unsigned plen = strlen(pattern);
6273 /* Does it end with "*"? */
6274 if (plen != 0 && pattern[--plen] == '*') {
6275 /* "xxxx*" is not escaped */
6276 /* "xxx\*" is escaped */
6277 /* "xx\\*" is not escaped */
6278 /* "x\\\*" is escaped */
6280 while (plen != 0 && pattern[--plen] == '\\')
6283 break; /* ends with unescaped "*" */
6291 esc = esclen(startp, loc);
6302 static void varunset(const char *, const char *, const char *, int) NORETURN;
6304 varunset(const char *end, const char *var, const char *umsg, int varflags)
6310 msg = "parameter not set";
6312 if ((unsigned char)*end == CTLENDVAR) {
6313 if (varflags & VSNUL)
6319 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6323 subevalvar(char *p, char *varname, int strloc, int subtype,
6324 int startloc, int varflags, int flag, struct strlist *var_str_list)
6326 struct nodelist *saveargbackq = argbackq;
6327 int quotes = flag & QUOTES_ESC;
6330 char *rmesc, *rmescend;
6332 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6333 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6334 int saveherefd = herefd;
6335 int amount, resetloc;
6336 IF_ASH_BASH_COMPAT(int workloc;)
6338 char *(*scan)(char*, char*, char*, char*, int, int);
6340 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6341 // p, varname, strloc, subtype, startloc, varflags, quotes);
6344 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6345 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6347 STPUTC('\0', expdest);
6348 herefd = saveherefd;
6349 argbackq = saveargbackq;
6350 startp = (char *)stackblock() + startloc;
6354 setvar0(varname, startp);
6355 amount = startp - expdest;
6356 STADJUST(amount, expdest);
6360 varunset(p, varname, startp, varflags);
6363 #if ENABLE_ASH_BASH_COMPAT
6365 //TODO: support more general format ${v:EXPR:EXPR},
6366 // where EXPR follows $(()) rules
6367 loc = str = stackblock() + strloc;
6368 /* Read POS in ${var:POS:LEN} */
6369 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6370 len = str - startp - 1;
6372 /* *loc != '\0', guaranteed by parser */
6376 /* Adjust the length by the number of escapes */
6377 for (ptr = startp; ptr < (str - 1); ptr++) {
6378 if ((unsigned char)*ptr == CTLESC) {
6386 if (*loc++ == ':') {
6390 /* Skip POS in ${var:POS:LEN} */
6392 while (*loc && *loc != ':') {
6394 * bash complains on: var=qwe; echo ${var:1a:123}
6396 ash_msg_and_raise_error(msg_illnum, str);
6400 if (*loc++ == ':') {
6405 /* ${VAR:$((-n)):l} starts n chars from the end */
6406 pos = orig_len + pos;
6408 if ((unsigned)pos >= orig_len) {
6409 /* apart from obvious ${VAR:999999:l},
6410 * covers ${VAR:$((-9999999)):l} - result is ""
6416 if (len > (orig_len - pos))
6417 len = orig_len - pos;
6419 for (str = startp; pos; str++, pos--) {
6420 if (quotes && (unsigned char)*str == CTLESC)
6423 for (loc = startp; len; len--) {
6424 if (quotes && (unsigned char)*str == CTLESC)
6429 amount = loc - expdest;
6430 STADJUST(amount, expdest);
6435 resetloc = expdest - (char *)stackblock();
6437 /* We'll comeback here if we grow the stack while handling
6438 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6439 * stack will need rebasing, and we'll need to remove our work
6442 IF_ASH_BASH_COMPAT(restart:)
6444 amount = expdest - ((char *)stackblock() + resetloc);
6445 STADJUST(-amount, expdest);
6446 startp = (char *)stackblock() + startloc;
6449 rmescend = (char *)stackblock() + strloc;
6451 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6452 if (rmesc != startp) {
6454 startp = (char *)stackblock() + startloc;
6458 str = (char *)stackblock() + strloc;
6460 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6461 * The result is a_\_z_c (not a\_\_z_c)!
6463 * The search pattern and replace string treat backslashes differently!
6464 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6465 * and string. It's only used on the first call.
6467 preglob(str, IF_ASH_BASH_COMPAT(
6468 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6469 RMESCAPE_SLASH :) 0);
6471 #if ENABLE_ASH_BASH_COMPAT
6472 workloc = expdest - (char *)stackblock();
6473 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6477 repl = strchr(str, CTLESC);
6483 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6485 /* If there's no pattern to match, return the expansion unmolested */
6494 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6495 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6497 /* No match, advance */
6498 char *restart_detect = stackblock();
6500 STPUTC(*idx, expdest);
6501 if (quotes && (unsigned char)*idx == CTLESC) {
6504 STPUTC(*idx, expdest);
6506 if (stackblock() != restart_detect)
6511 /* continue; - prone to quadratic behavior, smarter code: */
6514 if (str[0] == '*') {
6515 /* Pattern is "*foo". If "*foo" does not match "long_string",
6516 * it would never match "ong_string" etc, no point in trying.
6523 if (subtype == VSREPLACEALL) {
6525 if (quotes && (unsigned char)*idx == CTLESC)
6534 //bb_error_msg("repl:'%s'", repl);
6535 for (loc = (char*)repl; *loc; loc++) {
6536 char *restart_detect = stackblock();
6537 if (quotes && *loc == '\\') {
6538 STPUTC(CTLESC, expdest);
6541 STPUTC(*loc, expdest);
6542 if (stackblock() != restart_detect)
6547 if (subtype == VSREPLACE) {
6548 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6550 char *restart_detect = stackblock();
6551 STPUTC(*idx, expdest);
6552 if (stackblock() != restart_detect)
6561 /* We've put the replaced text into a buffer at workloc, now
6562 * move it to the right place and adjust the stack.
6564 STPUTC('\0', expdest);
6565 startp = (char *)stackblock() + startloc;
6566 memmove(startp, (char *)stackblock() + workloc, len + 1);
6567 //bb_error_msg("startp:'%s'", startp);
6568 amount = expdest - (startp + len);
6569 STADJUST(-amount, expdest);
6572 #endif /* ENABLE_ASH_BASH_COMPAT */
6574 subtype -= VSTRIMRIGHT;
6576 if (subtype < 0 || subtype > 7)
6579 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6580 zero = subtype >> 1;
6581 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6582 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6584 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6587 memmove(startp, loc, str - loc);
6588 loc = startp + (str - loc) - 1;
6591 amount = loc - expdest;
6592 STADJUST(amount, expdest);
6598 * Add the value of a specialized variable to the stack string.
6599 * name parameter (examples):
6600 * ash -c 'echo $1' name:'1='
6601 * ash -c 'echo $qwe' name:'qwe='
6602 * ash -c 'echo $$' name:'$='
6603 * ash -c 'echo ${$}' name:'$='
6604 * ash -c 'echo ${$##q}' name:'$=q'
6605 * ash -c 'echo ${#$}' name:'$='
6606 * note: examples with bad shell syntax:
6607 * ash -c 'echo ${#$1}' name:'$=1'
6608 * ash -c 'echo ${#1#}' name:'1=#'
6610 static NOINLINE ssize_t
6611 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6618 int quoted = *quotedp;
6619 int subtype = varflags & VSTYPE;
6620 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6621 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6624 sep = (flags & EXP_FULL) << CHAR_BIT;
6625 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6635 num = shellparam.nparam;
6643 goto check_1char_name;
6645 expdest = makestrspace(NOPTS, expdest);
6646 for (i = NOPTS - 1; i >= 0; i--) {
6648 USTPUTC(optletters(i), expdest);
6654 /* handles cases similar to ${#$1} */
6655 if (name[2] != '\0')
6656 raise_error_syntax("bad substitution");
6669 sep |= ifsset() ? ifsval()[0] : ' ';
6676 while ((p = *ap++) != NULL) {
6677 len += strtodest(p, syntax, quotes);
6681 memtodest(&sepc, 1, syntax, quotes);
6696 num = atoi(name); /* number(name) fails on ${N#str} etc */
6697 if (num < 0 || num > shellparam.nparam)
6699 p = num ? shellparam.p[num - 1] : arg0;
6702 /* NB: name has form "VAR=..." */
6704 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6705 * which should be considered before we check variables. */
6707 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6711 str = var_str_list->text;
6712 eq = strchr(str, '=');
6713 if (!eq) /* stop at first non-assignment */
6716 if (name_len == (unsigned)(eq - str)
6717 && strncmp(str, name, name_len) == 0
6720 /* goto value; - WRONG! */
6721 /* think "A=1 A=2 B=$A" */
6723 var_str_list = var_str_list->next;
6724 } while (var_str_list);
6728 p = lookupvar(name);
6733 len = strtodest(p, syntax, quotes);
6734 #if ENABLE_UNICODE_SUPPORT
6735 if (subtype == VSLENGTH && len > 0) {
6736 reinit_unicode_for_ash();
6737 if (unicode_status == UNICODE_ON) {
6738 STADJUST(-len, expdest);
6740 len = unicode_strlen(p);
6748 STADJUST(-len, expdest);
6753 * Expand a variable, and return a pointer to the next character in the
6757 evalvar(char *p, int flag, struct strlist *var_str_list)
6768 varflags = (unsigned char) *p++;
6769 subtype = varflags & VSTYPE;
6770 quoted = flag & EXP_QUOTED;
6772 easy = (!quoted || (*var == '@' && shellparam.nparam));
6773 startloc = expdest - (char *)stackblock();
6774 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6777 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6778 if (varflags & VSNUL)
6781 if (subtype == VSPLUS) {
6782 varlen = -1 - varlen;
6786 if (subtype == VSMINUS) {
6791 flag | EXP_TILDE | EXP_WORD,
6799 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6803 subevalvar(p, var, 0, subtype, startloc, varflags,
6804 flag & ~QUOTES_ESC, var_str_list);
6807 * Remove any recorded regions beyond
6810 removerecordregions(startloc);
6814 if (varlen < 0 && uflag)
6815 varunset(p, var, 0, 0);
6817 if (subtype == VSLENGTH) {
6818 cvtnum(varlen > 0 ? varlen : 0);
6822 if (subtype == VSNORMAL) {
6826 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6835 case VSTRIMRIGHTMAX:
6836 #if ENABLE_ASH_BASH_COMPAT
6849 * Terminate the string and start recording the pattern
6852 STPUTC('\0', expdest);
6853 patloc = expdest - (char *)stackblock();
6854 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6855 startloc, varflags, flag, var_str_list)) {
6856 int amount = expdest - (
6857 (char *)stackblock() + patloc - 1
6859 STADJUST(-amount, expdest);
6861 /* Remove any recorded regions beyond start of variable */
6862 removerecordregions(startloc);
6867 if (subtype != VSNORMAL) { /* skip to end of alternative */
6870 unsigned char c = *p++;
6873 else if (c == CTLBACKQ) {
6875 argbackq = argbackq->next;
6876 } else if (c == CTLVAR) {
6877 if ((*p++ & VSTYPE) != VSNORMAL)
6879 } else if (c == CTLENDVAR) {
6889 * Break the argument string into pieces based upon IFS and add the
6890 * strings to the argument list. The regions of the string to be
6891 * searched for IFS characters have been stored by recordregion.
6894 ifsbreakup(char *string, struct arglist *arglist)
6896 struct ifsregion *ifsp;
6901 const char *ifs, *realifs;
6906 if (ifslastp != NULL) {
6909 realifs = ifsset() ? ifsval() : defifs;
6912 p = string + ifsp->begoff;
6913 nulonly = ifsp->nulonly;
6914 ifs = nulonly ? nullstr : realifs;
6916 while (p < string + ifsp->endoff) {
6918 if ((unsigned char)*p == CTLESC)
6920 if (!strchr(ifs, *p)) {
6925 ifsspc = (strchr(defifs, *p) != NULL);
6926 /* Ignore IFS whitespace at start */
6927 if (q == start && ifsspc) {
6933 sp = stzalloc(sizeof(*sp));
6935 *arglist->lastp = sp;
6936 arglist->lastp = &sp->next;
6940 if (p >= string + ifsp->endoff) {
6944 if ((unsigned char)*p == CTLESC)
6946 if (strchr(ifs, *p) == NULL) {
6950 if (strchr(defifs, *p) == NULL) {
6965 } while (ifsp != NULL);
6974 sp = stzalloc(sizeof(*sp));
6976 *arglist->lastp = sp;
6977 arglist->lastp = &sp->next;
6983 struct ifsregion *p;
6988 struct ifsregion *ifsp;
6994 ifsfirst.next = NULL;
6999 * Add a file name to the list.
7002 addfname(const char *name)
7006 sp = stzalloc(sizeof(*sp));
7007 sp->text = sstrdup(name);
7009 exparg.lastp = &sp->next;
7012 /* If we want to use glob() from libc... */
7013 #if !ENABLE_ASH_INTERNAL_GLOB
7015 /* Add the result of glob() to the list */
7017 addglob(const glob_t *pglob)
7019 char **p = pglob->gl_pathv;
7026 expandmeta(struct strlist *str /*, int flag*/)
7028 /* TODO - EXP_REDIR */
7038 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7039 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7040 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7042 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7043 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7044 // Which means you need to unescape the string, right? Not so fast:
7045 // if there _is_ a file named "file\?" (with backslash), it is returned
7046 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7047 // You DONT KNOW by looking at the result whether you need to unescape it.
7049 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7050 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7051 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7052 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7053 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7054 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7055 i = glob(p, 0, NULL, &pglob);
7056 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7061 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7062 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7063 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7075 *exparg.lastp = str;
7076 rmescapes(str->text, 0);
7077 exparg.lastp = &str->next;
7079 default: /* GLOB_NOSPACE */
7082 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7089 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7092 * Do metacharacter (i.e. *, ?, [...]) expansion.
7095 expmeta(char *expdir, char *enddir, char *name)
7111 for (p = name; esc = 0, *p; p += esc + 1) {
7112 if (*p == '*' || *p == '?')
7114 else if (*p == '[') {
7121 if (*q == '/' || *q == '\0')
7131 if (p[esc] == '/') {
7134 start = p + esc + 1;
7138 if (metaflag == 0) { /* we've reached the end of the file name */
7139 if (enddir != expdir)
7147 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7158 } while (p < start);
7160 if (enddir == expdir) {
7162 } else if (enddir == expdir + 1 && *expdir == '/') {
7171 if (enddir != expdir)
7173 if (*endname == 0) {
7186 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7187 if (dp->d_name[0] == '.' && !matchdot)
7189 if (pmatch(start, dp->d_name)) {
7191 strcpy(enddir, dp->d_name);
7194 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7197 expmeta(expdir, p, endname);
7203 endname[-esc - 1] = esc ? '\\' : '/';
7206 static struct strlist *
7207 msort(struct strlist *list, int len)
7209 struct strlist *p, *q = NULL;
7210 struct strlist **lpp;
7218 for (n = half; --n >= 0;) {
7222 q->next = NULL; /* terminate first half of list */
7223 q = msort(list, half); /* sort first half of list */
7224 p = msort(p, len - half); /* sort second half */
7227 #if ENABLE_LOCALE_SUPPORT
7228 if (strcoll(p->text, q->text) < 0)
7230 if (strcmp(p->text, q->text) < 0)
7254 * Sort the results of file name expansion. It calculates the number of
7255 * strings to sort and then calls msort (short for merge sort) to do the
7258 static struct strlist *
7259 expsort(struct strlist *str)
7265 for (sp = str; sp; sp = sp->next)
7267 return msort(str, len);
7271 expandmeta(struct strlist *str /*, int flag*/)
7273 static const char metachars[] ALIGN1 = {
7276 /* TODO - EXP_REDIR */
7280 struct strlist **savelastp;
7286 if (!strpbrk(str->text, metachars))
7288 savelastp = exparg.lastp;
7291 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7293 int i = strlen(str->text);
7294 //BUGGY estimation of how long expanded name can be
7295 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7297 expmeta(expdir, expdir, p);
7302 if (exparg.lastp == savelastp) {
7307 *exparg.lastp = str;
7308 rmescapes(str->text, 0);
7309 exparg.lastp = &str->next;
7311 *exparg.lastp = NULL;
7312 *savelastp = sp = expsort(*savelastp);
7313 while (sp->next != NULL)
7315 exparg.lastp = &sp->next;
7320 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7323 * Perform variable substitution and command substitution on an argument,
7324 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7325 * perform splitting and file name expansion. When arglist is NULL, perform
7326 * here document expansion.
7329 expandarg(union node *arg, struct arglist *arglist, int flag)
7334 argbackq = arg->narg.backquote;
7335 STARTSTACKSTR(expdest);
7336 ifsfirst.next = NULL;
7338 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7339 argstr(arg->narg.text, flag,
7340 /* var_str_list: */ arglist ? arglist->list : NULL);
7341 p = _STPUTC('\0', expdest);
7343 if (arglist == NULL) {
7344 return; /* here document expanded */
7346 p = grabstackstr(p);
7347 TRACE(("expandarg: p:'%s'\n", p));
7348 exparg.lastp = &exparg.list;
7352 if (flag & EXP_FULL) {
7353 ifsbreakup(p, &exparg);
7354 *exparg.lastp = NULL;
7355 exparg.lastp = &exparg.list;
7356 expandmeta(exparg.list /*, flag*/);
7358 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7360 TRACE(("expandarg: rmescapes:'%s'\n", p));
7362 sp = stzalloc(sizeof(*sp));
7365 exparg.lastp = &sp->next;
7369 *exparg.lastp = NULL;
7371 *arglist->lastp = exparg.list;
7372 arglist->lastp = exparg.lastp;
7377 * Expand shell variables and backquotes inside a here document.
7380 expandhere(union node *arg, int fd)
7383 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7384 full_write(fd, stackblock(), expdest - (char *)stackblock());
7388 * Returns true if the pattern matches the string.
7391 patmatch(char *pattern, const char *string)
7393 return pmatch(preglob(pattern, 0), string);
7397 * See if a pattern matches in a case statement.
7400 casematch(union node *pattern, char *val)
7402 struct stackmark smark;
7405 setstackmark(&smark);
7406 argbackq = pattern->narg.backquote;
7407 STARTSTACKSTR(expdest);
7409 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7410 /* var_str_list: */ NULL);
7411 STACKSTRNUL(expdest);
7412 result = patmatch(stackblock(), val);
7413 popstackmark(&smark);
7418 /* ============ find_command */
7422 int (*builtin)(int, char **) FAST_FUNC;
7423 /* unsigned flags; */
7425 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7426 /* "regular" builtins always take precedence over commands,
7427 * regardless of PATH=....%builtin... position */
7428 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7429 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7432 smallint cmdtype; /* CMDxxx */
7435 /* index >= 0 for commands without path (slashes) */
7436 /* (TODO: what exactly does the value mean? PATH position?) */
7437 /* index == -1 for commands with slashes */
7438 /* index == (-2 - applet_no) for NOFORK applets */
7439 const struct builtincmd *cmd;
7440 struct funcnode *func;
7443 /* values of cmdtype */
7444 #define CMDUNKNOWN -1 /* no entry in table for command */
7445 #define CMDNORMAL 0 /* command is an executable program */
7446 #define CMDFUNCTION 1 /* command is a shell function */
7447 #define CMDBUILTIN 2 /* command is a shell builtin */
7449 /* action to find_command() */
7450 #define DO_ERR 0x01 /* prints errors */
7451 #define DO_ABS 0x02 /* checks absolute paths */
7452 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7453 #define DO_ALTPATH 0x08 /* using alternate path */
7454 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7456 static void find_command(char *, struct cmdentry *, int, const char *);
7459 /* ============ Hashing commands */
7462 * When commands are first encountered, they are entered in a hash table.
7463 * This ensures that a full path search will not have to be done for them
7464 * on each invocation.
7466 * We should investigate converting to a linear search, even though that
7467 * would make the command name "hash" a misnomer.
7471 struct tblentry *next; /* next entry in hash chain */
7472 union param param; /* definition of builtin function */
7473 smallint cmdtype; /* CMDxxx */
7474 char rehash; /* if set, cd done since entry created */
7475 char cmdname[1]; /* name of command */
7478 static struct tblentry **cmdtable;
7479 #define INIT_G_cmdtable() do { \
7480 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7483 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7487 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7489 #if ENABLE_FEATURE_SH_STANDALONE
7490 if (applet_no >= 0) {
7491 if (APPLET_IS_NOEXEC(applet_no)) {
7495 run_applet_no_and_exit(applet_no, argv);
7497 /* re-exec ourselves with the new arguments */
7498 execve(bb_busybox_exec_path, argv, envp);
7499 /* If they called chroot or otherwise made the binary no longer
7500 * executable, fall through */
7507 execve(cmd, argv, envp);
7508 } while (errno == EINTR);
7510 execve(cmd, argv, envp);
7512 if (cmd == (char*) bb_busybox_exec_path) {
7513 /* We already visited ENOEXEC branch below, don't do it again */
7514 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7518 if (errno == ENOEXEC) {
7519 /* Run "cmd" as a shell script:
7520 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7521 * "If the execve() function fails with ENOEXEC, the shell
7522 * shall execute a command equivalent to having a shell invoked
7523 * with the command name as its first operand,
7524 * with any remaining arguments passed to the new shell"
7526 * That is, do not use $SHELL, user's shell, or /bin/sh;
7527 * just call ourselves.
7529 * Note that bash reads ~80 chars of the file, and if it sees
7530 * a zero byte before it sees newline, it doesn't try to
7531 * interpret it, but fails with "cannot execute binary file"
7532 * message and exit code 126. For one, this prevents attempts
7533 * to interpret foreign ELF binaries as shell scripts.
7538 for (ap = argv; *ap; ap++)
7540 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7541 new[0] = (char*) "ash";
7544 while ((*ap++ = *++argv) != NULL)
7546 cmd = (char*) bb_busybox_exec_path;
7553 * Exec a program. Never returns. If you change this routine, you may
7554 * have to change the find_command routine as well.
7556 static void shellexec(char **, const char *, int) NORETURN;
7558 shellexec(char **argv, const char *path, int idx)
7564 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7566 clearredir(/*drop:*/ 1);
7567 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7568 if (strchr(argv[0], '/') != NULL
7569 #if ENABLE_FEATURE_SH_STANDALONE
7570 || (applet_no = find_applet_by_name(argv[0])) >= 0
7573 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7574 if (applet_no >= 0) {
7575 /* We tried execing ourself, but it didn't work.
7576 * Maybe /proc/self/exe doesn't exist?
7585 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7586 if (--idx < 0 && pathopt == NULL) {
7587 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7588 if (errno != ENOENT && errno != ENOTDIR)
7595 /* Map to POSIX errors */
7607 exitstatus = exerrno;
7608 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7609 argv[0], e, suppress_int));
7610 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7615 printentry(struct tblentry *cmdp)
7621 idx = cmdp->param.index;
7624 name = path_advance(&path, cmdp->cmdname);
7626 } while (--idx >= 0);
7627 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7631 * Clear out command entries. The argument specifies the first entry in
7632 * PATH which has changed.
7635 clearcmdentry(int firstchange)
7637 struct tblentry **tblp;
7638 struct tblentry **pp;
7639 struct tblentry *cmdp;
7642 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7644 while ((cmdp = *pp) != NULL) {
7645 if ((cmdp->cmdtype == CMDNORMAL &&
7646 cmdp->param.index >= firstchange)
7647 || (cmdp->cmdtype == CMDBUILTIN &&
7648 builtinloc >= firstchange)
7661 * Locate a command in the command hash table. If "add" is nonzero,
7662 * add the command to the table if it is not already present. The
7663 * variable "lastcmdentry" is set to point to the address of the link
7664 * pointing to the entry, so that delete_cmd_entry can delete the
7667 * Interrupts must be off if called with add != 0.
7669 static struct tblentry **lastcmdentry;
7671 static struct tblentry *
7672 cmdlookup(const char *name, int add)
7674 unsigned int hashval;
7676 struct tblentry *cmdp;
7677 struct tblentry **pp;
7680 hashval = (unsigned char)*p << 4;
7682 hashval += (unsigned char)*p++;
7684 pp = &cmdtable[hashval % CMDTABLESIZE];
7685 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7686 if (strcmp(cmdp->cmdname, name) == 0)
7690 if (add && cmdp == NULL) {
7691 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7693 /* + 1 - already done because
7694 * tblentry::cmdname is char[1] */);
7695 /*cmdp->next = NULL; - ckzalloc did it */
7696 cmdp->cmdtype = CMDUNKNOWN;
7697 strcpy(cmdp->cmdname, name);
7704 * Delete the command entry returned on the last lookup.
7707 delete_cmd_entry(void)
7709 struct tblentry *cmdp;
7712 cmdp = *lastcmdentry;
7713 *lastcmdentry = cmdp->next;
7714 if (cmdp->cmdtype == CMDFUNCTION)
7715 freefunc(cmdp->param.func);
7721 * Add a new command entry, replacing any existing command entry for
7722 * the same name - except special builtins.
7725 addcmdentry(char *name, struct cmdentry *entry)
7727 struct tblentry *cmdp;
7729 cmdp = cmdlookup(name, 1);
7730 if (cmdp->cmdtype == CMDFUNCTION) {
7731 freefunc(cmdp->param.func);
7733 cmdp->cmdtype = entry->cmdtype;
7734 cmdp->param = entry->u;
7738 static int FAST_FUNC
7739 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7741 struct tblentry **pp;
7742 struct tblentry *cmdp;
7744 struct cmdentry entry;
7747 if (nextopt("r") != '\0') {
7752 if (*argptr == NULL) {
7753 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7754 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7755 if (cmdp->cmdtype == CMDNORMAL)
7763 while ((name = *argptr) != NULL) {
7764 cmdp = cmdlookup(name, 0);
7766 && (cmdp->cmdtype == CMDNORMAL
7767 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7771 find_command(name, &entry, DO_ERR, pathval());
7772 if (entry.cmdtype == CMDUNKNOWN)
7780 * Called when a cd is done. Marks all commands so the next time they
7781 * are executed they will be rehashed.
7786 struct tblentry **pp;
7787 struct tblentry *cmdp;
7789 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7790 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7791 if (cmdp->cmdtype == CMDNORMAL
7792 || (cmdp->cmdtype == CMDBUILTIN
7793 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7803 * Fix command hash table when PATH changed.
7804 * Called before PATH is changed. The argument is the new value of PATH;
7805 * pathval() still returns the old value at this point.
7806 * Called with interrupts off.
7808 static void FAST_FUNC
7809 changepath(const char *new)
7817 firstchange = 9999; /* assume no change */
7823 if ((*old == '\0' && *new == ':')
7824 || (*old == ':' && *new == '\0')
7828 old = new; /* ignore subsequent differences */
7832 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7839 if (builtinloc < 0 && idx_bltin >= 0)
7840 builtinloc = idx_bltin; /* zap builtins */
7841 if (builtinloc >= 0 && idx_bltin < 0)
7843 clearcmdentry(firstchange);
7844 builtinloc = idx_bltin;
7869 #if ENABLE_ASH_BASH_COMPAT
7880 typedef smallint token_id_t;
7882 /* Nth bit indicates if token marks the end of a list */
7885 /* 0 */ | (1u << TEOF)
7886 /* 1 */ | (0u << TNL)
7887 /* 2 */ | (0u << TREDIR)
7888 /* 3 */ | (0u << TWORD)
7889 /* 4 */ | (0u << TSEMI)
7890 /* 5 */ | (0u << TBACKGND)
7891 /* 6 */ | (0u << TAND)
7892 /* 7 */ | (0u << TOR)
7893 /* 8 */ | (0u << TPIPE)
7894 /* 9 */ | (0u << TLP)
7895 /* 10 */ | (1u << TRP)
7896 /* 11 */ | (1u << TENDCASE)
7897 /* 12 */ | (1u << TENDBQUOTE)
7898 /* 13 */ | (0u << TNOT)
7899 /* 14 */ | (0u << TCASE)
7900 /* 15 */ | (1u << TDO)
7901 /* 16 */ | (1u << TDONE)
7902 /* 17 */ | (1u << TELIF)
7903 /* 18 */ | (1u << TELSE)
7904 /* 19 */ | (1u << TESAC)
7905 /* 20 */ | (1u << TFI)
7906 /* 21 */ | (0u << TFOR)
7907 #if ENABLE_ASH_BASH_COMPAT
7908 /* 22 */ | (0u << TFUNCTION)
7910 /* 23 */ | (0u << TIF)
7911 /* 24 */ | (0u << TIN)
7912 /* 25 */ | (1u << TTHEN)
7913 /* 26 */ | (0u << TUNTIL)
7914 /* 27 */ | (0u << TWHILE)
7915 /* 28 */ | (0u << TBEGIN)
7916 /* 29 */ | (1u << TEND)
7917 , /* thus far 29 bits used */
7920 static const char *const tokname_array[] = {
7934 #define KWDOFFSET 13
7935 /* the following are keywords */
7945 #if ENABLE_ASH_BASH_COMPAT
7957 /* Wrapper around strcmp for qsort/bsearch/... */
7959 pstrcmp(const void *a, const void *b)
7961 return strcmp((char*)a, *(char**)b);
7964 static const char *const *
7965 findkwd(const char *s)
7967 return bsearch(s, tokname_array + KWDOFFSET,
7968 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7969 sizeof(tokname_array[0]), pstrcmp);
7973 * Locate and print what a word is...
7976 describe_command(char *command, const char *path, int describe_command_verbose)
7978 struct cmdentry entry;
7979 struct tblentry *cmdp;
7980 #if ENABLE_ASH_ALIAS
7981 const struct alias *ap;
7984 path = path ? path : pathval();
7986 if (describe_command_verbose) {
7990 /* First look at the keywords */
7991 if (findkwd(command)) {
7992 out1str(describe_command_verbose ? " is a shell keyword" : command);
7996 #if ENABLE_ASH_ALIAS
7997 /* Then look at the aliases */
7998 ap = lookupalias(command, 0);
8000 if (!describe_command_verbose) {
8005 out1fmt(" is an alias for %s", ap->val);
8009 /* Then check if it is a tracked alias */
8010 cmdp = cmdlookup(command, 0);
8012 entry.cmdtype = cmdp->cmdtype;
8013 entry.u = cmdp->param;
8015 /* Finally use brute force */
8016 find_command(command, &entry, DO_ABS, path);
8019 switch (entry.cmdtype) {
8021 int j = entry.u.index;
8027 p = path_advance(&path, command);
8031 if (describe_command_verbose) {
8033 (cmdp ? " a tracked alias for" : nullstr), p
8042 if (describe_command_verbose) {
8043 out1str(" is a shell function");
8050 if (describe_command_verbose) {
8051 out1fmt(" is a %sshell builtin",
8052 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8053 "special " : nullstr
8061 if (describe_command_verbose) {
8062 out1str(": not found\n");
8071 static int FAST_FUNC
8072 typecmd(int argc UNUSED_PARAM, char **argv)
8078 /* type -p ... ? (we don't bother checking for 'p') */
8079 if (argv[1] && argv[1][0] == '-') {
8084 err |= describe_command(argv[i++], NULL, verbose);
8089 #if ENABLE_ASH_CMDCMD
8090 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8092 parse_command_args(char **argv, const char **path)
8105 if (c == '-' && !*cp) {
8113 *path = bb_default_path;
8116 /* run 'typecmd' for other options */
8125 static int FAST_FUNC
8126 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8134 const char *path = NULL;
8136 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8137 * never reaches this function.
8140 while ((c = nextopt("pvV")) != '\0')
8142 verify |= VERIFY_VERBOSE;
8144 /*verify |= VERIFY_BRIEF*/;
8150 path = bb_default_path;
8152 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8154 if (/*verify && */ cmd)
8155 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8162 static int funcblocksize; /* size of structures in function */
8163 static int funcstringsize; /* size of strings in node */
8164 static void *funcblock; /* block to allocate function from */
8165 static char *funcstring; /* block to allocate strings from */
8167 /* flags in argument to evaltree */
8168 #define EV_EXIT 01 /* exit after evaluating tree */
8169 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8171 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8172 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8173 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8174 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8175 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8176 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8177 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8178 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8179 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8180 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8181 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8182 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8183 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8184 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8185 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8186 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8187 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8188 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8189 #if ENABLE_ASH_BASH_COMPAT
8190 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8192 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8193 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8194 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8195 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8196 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8197 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8198 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8199 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8200 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8203 static void calcsize(union node *n);
8206 sizenodelist(struct nodelist *lp)
8209 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8216 calcsize(union node *n)
8220 funcblocksize += nodesize[n->type];
8223 calcsize(n->ncmd.redirect);
8224 calcsize(n->ncmd.args);
8225 calcsize(n->ncmd.assign);
8228 sizenodelist(n->npipe.cmdlist);
8233 calcsize(n->nredir.redirect);
8234 calcsize(n->nredir.n);
8241 calcsize(n->nbinary.ch2);
8242 calcsize(n->nbinary.ch1);
8245 calcsize(n->nif.elsepart);
8246 calcsize(n->nif.ifpart);
8247 calcsize(n->nif.test);
8250 funcstringsize += strlen(n->nfor.var) + 1;
8251 calcsize(n->nfor.body);
8252 calcsize(n->nfor.args);
8255 calcsize(n->ncase.cases);
8256 calcsize(n->ncase.expr);
8259 calcsize(n->nclist.body);
8260 calcsize(n->nclist.pattern);
8261 calcsize(n->nclist.next);
8265 sizenodelist(n->narg.backquote);
8266 funcstringsize += strlen(n->narg.text) + 1;
8267 calcsize(n->narg.next);
8270 #if ENABLE_ASH_BASH_COMPAT
8277 calcsize(n->nfile.fname);
8278 calcsize(n->nfile.next);
8282 calcsize(n->ndup.vname);
8283 calcsize(n->ndup.next);
8287 calcsize(n->nhere.doc);
8288 calcsize(n->nhere.next);
8291 calcsize(n->nnot.com);
8297 nodeckstrdup(char *s)
8299 char *rtn = funcstring;
8301 strcpy(funcstring, s);
8302 funcstring += strlen(s) + 1;
8306 static union node *copynode(union node *);
8308 static struct nodelist *
8309 copynodelist(struct nodelist *lp)
8311 struct nodelist *start;
8312 struct nodelist **lpp;
8317 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8318 (*lpp)->n = copynode(lp->n);
8320 lpp = &(*lpp)->next;
8327 copynode(union node *n)
8334 funcblock = (char *) funcblock + nodesize[n->type];
8338 new->ncmd.redirect = copynode(n->ncmd.redirect);
8339 new->ncmd.args = copynode(n->ncmd.args);
8340 new->ncmd.assign = copynode(n->ncmd.assign);
8343 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8344 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8349 new->nredir.redirect = copynode(n->nredir.redirect);
8350 new->nredir.n = copynode(n->nredir.n);
8357 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8358 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8361 new->nif.elsepart = copynode(n->nif.elsepart);
8362 new->nif.ifpart = copynode(n->nif.ifpart);
8363 new->nif.test = copynode(n->nif.test);
8366 new->nfor.var = nodeckstrdup(n->nfor.var);
8367 new->nfor.body = copynode(n->nfor.body);
8368 new->nfor.args = copynode(n->nfor.args);
8371 new->ncase.cases = copynode(n->ncase.cases);
8372 new->ncase.expr = copynode(n->ncase.expr);
8375 new->nclist.body = copynode(n->nclist.body);
8376 new->nclist.pattern = copynode(n->nclist.pattern);
8377 new->nclist.next = copynode(n->nclist.next);
8381 new->narg.backquote = copynodelist(n->narg.backquote);
8382 new->narg.text = nodeckstrdup(n->narg.text);
8383 new->narg.next = copynode(n->narg.next);
8386 #if ENABLE_ASH_BASH_COMPAT
8393 new->nfile.fname = copynode(n->nfile.fname);
8394 new->nfile.fd = n->nfile.fd;
8395 new->nfile.next = copynode(n->nfile.next);
8399 new->ndup.vname = copynode(n->ndup.vname);
8400 new->ndup.dupfd = n->ndup.dupfd;
8401 new->ndup.fd = n->ndup.fd;
8402 new->ndup.next = copynode(n->ndup.next);
8406 new->nhere.doc = copynode(n->nhere.doc);
8407 new->nhere.fd = n->nhere.fd;
8408 new->nhere.next = copynode(n->nhere.next);
8411 new->nnot.com = copynode(n->nnot.com);
8414 new->type = n->type;
8419 * Make a copy of a parse tree.
8421 static struct funcnode *
8422 copyfunc(union node *n)
8427 funcblocksize = offsetof(struct funcnode, n);
8430 blocksize = funcblocksize;
8431 f = ckmalloc(blocksize + funcstringsize);
8432 funcblock = (char *) f + offsetof(struct funcnode, n);
8433 funcstring = (char *) f + blocksize;
8440 * Define a shell function.
8443 defun(char *name, union node *func)
8445 struct cmdentry entry;
8448 entry.cmdtype = CMDFUNCTION;
8449 entry.u.func = copyfunc(func);
8450 addcmdentry(name, &entry);
8454 /* Reasons for skipping commands (see comment on breakcmd routine) */
8455 #define SKIPBREAK (1 << 0)
8456 #define SKIPCONT (1 << 1)
8457 #define SKIPFUNC (1 << 2)
8458 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8459 static int skipcount; /* number of levels to skip */
8460 static int funcnest; /* depth of function calls */
8461 static int loopnest; /* current loop nesting level */
8463 /* Forward decl way out to parsing code - dotrap needs it */
8464 static int evalstring(char *s, int flags);
8466 /* Called to execute a trap.
8467 * Single callsite - at the end of evaltree().
8468 * If we return non-zero, evaltree raises EXEXIT exception.
8470 * Perhaps we should avoid entering new trap handlers
8471 * while we are executing a trap handler. [is it a TODO?]
8478 uint8_t last_status;
8483 last_status = exitstatus;
8487 TRACE(("dotrap entered\n"));
8488 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8500 /* non-trapped SIGINT is handled separately by raise_interrupt,
8501 * don't upset it by resetting gotsig[SIGINT-1] */
8502 if (sig == SIGINT && !p)
8505 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8511 exitstatus = last_status;
8512 TRACE(("dotrap returns\n"));
8515 /* forward declarations - evaluation is fairly recursive business... */
8516 static int evalloop(union node *, int);
8517 static int evalfor(union node *, int);
8518 static int evalcase(union node *, int);
8519 static int evalsubshell(union node *, int);
8520 static void expredir(union node *);
8521 static int evalpipe(union node *, int);
8522 static int evalcommand(union node *, int);
8523 static int evalbltin(const struct builtincmd *, int, char **, int);
8524 static void prehash(union node *);
8527 * Evaluate a parse tree. The value is left in the global variable
8531 evaltree(union node *n, int flags)
8533 struct jmploc *volatile savehandler = exception_handler;
8534 struct jmploc jmploc;
8536 int (*evalfn)(union node *, int);
8540 SAVE_INT(int_level);
8543 TRACE(("evaltree(NULL) called\n"));
8546 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8550 exception_handler = &jmploc;
8552 int err = setjmp(jmploc.loc);
8554 /* if it was a signal, check for trap handlers */
8555 if (exception_type == EXSIG) {
8556 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8557 exception_type, err));
8560 /* continue on the way out */
8561 TRACE(("exception %d in evaltree, propagating err=%d\n",
8562 exception_type, err));
8563 exception_handler = savehandler;
8564 longjmp(exception_handler->loc, err);
8571 out1fmt("Node type = %d\n", n->type);
8576 status = !evaltree(n->nnot.com, EV_TESTED);
8579 expredir(n->nredir.redirect);
8580 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8582 status = evaltree(n->nredir.n, flags & EV_TESTED);
8584 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8587 evalfn = evalcommand;
8589 if (eflag && !(flags & EV_TESTED))
8600 evalfn = evalsubshell;
8603 evalfn = evalsubshell;
8616 #error NAND + 1 != NOR
8618 #if NOR + 1 != NSEMI
8619 #error NOR + 1 != NSEMI
8621 unsigned is_or = n->type - NAND;
8624 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8626 if ((!status) == is_or || evalskip)
8632 status = evalfn(n, flags);
8636 status = evaltree(n->nif.test, EV_TESTED);
8643 if (n->nif.elsepart) {
8644 n = n->nif.elsepart;
8650 defun(n->narg.text, n->narg.next);
8651 /* Not necessary. To test it:
8652 * "false; f() { qwerty; }; echo $?" should print 0.
8656 exitstatus = status;
8661 exception_handler = savehandler;
8664 /* Order of checks below is important:
8665 * signal handlers trigger before exit caused by "set -e".
8669 if (checkexit & status)
8670 raise_exception(EXEXIT);
8671 if (flags & EV_EXIT)
8672 raise_exception(EXEXIT);
8674 RESTORE_INT(int_level);
8675 TRACE(("leaving evaltree (no interrupts)\n"));
8680 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8683 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8688 int skip = evalskip;
8695 if (--skipcount <= 0) {
8706 evalloop(union node *n, int flags)
8717 i = evaltree(n->nbinary.ch1, EV_TESTED);
8719 if (skip == SKIPFUNC)
8723 if (n->type != NWHILE)
8727 status = evaltree(n->nbinary.ch2, flags);
8729 } while (!(skip & ~SKIPCONT));
8736 evalfor(union node *n, int flags)
8738 struct arglist arglist;
8741 struct stackmark smark;
8744 setstackmark(&smark);
8745 arglist.list = NULL;
8746 arglist.lastp = &arglist.list;
8747 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8748 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8750 *arglist.lastp = NULL;
8754 for (sp = arglist.list; sp; sp = sp->next) {
8755 setvar0(n->nfor.var, sp->text);
8756 status = evaltree(n->nfor.body, flags);
8757 if (skiploop() & ~SKIPCONT)
8761 popstackmark(&smark);
8767 evalcase(union node *n, int flags)
8771 struct arglist arglist;
8772 struct stackmark smark;
8775 setstackmark(&smark);
8776 arglist.list = NULL;
8777 arglist.lastp = &arglist.list;
8778 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8779 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8780 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8781 if (casematch(patp, arglist.list->text)) {
8782 /* Ensure body is non-empty as otherwise
8783 * EV_EXIT may prevent us from setting the
8786 if (evalskip == 0 && cp->nclist.body) {
8787 status = evaltree(cp->nclist.body, flags);
8794 popstackmark(&smark);
8800 * Kick off a subshell to evaluate a tree.
8803 evalsubshell(union node *n, int flags)
8806 int backgnd = (n->type == NBACKGND);
8809 expredir(n->nredir.redirect);
8810 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8813 jp = makejob(/*n,*/ 1);
8814 if (forkshell(jp, n, backgnd) == 0) {
8819 flags &= ~EV_TESTED;
8821 redirect(n->nredir.redirect, 0);
8822 evaltreenr(n->nredir.n, flags);
8827 status = waitforjob(jp);
8833 * Compute the names of the files in a redirection list.
8835 static void fixredir(union node *, const char *, int);
8837 expredir(union node *n)
8841 for (redir = n; redir; redir = redir->nfile.next) {
8845 fn.lastp = &fn.list;
8846 switch (redir->type) {
8850 #if ENABLE_ASH_BASH_COMPAT
8855 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8856 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8857 #if ENABLE_ASH_BASH_COMPAT
8861 // By the design of stack allocator, the loop of this kind:
8862 // while true; do while true; do break; done </dev/null; done
8863 // will look like a memory leak: ash plans to free expfname's
8864 // of "/dev/null" as soon as it finishes running the loop
8865 // (in this case, never).
8866 // This "fix" is wrong:
8867 if (redir->nfile.expfname)
8868 stunalloc(redir->nfile.expfname);
8869 // It results in corrupted state of stacked allocations.
8871 redir->nfile.expfname = fn.list->text;
8874 case NTOFD: /* >& */
8875 if (redir->ndup.vname) {
8876 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8877 if (fn.list == NULL)
8878 ash_msg_and_raise_error("redir error");
8879 #if ENABLE_ASH_BASH_COMPAT
8880 //FIXME: we used expandarg with different args!
8881 if (!isdigit_str9(fn.list->text)) {
8882 /* >&file, not >&fd */
8883 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8884 ash_msg_and_raise_error("redir error");
8886 goto store_expfname;
8889 fixredir(redir, fn.list->text, 1);
8897 * Evaluate a pipeline. All the processes in the pipeline are children
8898 * of the process creating the pipeline. (This differs from some versions
8899 * of the shell, which make the last process in a pipeline the parent
8903 evalpipe(union node *n, int flags)
8906 struct nodelist *lp;
8912 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8914 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8918 jp = makejob(/*n,*/ pipelen);
8920 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8924 if (pipe(pip) < 0) {
8926 ash_msg_and_raise_error("pipe call failed");
8929 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8942 evaltreenr(lp->n, flags);
8948 /* Don't want to trigger debugging */
8952 if (n->npipe.pipe_backgnd == 0) {
8953 status = waitforjob(jp);
8954 TRACE(("evalpipe: job done exit status %d\n", status));
8962 * Controls whether the shell is interactive or not.
8965 setinteractive(int on)
8967 static smallint is_interactive;
8969 if (++on == is_interactive)
8971 is_interactive = on;
8975 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8976 if (is_interactive > 1) {
8977 /* Looks like they want an interactive shell */
8978 static smallint did_banner;
8981 /* note: ash and hush share this string */
8982 out1fmt("\n\n%s %s\n"
8983 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8986 "built-in shell (ash)"
9000 setinteractive(iflag);
9002 #if ENABLE_FEATURE_EDITING_VI
9004 line_input_state->flags |= VI_MODE;
9006 line_input_state->flags &= ~VI_MODE;
9008 viflag = 0; /* forcibly keep the option off */
9012 static struct localvar *localvars;
9015 * Called after a function returns.
9016 * Interrupts must be off.
9021 struct localvar *lvp;
9024 while ((lvp = localvars) != NULL) {
9025 localvars = lvp->next;
9027 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9028 if (vp == NULL) { /* $- saved */
9029 memcpy(optlist, lvp->text, sizeof(optlist));
9030 free((char*)lvp->text);
9032 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9033 unsetvar(vp->var_text);
9036 vp->var_func(var_end(lvp->text));
9037 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9038 free((char*)vp->var_text);
9039 vp->flags = lvp->flags;
9040 vp->var_text = lvp->text;
9047 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9049 volatile struct shparam saveparam;
9050 struct localvar *volatile savelocalvars;
9051 struct jmploc *volatile savehandler;
9052 struct jmploc jmploc;
9055 saveparam = shellparam;
9056 savelocalvars = localvars;
9057 savehandler = exception_handler;
9058 e = setjmp(jmploc.loc);
9063 exception_handler = &jmploc;
9065 shellparam.malloced = 0;
9069 shellparam.nparam = argc - 1;
9070 shellparam.p = argv + 1;
9071 #if ENABLE_ASH_GETOPTS
9072 shellparam.optind = 1;
9073 shellparam.optoff = -1;
9075 evaltree(&func->n, flags & EV_TESTED);
9081 localvars = savelocalvars;
9082 freeparam(&shellparam);
9083 shellparam = saveparam;
9084 exception_handler = savehandler;
9086 evalskip &= ~SKIPFUNC;
9091 * Make a variable a local variable. When a variable is made local, it's
9092 * value and flags are saved in a localvar structure. The saved values
9093 * will be restored when the shell function returns. We handle the name
9094 * "-" as a special case: it makes changes to "set +-options" local
9095 * (options will be restored on return from the function).
9100 struct localvar *lvp;
9103 char *eq = strchr(name, '=');
9106 /* Cater for duplicate "local". Examples:
9107 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9108 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9112 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9116 * it's a duplicate "local VAR" declaration, do nothing
9123 lvp = ckzalloc(sizeof(*lvp));
9124 if (LONE_DASH(name)) {
9126 p = ckmalloc(sizeof(optlist));
9127 lvp->text = memcpy(p, optlist, sizeof(optlist));
9130 vpp = hashvar(name);
9131 vp = *findvar(vpp, name);
9133 /* variable did not exist yet */
9135 setvareq(name, VSTRFIXED);
9137 setvar(name, NULL, VSTRFIXED);
9138 vp = *vpp; /* the new variable */
9139 lvp->flags = VUNSET;
9141 lvp->text = vp->var_text;
9142 lvp->flags = vp->flags;
9143 /* make sure neither "struct var" nor string gets freed
9144 * during (un)setting:
9146 vp->flags |= VSTRFIXED|VTEXTFIXED;
9150 /* "local VAR" unsets VAR: */
9151 setvar0(name, NULL);
9155 lvp->next = localvars;
9161 * The "local" command.
9163 static int FAST_FUNC
9164 localcmd(int argc UNUSED_PARAM, char **argv)
9169 ash_msg_and_raise_error("not in a function");
9172 while ((name = *argv++) != NULL) {
9178 static int FAST_FUNC
9179 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9184 static int FAST_FUNC
9185 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9190 static int FAST_FUNC
9191 execcmd(int argc UNUSED_PARAM, char **argv)
9194 iflag = 0; /* exit on error */
9197 /* We should set up signals for "exec CMD"
9198 * the same way as for "CMD" without "exec".
9199 * But optschanged->setinteractive->setsignal
9200 * still thought we are a root shell. Therefore, for example,
9201 * SIGQUIT is still set to IGN. Fix it:
9205 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9206 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9207 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9209 shellexec(argv + 1, pathval(), 0);
9216 * The return command.
9218 static int FAST_FUNC
9219 returncmd(int argc UNUSED_PARAM, char **argv)
9222 * If called outside a function, do what ksh does;
9223 * skip the rest of the file.
9225 evalskip = SKIPFUNC;
9226 return argv[1] ? number(argv[1]) : exitstatus;
9229 /* Forward declarations for builtintab[] */
9230 static int breakcmd(int, char **) FAST_FUNC;
9231 static int dotcmd(int, char **) FAST_FUNC;
9232 static int evalcmd(int, char **, int) FAST_FUNC;
9233 static int exitcmd(int, char **) FAST_FUNC;
9234 static int exportcmd(int, char **) FAST_FUNC;
9235 #if ENABLE_ASH_GETOPTS
9236 static int getoptscmd(int, char **) FAST_FUNC;
9239 static int helpcmd(int, char **) FAST_FUNC;
9242 static int historycmd(int, char **) FAST_FUNC;
9244 #if ENABLE_SH_MATH_SUPPORT
9245 static int letcmd(int, char **) FAST_FUNC;
9247 static int readcmd(int, char **) FAST_FUNC;
9248 static int setcmd(int, char **) FAST_FUNC;
9249 static int shiftcmd(int, char **) FAST_FUNC;
9250 static int timescmd(int, char **) FAST_FUNC;
9251 static int trapcmd(int, char **) FAST_FUNC;
9252 static int umaskcmd(int, char **) FAST_FUNC;
9253 static int unsetcmd(int, char **) FAST_FUNC;
9254 static int ulimitcmd(int, char **) FAST_FUNC;
9256 #define BUILTIN_NOSPEC "0"
9257 #define BUILTIN_SPECIAL "1"
9258 #define BUILTIN_REGULAR "2"
9259 #define BUILTIN_SPEC_REG "3"
9260 #define BUILTIN_ASSIGN "4"
9261 #define BUILTIN_SPEC_ASSG "5"
9262 #define BUILTIN_REG_ASSG "6"
9263 #define BUILTIN_SPEC_REG_ASSG "7"
9265 /* Stubs for calling non-FAST_FUNC's */
9266 #if ENABLE_ASH_BUILTIN_ECHO
9267 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9269 #if ENABLE_ASH_BUILTIN_PRINTF
9270 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9272 #if ENABLE_ASH_BUILTIN_TEST
9273 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9276 /* Keep these in proper order since it is searched via bsearch() */
9277 static const struct builtincmd builtintab[] = {
9278 { BUILTIN_SPEC_REG "." , dotcmd },
9279 { BUILTIN_SPEC_REG ":" , truecmd },
9280 #if ENABLE_ASH_BUILTIN_TEST
9281 { BUILTIN_REGULAR "[" , testcmd },
9282 #if ENABLE_ASH_BASH_COMPAT
9283 { BUILTIN_REGULAR "[[" , testcmd },
9286 #if ENABLE_ASH_ALIAS
9287 { BUILTIN_REG_ASSG "alias" , aliascmd },
9290 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9292 { BUILTIN_SPEC_REG "break" , breakcmd },
9293 { BUILTIN_REGULAR "cd" , cdcmd },
9294 { BUILTIN_NOSPEC "chdir" , cdcmd },
9295 #if ENABLE_ASH_CMDCMD
9296 { BUILTIN_REGULAR "command" , commandcmd },
9298 { BUILTIN_SPEC_REG "continue", breakcmd },
9299 #if ENABLE_ASH_BUILTIN_ECHO
9300 { BUILTIN_REGULAR "echo" , echocmd },
9302 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9303 { BUILTIN_SPEC_REG "exec" , execcmd },
9304 { BUILTIN_SPEC_REG "exit" , exitcmd },
9305 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9306 { BUILTIN_REGULAR "false" , falsecmd },
9308 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9310 #if ENABLE_ASH_GETOPTS
9311 { BUILTIN_REGULAR "getopts" , getoptscmd },
9313 { BUILTIN_NOSPEC "hash" , hashcmd },
9315 { BUILTIN_NOSPEC "help" , helpcmd },
9318 { BUILTIN_NOSPEC "history" , historycmd },
9321 { BUILTIN_REGULAR "jobs" , jobscmd },
9322 { BUILTIN_REGULAR "kill" , killcmd },
9324 #if ENABLE_SH_MATH_SUPPORT
9325 { BUILTIN_NOSPEC "let" , letcmd },
9327 { BUILTIN_ASSIGN "local" , localcmd },
9328 #if ENABLE_ASH_BUILTIN_PRINTF
9329 { BUILTIN_REGULAR "printf" , printfcmd },
9331 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9332 { BUILTIN_REGULAR "read" , readcmd },
9333 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9334 { BUILTIN_SPEC_REG "return" , returncmd },
9335 { BUILTIN_SPEC_REG "set" , setcmd },
9336 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9337 #if ENABLE_ASH_BASH_COMPAT
9338 { BUILTIN_SPEC_REG "source" , dotcmd },
9340 #if ENABLE_ASH_BUILTIN_TEST
9341 { BUILTIN_REGULAR "test" , testcmd },
9343 { BUILTIN_SPEC_REG "times" , timescmd },
9344 { BUILTIN_SPEC_REG "trap" , trapcmd },
9345 { BUILTIN_REGULAR "true" , truecmd },
9346 { BUILTIN_NOSPEC "type" , typecmd },
9347 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9348 { BUILTIN_REGULAR "umask" , umaskcmd },
9349 #if ENABLE_ASH_ALIAS
9350 { BUILTIN_REGULAR "unalias" , unaliascmd },
9352 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9353 { BUILTIN_REGULAR "wait" , waitcmd },
9356 /* Should match the above table! */
9357 #define COMMANDCMD (builtintab + \
9359 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9360 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9361 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9362 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9363 /* break cd cddir */ 3)
9364 #define EVALCMD (COMMANDCMD + \
9365 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9366 /* continue */ 1 + \
9367 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9369 #define EXECCMD (EVALCMD + \
9373 * Search the table of builtin commands.
9376 pstrcmp1(const void *a, const void *b)
9378 return strcmp((char*)a, *(char**)b + 1);
9380 static struct builtincmd *
9381 find_builtin(const char *name)
9383 struct builtincmd *bp;
9386 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9393 * Execute a simple command.
9396 isassignment(const char *p)
9398 const char *q = endofname(p);
9403 static int FAST_FUNC
9404 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9406 /* Preserve exitstatus of a previous possible redirection
9407 * as POSIX mandates */
9408 return back_exitstatus;
9411 evalcommand(union node *cmd, int flags)
9413 static const struct builtincmd null_bltin = {
9414 "\0\0", bltincmd /* why three NULs? */
9416 struct stackmark smark;
9418 struct arglist arglist;
9419 struct arglist varlist;
9422 const struct strlist *sp;
9423 struct cmdentry cmdentry;
9430 struct builtincmd *bcmd;
9431 smallint cmd_is_exec;
9432 smallint pseudovarflag = 0;
9434 /* First expand the arguments. */
9435 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9436 setstackmark(&smark);
9437 back_exitstatus = 0;
9439 cmdentry.cmdtype = CMDBUILTIN;
9440 cmdentry.u.cmd = &null_bltin;
9441 varlist.lastp = &varlist.list;
9442 *varlist.lastp = NULL;
9443 arglist.lastp = &arglist.list;
9444 *arglist.lastp = NULL;
9447 if (cmd->ncmd.args) {
9448 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9449 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9452 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9453 struct strlist **spp;
9455 spp = arglist.lastp;
9456 if (pseudovarflag && isassignment(argp->narg.text))
9457 expandarg(argp, &arglist, EXP_VARTILDE);
9459 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9461 for (sp = *spp; sp; sp = sp->next)
9465 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9466 for (sp = arglist.list; sp; sp = sp->next) {
9467 TRACE(("evalcommand arg: %s\n", sp->text));
9468 *nargv++ = sp->text;
9473 if (iflag && funcnest == 0 && argc > 0)
9474 lastarg = nargv[-1];
9477 expredir(cmd->ncmd.redirect);
9478 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9480 path = vpath.var_text;
9481 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9482 struct strlist **spp;
9485 spp = varlist.lastp;
9486 expandarg(argp, &varlist, EXP_VARTILDE);
9489 * Modify the command lookup path, if a PATH= assignment
9493 if (varcmp(p, path) == 0)
9497 /* Print the command if xflag is set. */
9500 const char *p = " %s" + 1;
9502 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9504 for (n = 0; n < 2; n++) {
9506 fdprintf(preverrout_fd, p, sp->text);
9512 safe_write(preverrout_fd, "\n", 1);
9518 /* Now locate the command. */
9520 int cmd_flag = DO_ERR;
9521 #if ENABLE_ASH_CMDCMD
9522 const char *oldpath = path + 5;
9526 find_command(argv[0], &cmdentry, cmd_flag, path);
9527 if (cmdentry.cmdtype == CMDUNKNOWN) {
9528 flush_stdout_stderr();
9533 /* implement bltin and command here */
9534 if (cmdentry.cmdtype != CMDBUILTIN)
9537 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9538 if (cmdentry.u.cmd == EXECCMD)
9540 #if ENABLE_ASH_CMDCMD
9541 if (cmdentry.u.cmd == COMMANDCMD) {
9543 nargv = parse_command_args(argv, &path);
9546 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9547 * nargv => "PROG". path is updated if -p.
9549 argc -= nargv - argv;
9551 cmd_flag |= DO_NOFUNC;
9559 /* We have a redirection error. */
9561 raise_exception(EXERROR);
9563 exitstatus = status;
9567 /* Execute the command. */
9568 switch (cmdentry.cmdtype) {
9571 #if ENABLE_FEATURE_SH_NOFORK
9572 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9573 * around run_nofork_applet() call.
9574 * (2) Should this check also be done in forkshell()?
9575 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9577 /* find_command() encodes applet_no as (-2 - applet_no) */
9578 int applet_no = (- cmdentry.u.index - 2);
9579 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9580 listsetvar(varlist.list, VEXPORT|VSTACK);
9581 /* run <applet>_main() */
9582 exitstatus = run_nofork_applet(applet_no, argv);
9586 /* Can we avoid forking off? For example, very last command
9587 * in a script or a subshell does not need forking,
9588 * we can just exec it.
9590 if (!(flags & EV_EXIT) || may_have_traps) {
9591 /* No, forking off a child is necessary */
9593 jp = makejob(/*cmd,*/ 1);
9594 if (forkshell(jp, cmd, FORK_FG) != 0) {
9596 status = waitforjob(jp);
9598 TRACE(("forked child exited with %d\n", status));
9603 /* fall through to exec'ing external program */
9605 listsetvar(varlist.list, VEXPORT|VSTACK);
9606 shellexec(argv, path, cmdentry.u.index);
9610 cmdenviron = varlist.list;
9612 struct strlist *list = cmdenviron;
9614 if (spclbltin > 0 || argc == 0) {
9616 if (cmd_is_exec && argc > 1)
9619 listsetvar(list, i);
9621 /* Tight loop with builtins only:
9622 * "while kill -0 $child; do true; done"
9623 * will never exit even if $child died, unless we do this
9624 * to reap the zombie and make kill detect that it's gone: */
9625 dowait(DOWAIT_NONBLOCK, NULL);
9627 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9629 int i = exception_type;
9630 if (i == EXEXIT || i == EXEXEC)
9634 exit_status = 128 + SIGINT;
9636 exit_status = 128 + pending_sig;
9637 exitstatus = exit_status;
9638 if (i == EXINT || spclbltin > 0) {
9640 longjmp(exception_handler->loc, 1);
9647 listsetvar(varlist.list, 0);
9648 /* See above for the rationale */
9649 dowait(DOWAIT_NONBLOCK, NULL);
9650 if (evalfun(cmdentry.u.func, argc, argv, flags))
9653 status = exitstatus;
9658 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9660 /* dsl: I think this is intended to be used to support
9661 * '_' in 'vi' command mode during line editing...
9662 * However I implemented that within libedit itself.
9664 setvar0("_", lastarg);
9666 popstackmark(&smark);
9672 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9674 char *volatile savecmdname;
9675 struct jmploc *volatile savehandler;
9676 struct jmploc jmploc;
9680 savecmdname = commandname;
9681 savehandler = exception_handler;
9682 i = setjmp(jmploc.loc);
9685 exception_handler = &jmploc;
9686 commandname = argv[0];
9688 optptr = NULL; /* initialize nextopt */
9690 status = evalcmd(argc, argv, flags);
9692 status = (*cmd->builtin)(argc, argv);
9693 flush_stdout_stderr();
9694 status |= ferror(stdout);
9695 exitstatus = status;
9698 commandname = savecmdname;
9699 exception_handler = savehandler;
9705 goodname(const char *p)
9707 return endofname(p)[0] == '\0';
9712 * Search for a command. This is called before we fork so that the
9713 * location of the command will be available in the parent as well as
9714 * the child. The check for "goodname" is an overly conservative
9715 * check that the name will not be subject to expansion.
9718 prehash(union node *n)
9720 struct cmdentry entry;
9722 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9723 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9727 /* ============ Builtin commands
9729 * Builtin commands whose functions are closely tied to evaluation
9730 * are implemented here.
9734 * Handle break and continue commands. Break, continue, and return are
9735 * all handled by setting the evalskip flag. The evaluation routines
9736 * above all check this flag, and if it is set they start skipping
9737 * commands rather than executing them. The variable skipcount is
9738 * the number of loops to break/continue, or the number of function
9739 * levels to return. (The latter is always 1.) It should probably
9740 * be an error to break out of more loops than exist, but it isn't
9741 * in the standard shell so we don't make it one here.
9743 static int FAST_FUNC
9744 breakcmd(int argc UNUSED_PARAM, char **argv)
9746 int n = argv[1] ? number(argv[1]) : 1;
9749 ash_msg_and_raise_error(msg_illnum, argv[1]);
9753 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9760 /* ============ input.c
9762 * This implements the input routines used by the parser.
9766 INPUT_PUSH_FILE = 1,
9767 INPUT_NOFILE_OK = 2,
9770 static smallint checkkwd;
9771 /* values of checkkwd variable */
9772 #define CHKALIAS 0x1
9777 * Push a string back onto the input at this current parsefile level.
9778 * We handle aliases this way.
9780 #if !ENABLE_ASH_ALIAS
9781 #define pushstring(s, ap) pushstring(s)
9784 pushstring(char *s, struct alias *ap)
9791 if (g_parsefile->strpush) {
9792 sp = ckzalloc(sizeof(*sp));
9793 sp->prev = g_parsefile->strpush;
9795 sp = &(g_parsefile->basestrpush);
9797 g_parsefile->strpush = sp;
9798 sp->prev_string = g_parsefile->next_to_pgetc;
9799 sp->prev_left_in_line = g_parsefile->left_in_line;
9800 sp->unget = g_parsefile->unget;
9801 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9802 #if ENABLE_ASH_ALIAS
9805 ap->flag |= ALIASINUSE;
9809 g_parsefile->next_to_pgetc = s;
9810 g_parsefile->left_in_line = len;
9811 g_parsefile->unget = 0;
9818 struct strpush *sp = g_parsefile->strpush;
9821 #if ENABLE_ASH_ALIAS
9823 if (g_parsefile->next_to_pgetc[-1] == ' '
9824 || g_parsefile->next_to_pgetc[-1] == '\t'
9826 checkkwd |= CHKALIAS;
9828 if (sp->string != sp->ap->val) {
9831 sp->ap->flag &= ~ALIASINUSE;
9832 if (sp->ap->flag & ALIASDEAD) {
9833 unalias(sp->ap->name);
9837 g_parsefile->next_to_pgetc = sp->prev_string;
9838 g_parsefile->left_in_line = sp->prev_left_in_line;
9839 g_parsefile->unget = sp->unget;
9840 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9841 g_parsefile->strpush = sp->prev;
9842 if (sp != &(g_parsefile->basestrpush))
9851 char *buf = g_parsefile->buf;
9853 g_parsefile->next_to_pgetc = buf;
9854 #if ENABLE_FEATURE_EDITING
9856 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9857 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9860 # if ENABLE_ASH_IDLE_TIMEOUT
9862 const char *tmout_var = lookupvar("TMOUT");
9864 timeout = atoi(tmout_var) * 1000;
9870 # if ENABLE_FEATURE_TAB_COMPLETION
9871 line_input_state->path_lookup = pathval();
9873 reinit_unicode_for_ash();
9874 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9876 /* Ctrl+C pressed */
9887 /* Ctrl+D pressed */
9890 # if ENABLE_ASH_IDLE_TIMEOUT
9891 else if (errno == EAGAIN && timeout > 0) {
9892 puts("\007timed out waiting for input: auto-logout");
9899 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9902 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9904 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9905 int flags = fcntl(0, F_GETFL);
9906 if (flags >= 0 && (flags & O_NONBLOCK)) {
9907 flags &= ~O_NONBLOCK;
9908 if (fcntl(0, F_SETFL, flags) >= 0) {
9909 out2str("sh: turning off NDELAY mode\n");
9920 * Refill the input buffer and return the next input character:
9922 * 1) If a string was pushed back on the input, pop it;
9923 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9924 * or we are reading from a string so we can't refill the buffer,
9926 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9927 * 4) Process input up to the next newline, deleting nul characters.
9929 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9930 #define pgetc_debug(...) ((void)0)
9931 static int pgetc(void);
9938 if (g_parsefile->strpush) {
9939 #if ENABLE_ASH_ALIAS
9940 if (g_parsefile->left_in_line == -1
9941 && g_parsefile->strpush->ap
9942 && g_parsefile->next_to_pgetc[-1] != ' '
9943 && g_parsefile->next_to_pgetc[-1] != '\t'
9945 pgetc_debug("preadbuffer PEOA");
9952 /* on both branches above g_parsefile->left_in_line < 0.
9953 * "pgetc" needs refilling.
9956 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9957 * pungetc() may increment it a few times.
9958 * Assuming it won't increment it to less than -90.
9960 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9961 pgetc_debug("preadbuffer PEOF1");
9962 /* even in failure keep left_in_line and next_to_pgetc
9963 * in lock step, for correct multi-layer pungetc.
9964 * left_in_line was decremented before preadbuffer(),
9965 * must inc next_to_pgetc: */
9966 g_parsefile->next_to_pgetc++;
9970 more = g_parsefile->left_in_buffer;
9972 flush_stdout_stderr();
9976 /* don't try reading again */
9977 g_parsefile->left_in_line = -99;
9978 pgetc_debug("preadbuffer PEOF2");
9979 g_parsefile->next_to_pgetc++;
9984 /* Find out where's the end of line.
9985 * Set g_parsefile->left_in_line
9986 * and g_parsefile->left_in_buffer acordingly.
9987 * NUL chars are deleted.
9989 q = g_parsefile->next_to_pgetc;
9997 memmove(q, q + 1, more);
10001 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10007 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10008 if (g_parsefile->left_in_line < 0)
10013 g_parsefile->left_in_buffer = more;
10018 out2str(g_parsefile->next_to_pgetc);
10022 pgetc_debug("preadbuffer at %d:%p'%s'",
10023 g_parsefile->left_in_line,
10024 g_parsefile->next_to_pgetc,
10025 g_parsefile->next_to_pgetc);
10026 return (unsigned char)*g_parsefile->next_to_pgetc++;
10032 g_parsefile->linno++;
10033 setprompt_if(doprompt, 2);
10038 g_parsefile->linno++;
10039 needprompt = doprompt;
10047 pgetc_debug("pgetc at %d:%p'%s'",
10048 g_parsefile->left_in_line,
10049 g_parsefile->next_to_pgetc,
10050 g_parsefile->next_to_pgetc);
10051 if (g_parsefile->unget)
10052 return g_parsefile->lastc[--g_parsefile->unget];
10054 if (--g_parsefile->left_in_line >= 0)
10055 c = (signed char)*g_parsefile->next_to_pgetc++;
10059 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10060 g_parsefile->lastc[0] = c;
10065 #if ENABLE_ASH_ALIAS
10067 pgetc_without_PEOA(void)
10071 pgetc_debug("pgetc at %d:%p'%s'",
10072 g_parsefile->left_in_line,
10073 g_parsefile->next_to_pgetc,
10074 g_parsefile->next_to_pgetc);
10076 } while (c == PEOA);
10080 # define pgetc_without_PEOA() pgetc()
10084 * Read a line from the script.
10087 pfgets(char *line, int len)
10093 while (--nleft > 0) {
10094 c = pgetc_without_PEOA();
10109 * Undo a call to pgetc. Only two characters may be pushed back.
10110 * PEOF may be pushed back.
10115 g_parsefile->unget++;
10118 /* This one eats backslash+newline */
10124 while ((c = pgetc()) == '\\') {
10125 if (pgetc() != '\n') {
10137 * To handle the "." command, a stack of input files is used. Pushfile
10138 * adds a new entry to the stack and popfile restores the previous level.
10143 struct parsefile *pf;
10145 pf = ckzalloc(sizeof(*pf));
10146 pf->prev = g_parsefile;
10148 /*pf->strpush = NULL; - ckzalloc did it */
10149 /*pf->basestrpush.prev = NULL;*/
10157 struct parsefile *pf = g_parsefile;
10160 if (pf->pf_fd >= 0)
10163 while (pf->strpush)
10165 g_parsefile = pf->prev;
10171 * Return to top level.
10176 while (g_parsefile != &basepf)
10181 * Close the file(s) that the shell is reading commands from. Called
10182 * after a fork is done.
10188 if (g_parsefile->pf_fd > 0) {
10189 close(g_parsefile->pf_fd);
10190 g_parsefile->pf_fd = 0;
10195 * Like setinputfile, but takes an open file descriptor. Call this with
10199 setinputfd(int fd, int push)
10201 close_on_exec_on(fd);
10204 g_parsefile->buf = NULL;
10206 g_parsefile->pf_fd = fd;
10207 if (g_parsefile->buf == NULL)
10208 g_parsefile->buf = ckmalloc(IBUFSIZ);
10209 g_parsefile->left_in_buffer = 0;
10210 g_parsefile->left_in_line = 0;
10211 g_parsefile->linno = 1;
10215 * Set the input to take input from a file. If push is set, push the
10216 * old input onto the stack first.
10219 setinputfile(const char *fname, int flags)
10225 fd = open(fname, O_RDONLY);
10227 if (flags & INPUT_NOFILE_OK)
10229 ash_msg_and_raise_error("can't open '%s'", fname);
10232 fd2 = copyfd(fd, 10);
10235 ash_msg_and_raise_error("out of file descriptors");
10238 setinputfd(fd, flags & INPUT_PUSH_FILE);
10245 * Like setinputfile, but takes input from a string.
10248 setinputstring(char *string)
10252 g_parsefile->next_to_pgetc = string;
10253 g_parsefile->left_in_line = strlen(string);
10254 g_parsefile->buf = NULL;
10255 g_parsefile->linno = 1;
10260 /* ============ mail.c
10262 * Routines to check for mail.
10265 #if ENABLE_ASH_MAIL
10267 /* Hash of mtimes of mailboxes */
10268 static unsigned mailtime_hash;
10269 /* Set if MAIL or MAILPATH is changed. */
10270 static smallint mail_var_path_changed;
10273 * Print appropriate message(s) if mail has arrived.
10274 * If mail_var_path_changed is set,
10275 * then the value of MAIL has mail_var_path_changed,
10276 * so we just update the values.
10285 struct stackmark smark;
10288 setstackmark(&smark);
10289 mpath = mpathset() ? mpathval() : mailval();
10292 p = path_advance(&mpath, nullstr);
10297 for (q = p; *q; q++)
10303 q[-1] = '\0'; /* delete trailing '/' */
10304 if (stat(p, &statb) < 0) {
10307 /* Very simplistic "hash": just a sum of all mtimes */
10308 new_hash += (unsigned)statb.st_mtime;
10310 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10311 if (mailtime_hash != 0)
10312 out2str("you have mail\n");
10313 mailtime_hash = new_hash;
10315 mail_var_path_changed = 0;
10316 popstackmark(&smark);
10319 static void FAST_FUNC
10320 changemail(const char *val UNUSED_PARAM)
10322 mail_var_path_changed = 1;
10325 #endif /* ASH_MAIL */
10328 /* ============ ??? */
10331 * Set the shell parameters.
10334 setparam(char **argv)
10340 for (nparam = 0; argv[nparam]; nparam++)
10342 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10344 *ap++ = ckstrdup(*argv++);
10347 freeparam(&shellparam);
10348 shellparam.malloced = 1;
10349 shellparam.nparam = nparam;
10350 shellparam.p = newparam;
10351 #if ENABLE_ASH_GETOPTS
10352 shellparam.optind = 1;
10353 shellparam.optoff = -1;
10358 * Process shell options. The global variable argptr contains a pointer
10359 * to the argument list; we advance it past the options.
10361 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10362 * For a non-interactive shell, an error condition encountered
10363 * by a special built-in ... shall cause the shell to write a diagnostic message
10364 * to standard error and exit as shown in the following table:
10365 * Error Special Built-In
10367 * Utility syntax error (option or operand error) Shall exit
10369 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10370 * we see that bash does not do that (set "finishes" with error code 1 instead,
10371 * and shell continues), and people rely on this behavior!
10373 * set -o barfoo 2>/dev/null
10376 * Oh well. Let's mimic that.
10379 plus_minus_o(char *name, int val)
10384 for (i = 0; i < NOPTS; i++) {
10385 if (strcmp(name, optnames(i)) == 0) {
10390 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10393 for (i = 0; i < NOPTS; i++) {
10395 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10397 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10403 setoption(int flag, int val)
10407 for (i = 0; i < NOPTS; i++) {
10408 if (optletters(i) == flag) {
10413 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10417 options(int cmdline)
10425 while ((p = *argptr) != NULL) {
10427 if (c != '-' && c != '+')
10430 val = 0; /* val = 0 if c == '+' */
10433 if (p[0] == '\0' || LONE_DASH(p)) {
10435 /* "-" means turn off -x and -v */
10438 /* "--" means reset params */
10439 else if (*argptr == NULL)
10442 break; /* "-" or "--" terminates options */
10445 /* first char was + or - */
10446 while ((c = *p++) != '\0') {
10447 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10448 if (c == 'c' && cmdline) {
10449 minusc = p; /* command is after shell args */
10450 } else if (c == 'o') {
10451 if (plus_minus_o(*argptr, val)) {
10452 /* it already printed err message */
10453 return 1; /* error */
10457 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10459 /* bash does not accept +-login, we also won't */
10460 } else if (cmdline && val && (c == '-')) { /* long options */
10461 if (strcmp(p, "login") == 0)
10473 * The shift builtin command.
10475 static int FAST_FUNC
10476 shiftcmd(int argc UNUSED_PARAM, char **argv)
10483 n = number(argv[1]);
10484 if (n > shellparam.nparam)
10485 n = 0; /* bash compat, was = shellparam.nparam; */
10487 shellparam.nparam -= n;
10488 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10489 if (shellparam.malloced)
10492 ap2 = shellparam.p;
10493 while ((*ap2++ = *ap1++) != NULL)
10495 #if ENABLE_ASH_GETOPTS
10496 shellparam.optind = 1;
10497 shellparam.optoff = -1;
10504 * POSIX requires that 'set' (but not export or readonly) output the
10505 * variables in lexicographic order - by the locale's collating order (sigh).
10506 * Maybe we could keep them in an ordered balanced binary tree
10507 * instead of hashed lists.
10508 * For now just roll 'em through qsort for printing...
10511 showvars(const char *sep_prefix, int on, int off)
10514 char **ep, **epend;
10516 ep = listvars(on, off, &epend);
10517 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10519 sep = *sep_prefix ? " " : sep_prefix;
10521 for (; ep < epend; ep++) {
10525 p = strchrnul(*ep, '=');
10528 q = single_quote(++p);
10529 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10535 * The set command builtin.
10537 static int FAST_FUNC
10538 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10543 return showvars(nullstr, 0, VUNSET);
10546 retval = options(/*cmdline:*/ 0);
10547 if (retval == 0) { /* if no parse error... */
10549 if (*argptr != NULL) {
10557 #if ENABLE_ASH_RANDOM_SUPPORT
10558 static void FAST_FUNC
10559 change_random(const char *value)
10563 if (value == NULL) {
10564 /* "get", generate */
10565 t = next_random(&random_gen);
10566 /* set without recursion */
10567 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10568 vrandom.flags &= ~VNOFUNC;
10571 t = strtoul(value, NULL, 10);
10572 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10577 #if ENABLE_ASH_GETOPTS
10579 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10590 if (*param_optind < 1)
10592 optnext = optfirst + *param_optind - 1;
10594 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10597 p = optnext[-1] + *optoff;
10598 if (p == NULL || *p == '\0') {
10599 /* Current word is done, advance */
10601 if (p == NULL || *p != '-' || *++p == '\0') {
10608 if (LONE_DASH(p)) /* check for "--" */
10613 for (q = optstr; *q != c;) {
10615 if (optstr[0] == ':') {
10617 /*sbuf[1] = '\0'; - already is */
10618 err |= setvarsafe("OPTARG", sbuf, 0);
10620 fprintf(stderr, "Illegal option -%c\n", c);
10621 unsetvar("OPTARG");
10631 if (*p == '\0' && (p = *optnext) == NULL) {
10632 if (optstr[0] == ':') {
10634 /*sbuf[1] = '\0'; - already is */
10635 err |= setvarsafe("OPTARG", sbuf, 0);
10638 fprintf(stderr, "No arg for -%c option\n", c);
10639 unsetvar("OPTARG");
10647 err |= setvarsafe("OPTARG", p, 0);
10650 err |= setvarsafe("OPTARG", nullstr, 0);
10652 *optoff = p ? p - *(optnext - 1) : -1;
10653 *param_optind = optnext - optfirst + 1;
10654 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10656 /*sbuf[1] = '\0'; - already is */
10657 err |= setvarsafe(optvar, sbuf, 0);
10661 flush_stdout_stderr();
10662 raise_exception(EXERROR);
10668 * The getopts builtin. Shellparam.optnext points to the next argument
10669 * to be processed. Shellparam.optptr points to the next character to
10670 * be processed in the current argument. If shellparam.optnext is NULL,
10671 * then it's the first time getopts has been called.
10673 static int FAST_FUNC
10674 getoptscmd(int argc, char **argv)
10679 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10681 optbase = shellparam.p;
10682 if (shellparam.optind > shellparam.nparam + 1) {
10683 shellparam.optind = 1;
10684 shellparam.optoff = -1;
10687 optbase = &argv[3];
10688 if (shellparam.optind > argc - 2) {
10689 shellparam.optind = 1;
10690 shellparam.optoff = -1;
10694 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10695 &shellparam.optoff);
10697 #endif /* ASH_GETOPTS */
10700 /* ============ Shell parser */
10703 struct heredoc *next; /* next here document in list */
10704 union node *here; /* redirection node */
10705 char *eofmark; /* string indicating end of input */
10706 smallint striptabs; /* if set, strip leading tabs */
10709 static smallint tokpushback; /* last token pushed back */
10710 static smallint quoteflag; /* set if (part of) last token was quoted */
10711 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10712 static struct heredoc *heredoclist; /* list of here documents to read */
10713 static char *wordtext; /* text of last word returned by readtoken */
10714 static struct nodelist *backquotelist;
10715 static union node *redirnode;
10716 static struct heredoc *heredoc;
10718 static const char *
10719 tokname(char *buf, int tok)
10722 return tokname_array[tok];
10723 sprintf(buf, "\"%s\"", tokname_array[tok]);
10727 /* raise_error_unexpected_syntax:
10728 * Called when an unexpected token is read during the parse. The argument
10729 * is the token that is expected, or -1 if more than one type of token can
10730 * occur at this point.
10732 static void raise_error_unexpected_syntax(int) NORETURN;
10734 raise_error_unexpected_syntax(int token)
10740 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10742 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10743 raise_error_syntax(msg);
10747 #define EOFMARKLEN 79
10749 /* parsing is heavily cross-recursive, need these forward decls */
10750 static union node *andor(void);
10751 static union node *pipeline(void);
10752 static union node *parse_command(void);
10753 static void parseheredoc(void);
10754 static int peektoken(void);
10755 static int readtoken(void);
10757 static union node *
10760 union node *n1, *n2, *n3;
10765 switch (peektoken()) {
10773 if (!n1 && (nlflag & 1))
10779 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10780 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10786 if (tok == TBACKGND) {
10787 if (n2->type == NPIPE) {
10788 n2->npipe.pipe_backgnd = 1;
10790 if (n2->type != NREDIR) {
10791 n3 = stzalloc(sizeof(struct nredir));
10793 /*n3->nredir.redirect = NULL; - stzalloc did it */
10796 n2->type = NBACKGND;
10802 n3 = stzalloc(sizeof(struct nbinary));
10804 n3->nbinary.ch1 = n1;
10805 n3->nbinary.ch2 = n2;
10818 raise_error_unexpected_syntax(-1);
10825 static union node *
10828 union node *n1, *n2, *n3;
10836 } else if (t == TOR) {
10842 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10844 n3 = stzalloc(sizeof(struct nbinary));
10846 n3->nbinary.ch1 = n1;
10847 n3->nbinary.ch2 = n2;
10852 static union node *
10855 union node *n1, *n2, *pipenode;
10856 struct nodelist *lp, *prev;
10860 TRACE(("pipeline: entered\n"));
10861 if (readtoken() == TNOT) {
10863 checkkwd = CHKKWD | CHKALIAS;
10866 n1 = parse_command();
10867 if (readtoken() == TPIPE) {
10868 pipenode = stzalloc(sizeof(struct npipe));
10869 pipenode->type = NPIPE;
10870 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10871 lp = stzalloc(sizeof(struct nodelist));
10872 pipenode->npipe.cmdlist = lp;
10876 lp = stzalloc(sizeof(struct nodelist));
10877 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10878 lp->n = parse_command();
10880 } while (readtoken() == TPIPE);
10886 n2 = stzalloc(sizeof(struct nnot));
10894 static union node *
10899 n = stzalloc(sizeof(struct narg));
10901 /*n->narg.next = NULL; - stzalloc did it */
10902 n->narg.text = wordtext;
10903 n->narg.backquote = backquotelist;
10908 fixredir(union node *n, const char *text, int err)
10912 TRACE(("Fix redir %s %d\n", text, err));
10914 n->ndup.vname = NULL;
10916 fd = bb_strtou(text, NULL, 10);
10917 if (!errno && fd >= 0)
10918 n->ndup.dupfd = fd;
10919 else if (LONE_DASH(text))
10920 n->ndup.dupfd = -1;
10923 raise_error_syntax("bad fd number");
10924 n->ndup.vname = makename();
10929 * Returns true if the text contains nothing to expand (no dollar signs
10933 noexpand(const char *text)
10937 while ((c = *text++) != '\0') {
10938 if (c == CTLQUOTEMARK)
10942 else if (SIT(c, BASESYNTAX) == CCTL)
10951 union node *n = redirnode;
10953 if (readtoken() != TWORD)
10954 raise_error_unexpected_syntax(-1);
10955 if (n->type == NHERE) {
10956 struct heredoc *here = heredoc;
10960 if (quoteflag == 0)
10962 TRACE(("Here document %d\n", n->type));
10963 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10964 raise_error_syntax("illegal eof marker for << redirection");
10965 rmescapes(wordtext, 0);
10966 here->eofmark = wordtext;
10968 if (heredoclist == NULL)
10969 heredoclist = here;
10971 for (p = heredoclist; p->next; p = p->next)
10975 } else if (n->type == NTOFD || n->type == NFROMFD) {
10976 fixredir(n, wordtext, 0);
10978 n->nfile.fname = makename();
10982 static union node *
10985 union node *args, **app;
10986 union node *n = NULL;
10987 union node *vars, **vpp;
10988 union node **rpp, *redir;
10990 #if ENABLE_ASH_BASH_COMPAT
10991 smallint double_brackets_flag = 0;
10992 smallint function_flag = 0;
11002 savecheckkwd = CHKALIAS;
11005 checkkwd = savecheckkwd;
11008 #if ENABLE_ASH_BASH_COMPAT
11010 if (peektoken() != TWORD)
11011 raise_error_unexpected_syntax(TWORD);
11014 case TAND: /* "&&" */
11015 case TOR: /* "||" */
11016 if (!double_brackets_flag) {
11020 wordtext = (char *) (t == TAND ? "-a" : "-o");
11023 n = stzalloc(sizeof(struct narg));
11025 /*n->narg.next = NULL; - stzalloc did it */
11026 n->narg.text = wordtext;
11027 #if ENABLE_ASH_BASH_COMPAT
11028 if (strcmp("[[", wordtext) == 0)
11029 double_brackets_flag = 1;
11030 else if (strcmp("]]", wordtext) == 0)
11031 double_brackets_flag = 0;
11033 n->narg.backquote = backquotelist;
11034 if (savecheckkwd && isassignment(wordtext)) {
11036 vpp = &n->narg.next;
11039 app = &n->narg.next;
11042 #if ENABLE_ASH_BASH_COMPAT
11043 if (function_flag) {
11044 checkkwd = CHKNL | CHKKWD;
11045 switch (peektoken()) {
11057 if (strcmp("[[", wordtext) == 0)
11061 raise_error_unexpected_syntax(-1);
11067 *rpp = n = redirnode;
11068 rpp = &n->nfile.next;
11069 parsefname(); /* read name of redirection file */
11072 IF_ASH_BASH_COMPAT(do_func:)
11073 if (args && app == &args->narg.next
11076 struct builtincmd *bcmd;
11079 /* We have a function */
11080 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11081 raise_error_unexpected_syntax(TRP);
11082 name = n->narg.text;
11083 if (!goodname(name)
11084 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11086 raise_error_syntax("bad function name");
11089 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11090 n->narg.next = parse_command();
11093 IF_ASH_BASH_COMPAT(function_flag = 0;)
11104 n = stzalloc(sizeof(struct ncmd));
11106 n->ncmd.args = args;
11107 n->ncmd.assign = vars;
11108 n->ncmd.redirect = redir;
11112 static union node *
11113 parse_command(void)
11115 union node *n1, *n2;
11116 union node *ap, **app;
11117 union node *cp, **cpp;
11118 union node *redir, **rpp;
11125 switch (readtoken()) {
11127 raise_error_unexpected_syntax(-1);
11130 n1 = stzalloc(sizeof(struct nif));
11132 n1->nif.test = list(0);
11133 if (readtoken() != TTHEN)
11134 raise_error_unexpected_syntax(TTHEN);
11135 n1->nif.ifpart = list(0);
11137 while (readtoken() == TELIF) {
11138 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11139 n2 = n2->nif.elsepart;
11141 n2->nif.test = list(0);
11142 if (readtoken() != TTHEN)
11143 raise_error_unexpected_syntax(TTHEN);
11144 n2->nif.ifpart = list(0);
11146 if (lasttoken == TELSE)
11147 n2->nif.elsepart = list(0);
11149 n2->nif.elsepart = NULL;
11157 n1 = stzalloc(sizeof(struct nbinary));
11158 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11159 n1->nbinary.ch1 = list(0);
11162 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11163 got == TWORD ? wordtext : ""));
11164 raise_error_unexpected_syntax(TDO);
11166 n1->nbinary.ch2 = list(0);
11171 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11172 raise_error_syntax("bad for loop variable");
11173 n1 = stzalloc(sizeof(struct nfor));
11175 n1->nfor.var = wordtext;
11176 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11177 if (readtoken() == TIN) {
11179 while (readtoken() == TWORD) {
11180 n2 = stzalloc(sizeof(struct narg));
11182 /*n2->narg.next = NULL; - stzalloc did it */
11183 n2->narg.text = wordtext;
11184 n2->narg.backquote = backquotelist;
11186 app = &n2->narg.next;
11189 n1->nfor.args = ap;
11190 if (lasttoken != TNL && lasttoken != TSEMI)
11191 raise_error_unexpected_syntax(-1);
11193 n2 = stzalloc(sizeof(struct narg));
11195 /*n2->narg.next = NULL; - stzalloc did it */
11196 n2->narg.text = (char *)dolatstr;
11197 /*n2->narg.backquote = NULL;*/
11198 n1->nfor.args = n2;
11200 * Newline or semicolon here is optional (but note
11201 * that the original Bourne shell only allowed NL).
11203 if (lasttoken != TSEMI)
11206 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11207 if (readtoken() != TDO)
11208 raise_error_unexpected_syntax(TDO);
11209 n1->nfor.body = list(0);
11213 n1 = stzalloc(sizeof(struct ncase));
11215 if (readtoken() != TWORD)
11216 raise_error_unexpected_syntax(TWORD);
11217 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11219 /*n2->narg.next = NULL; - stzalloc did it */
11220 n2->narg.text = wordtext;
11221 n2->narg.backquote = backquotelist;
11222 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11223 if (readtoken() != TIN)
11224 raise_error_unexpected_syntax(TIN);
11225 cpp = &n1->ncase.cases;
11227 checkkwd = CHKNL | CHKKWD;
11229 while (t != TESAC) {
11230 if (lasttoken == TLP)
11232 *cpp = cp = stzalloc(sizeof(struct nclist));
11234 app = &cp->nclist.pattern;
11236 *app = ap = stzalloc(sizeof(struct narg));
11238 /*ap->narg.next = NULL; - stzalloc did it */
11239 ap->narg.text = wordtext;
11240 ap->narg.backquote = backquotelist;
11241 if (readtoken() != TPIPE)
11243 app = &ap->narg.next;
11246 //ap->narg.next = NULL;
11247 if (lasttoken != TRP)
11248 raise_error_unexpected_syntax(TRP);
11249 cp->nclist.body = list(2);
11251 cpp = &cp->nclist.next;
11253 checkkwd = CHKNL | CHKKWD;
11257 raise_error_unexpected_syntax(TENDCASE);
11264 n1 = stzalloc(sizeof(struct nredir));
11265 n1->type = NSUBSHELL;
11266 n1->nredir.n = list(0);
11267 /*n1->nredir.redirect = NULL; - stzalloc did it */
11274 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11278 return simplecmd();
11281 if (readtoken() != t)
11282 raise_error_unexpected_syntax(t);
11285 /* Now check for redirection which may follow command */
11286 checkkwd = CHKKWD | CHKALIAS;
11288 while (readtoken() == TREDIR) {
11289 *rpp = n2 = redirnode;
11290 rpp = &n2->nfile.next;
11296 if (n1->type != NSUBSHELL) {
11297 n2 = stzalloc(sizeof(struct nredir));
11302 n1->nredir.redirect = redir;
11307 #if ENABLE_ASH_BASH_COMPAT
11309 decode_dollar_squote(void)
11311 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11317 p = strchr(C_escapes, c);
11322 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11326 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11328 } else if (c == 'x') { /* \xHH */
11332 } while (isxdigit(c) && --cnt);
11334 if (cnt == 3) { /* \x but next char is "bad" */
11338 } else { /* simple seq like \\ or \t */
11343 c = bb_process_escape_sequence((void*)&p);
11344 } else { /* unrecognized "\z": print both chars unless ' or " */
11345 if (c != '\'' && c != '"') {
11347 c |= 0x100; /* "please encode \, then me" */
11355 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11356 * is not NULL, read a here document. In the latter case, eofmark is the
11357 * word which marks the end of the document and striptabs is true if
11358 * leading tabs should be stripped from the document. The argument c
11359 * is the first character of the input token or document.
11361 * Because C does not have internal subroutines, I have simulated them
11362 * using goto's to implement the subroutine linkage. The following macros
11363 * will run code that appears at the end of readtoken1.
11365 #define CHECKEND() {goto checkend; checkend_return:;}
11366 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11367 #define PARSESUB() {goto parsesub; parsesub_return:;}
11368 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11369 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11370 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11372 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11374 /* NB: syntax parameter fits into smallint */
11375 /* c parameter is an unsigned char or PEOF or PEOA */
11378 char line[EOFMARKLEN + 1];
11379 struct nodelist *bqlist;
11383 smallint prevsyntax; /* syntax before arithmetic */
11384 #if ENABLE_ASH_EXPAND_PRMT
11385 smallint pssyntax; /* we are expanding a prompt string */
11387 int varnest; /* levels of variables expansion */
11388 int arinest; /* levels of arithmetic expansion */
11389 int parenlevel; /* levels of parens in arithmetic */
11390 int dqvarnest; /* levels of variables expansion within double quotes */
11392 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11394 startlinno = g_parsefile->linno;
11398 #if ENABLE_ASH_EXPAND_PRMT
11399 pssyntax = (syntax == PSSYNTAX);
11403 dblquote = (syntax == DQSYNTAX);
11409 STARTSTACKSTR(out);
11411 /* For each line, until end of word */
11412 CHECKEND(); /* set c to PEOF if at end of here document */
11413 for (;;) { /* until end of line or end of word */
11414 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11415 switch (SIT(c, syntax)) {
11416 case CNL: /* '\n' */
11417 if (syntax == BASESYNTAX)
11418 goto endword; /* exit outer loop */
11422 goto loop; /* continue outer loop */
11427 #if ENABLE_ASH_BASH_COMPAT
11428 if (c == '\\' && bash_dollar_squote) {
11429 c = decode_dollar_squote();
11431 /* skip $'\000', $'\x00' (like bash) */
11435 /* Unknown escape. Encode as '\z' */
11436 c = (unsigned char)c;
11437 if (eofmark == NULL || dblquote)
11438 USTPUTC(CTLESC, out);
11439 USTPUTC('\\', out);
11443 if (eofmark == NULL || dblquote)
11444 USTPUTC(CTLESC, out);
11447 case CBACK: /* backslash */
11448 c = pgetc_without_PEOA();
11450 USTPUTC(CTLESC, out);
11451 USTPUTC('\\', out);
11453 } else if (c == '\n') {
11456 #if ENABLE_ASH_EXPAND_PRMT
11457 if (c == '$' && pssyntax) {
11458 USTPUTC(CTLESC, out);
11459 USTPUTC('\\', out);
11462 /* Backslash is retained if we are in "str" and next char isn't special */
11467 && (c != '"' || eofmark != NULL)
11469 USTPUTC('\\', out);
11471 USTPUTC(CTLESC, out);
11479 if (eofmark == NULL) {
11480 USTPUTC(CTLQUOTEMARK, out);
11488 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11489 if (eofmark != NULL && varnest == 0) {
11492 if (dqvarnest == 0) {
11493 syntax = BASESYNTAX;
11500 case CVAR: /* '$' */
11501 PARSESUB(); /* parse substitution */
11503 case CENDVAR: /* '}' */
11506 if (dqvarnest > 0) {
11513 #if ENABLE_SH_MATH_SUPPORT
11514 case CLP: /* '(' in arithmetic */
11518 case CRP: /* ')' in arithmetic */
11519 if (parenlevel > 0) {
11522 if (pgetc_eatbnl() == ')') {
11524 if (--arinest == 0) {
11525 syntax = prevsyntax;
11529 * unbalanced parens
11530 * (don't 2nd guess - no error)
11538 case CBQUOTE: /* '`' */
11542 goto endword; /* exit outer loop */
11546 if (varnest == 0) {
11547 #if ENABLE_ASH_BASH_COMPAT
11549 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11550 if (pgetc() == '>')
11551 c = 0x100 + '>'; /* flag &> */
11555 goto endword; /* exit outer loop */
11557 IF_ASH_ALIAS(if (c != PEOA))
11564 #if ENABLE_SH_MATH_SUPPORT
11565 if (syntax == ARISYNTAX)
11566 raise_error_syntax("missing '))'");
11568 if (syntax != BASESYNTAX && eofmark == NULL)
11569 raise_error_syntax("unterminated quoted string");
11570 if (varnest != 0) {
11571 startlinno = g_parsefile->linno;
11573 raise_error_syntax("missing '}'");
11575 USTPUTC('\0', out);
11576 len = out - (char *)stackblock();
11577 out = stackblock();
11578 if (eofmark == NULL) {
11579 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11582 if (isdigit_str9(out)) {
11583 PARSEREDIR(); /* passed as params: out, c */
11584 lasttoken = TREDIR;
11587 /* else: non-number X seen, interpret it
11588 * as "NNNX>file" = "NNNX >file" */
11592 quoteflag = quotef;
11593 backquotelist = bqlist;
11594 grabstackblock(len);
11598 /* end of readtoken routine */
11601 * Check to see whether we are at the end of the here document. When this
11602 * is called, c is set to the first character of the next input line. If
11603 * we are at the end of the here document, this routine sets the c to PEOF.
11607 #if ENABLE_ASH_ALIAS
11609 c = pgetc_without_PEOA();
11612 while (c == '\t') {
11613 c = pgetc_without_PEOA();
11616 if (c == *eofmark) {
11617 if (pfgets(line, sizeof(line)) != NULL) {
11621 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11623 if (*p == '\n' && *q == '\0') {
11627 pushstring(line, NULL);
11632 goto checkend_return;
11636 * Parse a redirection operator. The variable "out" points to a string
11637 * specifying the fd to be redirected. The variable "c" contains the
11638 * first character of the redirection operator.
11641 /* out is already checked to be a valid number or "" */
11642 int fd = (*out == '\0' ? -1 : atoi(out));
11645 np = stzalloc(sizeof(struct nfile));
11650 np->type = NAPPEND;
11652 np->type = NCLOBBER;
11655 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11661 #if ENABLE_ASH_BASH_COMPAT
11662 else if (c == 0x100 + '>') { /* this flags &> redirection */
11664 pgetc(); /* this is '>', no need to check */
11668 else { /* c == '<' */
11669 /*np->nfile.fd = 0; - stzalloc did it */
11673 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11674 np = stzalloc(sizeof(struct nhere));
11675 /*np->nfile.fd = 0; - stzalloc did it */
11678 heredoc = stzalloc(sizeof(struct heredoc));
11679 heredoc->here = np;
11682 heredoc->striptabs = 1;
11684 /*heredoc->striptabs = 0; - stzalloc did it */
11690 np->type = NFROMFD;
11694 np->type = NFROMTO;
11706 goto parseredir_return;
11710 * Parse a substitution. At this point, we have read the dollar sign
11711 * and nothing else.
11714 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11715 * (assuming ascii char codes, as the original implementation did) */
11716 #define is_special(c) \
11717 (((unsigned)(c) - 33 < 32) \
11718 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11720 unsigned char subtype;
11724 c = pgetc_eatbnl();
11725 if (c > 255 /* PEOA or PEOF */
11726 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11728 #if ENABLE_ASH_BASH_COMPAT
11729 if (syntax != DQSYNTAX && c == '\'')
11730 bash_dollar_squote = 1;
11735 } else if (c == '(') {
11736 /* $(command) or $((arith)) */
11737 if (pgetc_eatbnl() == '(') {
11738 #if ENABLE_SH_MATH_SUPPORT
11741 raise_error_syntax("you disabled math support for $((arith)) syntax");
11748 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11749 USTPUTC(CTLVAR, out);
11750 typeloc = out - (char *)stackblock();
11751 USTPUTC(VSNORMAL, out);
11752 subtype = VSNORMAL;
11754 c = pgetc_eatbnl();
11756 c = pgetc_eatbnl();
11758 c = '#'; /* ${#} - same as $# */
11760 subtype = VSLENGTH; /* ${#VAR} */
11765 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11766 /* $[{[#]]NAME[}] */
11769 c = pgetc_eatbnl();
11770 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11771 } else if (isdigit(c)) {
11772 /* $[{[#]]NUM[}] */
11775 c = pgetc_eatbnl();
11776 } while (isdigit(c));
11777 } else if (is_special(c)) {
11778 /* $[{[#]]<specialchar>[}] */
11780 c = pgetc_eatbnl();
11783 raise_error_syntax("bad substitution");
11785 if (c != '}' && subtype == VSLENGTH) {
11786 /* ${#VAR didn't end with } */
11792 if (subtype == 0) {
11793 static const char types[] ALIGN1 = "}-+?=";
11794 /* ${VAR...} but not $VAR or ${#VAR} */
11795 /* c == first char after VAR */
11798 c = pgetc_eatbnl();
11799 #if ENABLE_ASH_BASH_COMPAT
11800 /* This check is only needed to not misinterpret
11801 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11804 if (!strchr(types, c)) {
11805 subtype = VSSUBSTR;
11807 break; /* "goto do_pungetc" is bigger (!) */
11813 const char *p = strchr(types, c);
11816 subtype = p - types + VSNORMAL;
11822 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11823 c = pgetc_eatbnl();
11829 #if ENABLE_ASH_BASH_COMPAT
11831 /* ${v/[/]pattern/repl} */
11832 //TODO: encode pattern and repl separately.
11833 // Currently ${v/$var_with_slash/repl} is horribly broken
11834 subtype = VSREPLACE;
11835 c = pgetc_eatbnl();
11838 subtype++; /* VSREPLACEALL */
11846 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11847 if (subtype != VSNORMAL) {
11854 goto parsesub_return;
11858 * Called to parse command substitutions. Newstyle is set if the command
11859 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11860 * list of commands (passed by reference), and savelen is the number of
11861 * characters on the top of the stack which must be preserved.
11864 struct nodelist **nlpp;
11868 smallint saveprompt = 0;
11871 savelen = out - (char *)stackblock();
11874 * FIXME: this can allocate very large block on stack and SEGV.
11876 * echo "..<100kbytes>..`true` $(true) `true` ..."
11877 * allocates 100kb for every command subst. With about
11878 * a hundred command substitutions stack overflows.
11879 * With larger prepended string, SEGV happens sooner.
11881 str = alloca(savelen);
11882 memcpy(str, stackblock(), savelen);
11886 /* We must read until the closing backquote, giving special
11887 * treatment to some slashes, and then push the string and
11888 * reread it as input, interpreting it normally.
11894 STARTSTACKSTR(pout);
11898 setprompt_if(needprompt, 2);
11909 * If eating a newline, avoid putting
11910 * the newline into the new character
11911 * stream (via the STPUTC after the
11916 if (pc != '\\' && pc != '`' && pc != '$'
11917 && (!dblquote || pc != '"')
11919 STPUTC('\\', pout);
11921 if (pc <= 255 /* not PEOA or PEOF */) {
11927 IF_ASH_ALIAS(case PEOA:)
11928 startlinno = g_parsefile->linno;
11929 raise_error_syntax("EOF in backquote substitution");
11941 STPUTC('\0', pout);
11942 psavelen = pout - (char *)stackblock();
11943 if (psavelen > 0) {
11944 pstr = grabstackstr(pout);
11945 setinputstring(pstr);
11950 nlpp = &(*nlpp)->next;
11951 *nlpp = stzalloc(sizeof(**nlpp));
11952 /* (*nlpp)->next = NULL; - stzalloc did it */
11955 saveprompt = doprompt;
11962 doprompt = saveprompt;
11963 else if (readtoken() != TRP)
11964 raise_error_unexpected_syntax(TRP);
11969 * Start reading from old file again, ignoring any pushed back
11970 * tokens left from the backquote parsing
11975 while (stackblocksize() <= savelen)
11977 STARTSTACKSTR(out);
11979 memcpy(out, str, savelen);
11980 STADJUST(savelen, out);
11982 USTPUTC(CTLBACKQ, out);
11984 goto parsebackq_oldreturn;
11985 goto parsebackq_newreturn;
11988 #if ENABLE_SH_MATH_SUPPORT
11990 * Parse an arithmetic expansion (indicate start of one and set state)
11993 if (++arinest == 1) {
11994 prevsyntax = syntax;
11995 syntax = ARISYNTAX;
11997 USTPUTC(CTLARI, out);
11998 goto parsearith_return;
12001 } /* end of readtoken */
12004 * Read the next input token.
12005 * If the token is a word, we set backquotelist to the list of cmds in
12006 * backquotes. We set quoteflag to true if any part of the word was
12008 * If the token is TREDIR, then we set redirnode to a structure containing
12010 * In all cases, the variable startlinno is set to the number of the line
12011 * on which the token starts.
12013 * [Change comment: here documents and internal procedures]
12014 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12015 * word parsing code into a separate routine. In this case, readtoken
12016 * doesn't need to have any internal procedures, but parseword does.
12017 * We could also make parseoperator in essence the main routine, and
12018 * have parseword (readtoken1?) handle both words and redirection.]
12020 #define NEW_xxreadtoken
12021 #ifdef NEW_xxreadtoken
12022 /* singles must be first! */
12023 static const char xxreadtoken_chars[7] ALIGN1 = {
12024 '\n', '(', ')', /* singles */
12025 '&', '|', ';', /* doubles */
12029 #define xxreadtoken_singles 3
12030 #define xxreadtoken_doubles 3
12032 static const char xxreadtoken_tokens[] ALIGN1 = {
12033 TNL, TLP, TRP, /* only single occurrence allowed */
12034 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12035 TEOF, /* corresponds to trailing nul */
12036 TAND, TOR, TENDCASE /* if double occurrence */
12048 setprompt_if(needprompt, 2);
12049 startlinno = g_parsefile->linno;
12050 for (;;) { /* until token or start of word found */
12052 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12056 while ((c = pgetc()) != '\n' && c != PEOF)
12059 } else if (c == '\\') {
12060 if (pgetc() != '\n') {
12062 break; /* return readtoken1(...) */
12068 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12074 p = strchr(xxreadtoken_chars, c);
12076 break; /* return readtoken1(...) */
12078 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12080 if (cc == c) { /* double occurrence? */
12081 p += xxreadtoken_doubles + 1;
12084 #if ENABLE_ASH_BASH_COMPAT
12085 if (c == '&' && cc == '>') /* &> */
12086 break; /* return readtoken1(...) */
12091 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12096 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12098 #else /* old xxreadtoken */
12099 #define RETURN(token) return lasttoken = token
12109 setprompt_if(needprompt, 2);
12110 startlinno = g_parsefile->linno;
12111 for (;;) { /* until token or start of word found */
12114 case ' ': case '\t':
12115 IF_ASH_ALIAS(case PEOA:)
12118 while ((c = pgetc()) != '\n' && c != PEOF)
12123 if (pgetc() == '\n') {
12135 if (pgetc() == '&')
12140 if (pgetc() == '|')
12145 if (pgetc() == ';')
12158 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12161 #endif /* old xxreadtoken */
12167 int kwd = checkkwd;
12169 smallint alreadyseen = tokpushback;
12172 #if ENABLE_ASH_ALIAS
12188 if (t != TWORD || quoteflag) {
12193 * check for keywords
12195 if (kwd & CHKKWD) {
12196 const char *const *pp;
12198 pp = findkwd(wordtext);
12200 lasttoken = t = pp - tokname_array;
12201 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12206 if (checkkwd & CHKALIAS) {
12207 #if ENABLE_ASH_ALIAS
12209 ap = lookupalias(wordtext, 1);
12212 pushstring(ap->val, ap);
12222 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12224 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12240 * Read and parse a command. Returns NODE_EOF on end of file.
12241 * (NULL is a valid parse tree indicating a blank line.)
12243 static union node *
12244 parsecmd(int interact)
12249 doprompt = interact;
12250 setprompt_if(doprompt, doprompt);
12256 * Input any here documents.
12261 struct heredoc *here;
12264 here = heredoclist;
12265 heredoclist = NULL;
12268 setprompt_if(needprompt, 2);
12269 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12270 here->eofmark, here->striptabs);
12271 n = stzalloc(sizeof(struct narg));
12272 n->narg.type = NARG;
12273 /*n->narg.next = NULL; - stzalloc did it */
12274 n->narg.text = wordtext;
12275 n->narg.backquote = backquotelist;
12276 here->here->nhere.doc = n;
12283 * called by editline -- any expansions to the prompt should be added here.
12285 #if ENABLE_ASH_EXPAND_PRMT
12286 static const char *
12287 expandstr(const char *ps)
12291 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12292 * and token processing _can_ alter it (delete NULs etc). */
12293 setinputstring((char *)ps);
12294 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12297 n.narg.type = NARG;
12298 n.narg.next = NULL;
12299 n.narg.text = wordtext;
12300 n.narg.backquote = backquotelist;
12302 expandarg(&n, NULL, EXP_QUOTED);
12303 return stackblock();
12308 * Execute a command or commands contained in a string.
12311 evalstring(char *s, int flags)
12314 struct stackmark smark;
12319 setstackmark(&smark);
12322 while ((n = parsecmd(0)) != NODE_EOF) {
12325 i = evaltree(n, flags);
12328 popstackmark(&smark);
12332 popstackmark(&smark);
12340 * The eval command.
12342 static int FAST_FUNC
12343 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12352 STARTSTACKSTR(concat);
12354 concat = stack_putstr(p, concat);
12358 STPUTC(' ', concat);
12360 STPUTC('\0', concat);
12361 p = grabstackstr(concat);
12363 return evalstring(p, flags & EV_TESTED);
12369 * Read and execute commands.
12370 * "Top" is nonzero for the top level command loop;
12371 * it turns on prompting if the shell is interactive.
12377 struct stackmark smark;
12382 TRACE(("cmdloop(%d) called\n", top));
12386 setstackmark(&smark);
12389 showjobs(SHOW_CHANGED|SHOW_STDERR);
12392 if (iflag && top) {
12396 n = parsecmd(inter);
12398 if (DEBUG > 2 && debug && (n != NODE_EOF))
12401 if (n == NODE_EOF) {
12402 if (!top || numeof >= 50)
12404 if (!stoppedjobs()) {
12407 out2str("\nUse \"exit\" to leave shell.\n");
12410 } else if (nflag == 0) {
12413 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12416 i = evaltree(n, 0);
12420 popstackmark(&smark);
12424 evalskip &= ~SKIPFUNC;
12432 * Take commands from a file. To be compatible we should do a path
12433 * search for the file, which is necessary to find sub-commands.
12436 find_dot_file(char *name)
12439 const char *path = pathval();
12442 /* don't try this for absolute or relative paths */
12443 if (strchr(name, '/'))
12446 /* IIRC standards do not say whether . is to be searched.
12447 * And it is even smaller this way, making it unconditional for now:
12449 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12454 while ((fullname = path_advance(&path, name)) != NULL) {
12456 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12458 * Don't bother freeing here, since it will
12459 * be freed by the caller.
12463 if (fullname != name)
12464 stunalloc(fullname);
12467 /* not found in the PATH */
12468 ash_msg_and_raise_error("%s: not found", name);
12472 static int FAST_FUNC
12473 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12475 /* "false; . empty_file; echo $?" should print 0, not 1: */
12479 struct strlist *sp;
12480 volatile struct shparam saveparam;
12482 for (sp = cmdenviron; sp; sp = sp->next)
12483 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12485 nextopt(nullstr); /* handle possible "--" */
12489 /* bash says: "bash: .: filename argument required" */
12490 return 2; /* bash compat */
12493 /* This aborts if file isn't found, which is POSIXly correct.
12494 * bash returns exitcode 1 instead.
12496 fullname = find_dot_file(argv[0]);
12498 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12500 saveparam = shellparam;
12501 shellparam.malloced = 0;
12505 shellparam.nparam = argc;
12506 shellparam.p = argv;
12509 /* This aborts if file can't be opened, which is POSIXly correct.
12510 * bash returns exitcode 1 instead.
12512 setinputfile(fullname, INPUT_PUSH_FILE);
12513 commandname = fullname;
12514 status = cmdloop(0);
12518 freeparam(&shellparam);
12519 shellparam = saveparam;
12525 static int FAST_FUNC
12526 exitcmd(int argc UNUSED_PARAM, char **argv)
12531 exitstatus = number(argv[1]);
12532 raise_exception(EXEXIT);
12537 * Read a file containing shell functions.
12540 readcmdfile(char *name)
12542 setinputfile(name, INPUT_PUSH_FILE);
12548 /* ============ find_command inplementation */
12551 * Resolve a command name. If you change this routine, you may have to
12552 * change the shellexec routine as well.
12555 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12557 struct tblentry *cmdp;
12564 struct builtincmd *bcmd;
12566 /* If name contains a slash, don't use PATH or hash table */
12567 if (strchr(name, '/') != NULL) {
12568 entry->u.index = -1;
12569 if (act & DO_ABS) {
12570 while (stat(name, &statb) < 0) {
12572 if (errno == EINTR)
12575 entry->cmdtype = CMDUNKNOWN;
12579 entry->cmdtype = CMDNORMAL;
12583 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12585 updatetbl = (path == pathval());
12588 if (strstr(path, "%builtin") != NULL)
12589 act |= DO_ALTBLTIN;
12592 /* If name is in the table, check answer will be ok */
12593 cmdp = cmdlookup(name, 0);
12594 if (cmdp != NULL) {
12597 switch (cmdp->cmdtype) {
12615 } else if (cmdp->rehash == 0)
12616 /* if not invalidated by cd, we're done */
12620 /* If %builtin not in path, check for builtin next */
12621 bcmd = find_builtin(name);
12623 if (IS_BUILTIN_REGULAR(bcmd))
12624 goto builtin_success;
12625 if (act & DO_ALTPATH) {
12626 if (!(act & DO_ALTBLTIN))
12627 goto builtin_success;
12628 } else if (builtinloc <= 0) {
12629 goto builtin_success;
12633 #if ENABLE_FEATURE_SH_STANDALONE
12635 int applet_no = find_applet_by_name(name);
12636 if (applet_no >= 0) {
12637 entry->cmdtype = CMDNORMAL;
12638 entry->u.index = -2 - applet_no;
12644 /* We have to search path. */
12645 prev = -1; /* where to start */
12646 if (cmdp && cmdp->rehash) { /* doing a rehash */
12647 if (cmdp->cmdtype == CMDBUILTIN)
12650 prev = cmdp->param.index;
12656 while ((fullname = path_advance(&path, name)) != NULL) {
12657 stunalloc(fullname);
12658 /* NB: code below will still use fullname
12659 * despite it being "unallocated" */
12662 if (prefix(pathopt, "builtin")) {
12664 goto builtin_success;
12667 if ((act & DO_NOFUNC)
12668 || !prefix(pathopt, "func")
12669 ) { /* ignore unimplemented options */
12673 /* if rehash, don't redo absolute path names */
12674 if (fullname[0] == '/' && idx <= prev) {
12677 TRACE(("searchexec \"%s\": no change\n", name));
12680 while (stat(fullname, &statb) < 0) {
12682 if (errno == EINTR)
12685 if (errno != ENOENT && errno != ENOTDIR)
12689 e = EACCES; /* if we fail, this will be the error */
12690 if (!S_ISREG(statb.st_mode))
12692 if (pathopt) { /* this is a %func directory */
12693 stalloc(strlen(fullname) + 1);
12694 /* NB: stalloc will return space pointed by fullname
12695 * (because we don't have any intervening allocations
12696 * between stunalloc above and this stalloc) */
12697 readcmdfile(fullname);
12698 cmdp = cmdlookup(name, 0);
12699 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12700 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12701 stunalloc(fullname);
12704 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12706 entry->cmdtype = CMDNORMAL;
12707 entry->u.index = idx;
12711 cmdp = cmdlookup(name, 1);
12712 cmdp->cmdtype = CMDNORMAL;
12713 cmdp->param.index = idx;
12718 /* We failed. If there was an entry for this command, delete it */
12719 if (cmdp && updatetbl)
12720 delete_cmd_entry();
12722 ash_msg("%s: %s", name, errmsg(e, "not found"));
12723 entry->cmdtype = CMDUNKNOWN;
12728 entry->cmdtype = CMDBUILTIN;
12729 entry->u.cmd = bcmd;
12733 cmdp = cmdlookup(name, 1);
12734 cmdp->cmdtype = CMDBUILTIN;
12735 cmdp->param.cmd = bcmd;
12739 entry->cmdtype = cmdp->cmdtype;
12740 entry->u = cmdp->param;
12745 * The trap builtin.
12747 static int FAST_FUNC
12748 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12752 int signo, exitcode;
12757 for (signo = 0; signo < NSIG; signo++) {
12758 char *tr = trap_ptr[signo];
12760 /* note: bash adds "SIG", but only if invoked
12761 * as "bash". If called as "sh", or if set -o posix,
12762 * then it prints short signal names.
12763 * We are printing short names: */
12764 out1fmt("trap -- %s %s\n",
12766 get_signame(signo));
12767 /* trap_ptr != trap only if we are in special-cased `trap` code.
12768 * In this case, we will exit very soon, no need to free(). */
12769 /* if (trap_ptr != trap && tp[0]) */
12774 if (trap_ptr != trap) {
12787 signo = get_signum(*ap);
12789 /* Mimic bash message exactly */
12790 ash_msg("%s: invalid signal specification", *ap);
12796 if (LONE_DASH(action))
12799 action = ckstrdup(action);
12803 may_have_traps = 1;
12804 trap[signo] = action;
12815 /* ============ Builtins */
12817 #if ENABLE_ASH_HELP
12818 static int FAST_FUNC
12819 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12825 "Built-in commands:\n"
12826 "------------------\n");
12827 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12828 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12829 builtintab[i].name + 1);
12835 # if ENABLE_FEATURE_SH_STANDALONE
12837 const char *a = applet_names;
12839 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12844 while (*a++ != '\0')
12849 newline_and_flush(stdout);
12850 return EXIT_SUCCESS;
12855 static int FAST_FUNC
12856 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12858 show_history(line_input_state);
12859 return EXIT_SUCCESS;
12864 * The export and readonly commands.
12866 static int FAST_FUNC
12867 exportcmd(int argc UNUSED_PARAM, char **argv)
12877 /* "readonly" in bash accepts, but ignores -n.
12878 * We do the same: it saves a conditional in nextopt's param.
12881 while ((opt = nextopt("np")) != '\0') {
12883 flag_off = VEXPORT;
12886 if (argv[0][0] == 'r') {
12888 flag_off = 0; /* readonly ignores -n */
12890 flag_off = ~flag_off;
12892 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12898 p = strchr(name, '=');
12902 vp = *findvar(hashvar(name), name);
12904 vp->flags = ((vp->flags | flag) & flag_off);
12908 setvar(name, p, (flag & flag_off));
12909 } while ((name = *++aptr) != NULL);
12914 /* No arguments. Show the list of exported or readonly vars.
12917 showvars(argv[0], flag, 0);
12922 * Delete a function if it exists.
12925 unsetfunc(const char *name)
12927 struct tblentry *cmdp;
12929 cmdp = cmdlookup(name, 0);
12930 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12931 delete_cmd_entry();
12935 * The unset builtin command. We unset the function before we unset the
12936 * variable to allow a function to be unset when there is a readonly variable
12937 * with the same name.
12939 static int FAST_FUNC
12940 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12947 while ((i = nextopt("vf")) != 0) {
12951 for (ap = argptr; *ap; ap++) {
12964 static const unsigned char timescmd_str[] ALIGN1 = {
12965 ' ', offsetof(struct tms, tms_utime),
12966 '\n', offsetof(struct tms, tms_stime),
12967 ' ', offsetof(struct tms, tms_cutime),
12968 '\n', offsetof(struct tms, tms_cstime),
12971 static int FAST_FUNC
12972 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12974 unsigned long clk_tck, s, t;
12975 const unsigned char *p;
12978 clk_tck = bb_clk_tck();
12983 t = *(clock_t *)(((char *) &buf) + p[1]);
12986 out1fmt("%lum%lu.%03lus%c",
12988 (t * 1000) / clk_tck,
12996 #if ENABLE_SH_MATH_SUPPORT
12998 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12999 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13001 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13003 static int FAST_FUNC
13004 letcmd(int argc UNUSED_PARAM, char **argv)
13010 ash_msg_and_raise_error("expression expected");
13012 i = ash_arith(*argv);
13020 * The read builtin. Options:
13021 * -r Do not interpret '\' specially
13022 * -s Turn off echo (tty only)
13023 * -n NCHARS Read NCHARS max
13024 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13025 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13026 * -u FD Read from given FD instead of fd 0
13027 * This uses unbuffered input, which may be avoidable in some cases.
13028 * TODO: bash also has:
13029 * -a ARRAY Read into array[0],[1],etc
13030 * -d DELIM End on DELIM char, not newline
13031 * -e Use line editing (tty only)
13033 static int FAST_FUNC
13034 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13036 char *opt_n = NULL;
13037 char *opt_p = NULL;
13038 char *opt_t = NULL;
13039 char *opt_u = NULL;
13040 int read_flags = 0;
13044 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13053 read_flags |= BUILTIN_READ_SILENT;
13059 read_flags |= BUILTIN_READ_RAW;
13069 /* "read -s" needs to save/restore termios, can't allow ^C
13070 * to jump out of it.
13073 r = shell_builtin_read(setvar0,
13075 bltinlookup("IFS"), /* can be NULL */
13084 if ((uintptr_t)r > 1)
13085 ash_msg_and_raise_error(r);
13087 return (uintptr_t)r;
13090 static int FAST_FUNC
13091 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13093 static const char permuser[3] ALIGN1 = "ogu";
13096 int symbolic_mode = 0;
13098 while (nextopt("S") != '\0') {
13107 if (*argptr == NULL) {
13108 if (symbolic_mode) {
13109 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13116 *p++ = permuser[i];
13118 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13119 if (!(mask & 0400)) *p++ = 'r';
13120 if (!(mask & 0200)) *p++ = 'w';
13121 if (!(mask & 0100)) *p++ = 'x';
13129 out1fmt("%04o\n", mask);
13132 char *modestr = *argptr;
13133 /* numeric umasks are taken as-is */
13134 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13135 if (!isdigit(modestr[0]))
13137 mask = bb_parse_mode(modestr, mask);
13138 if ((unsigned)mask > 0777) {
13139 ash_msg_and_raise_error("illegal mode: %s", modestr);
13141 if (!isdigit(modestr[0]))
13148 static int FAST_FUNC
13149 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13151 return shell_builtin_ulimit(argv);
13154 /* ============ main() and helpers */
13157 * Called to exit the shell.
13166 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13167 save_history(line_input_state);
13169 status = exitstatus;
13170 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13171 if (setjmp(loc.loc)) {
13172 if (exception_type == EXEXIT)
13173 status = exitstatus;
13176 exception_handler = &loc;
13182 /*free(p); - we'll exit soon */
13184 flush_stdout_stderr();
13186 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13187 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13197 /* we will never free this */
13198 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13200 signal(SIGCHLD, SIG_DFL);
13201 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13202 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13204 signal(SIGHUP, SIG_DFL);
13209 struct stat st1, st2;
13212 for (envp = environ; envp && *envp; envp++) {
13213 p = endofname(*envp);
13214 if (p != *envp && *p == '=') {
13215 setvareq(*envp, VEXPORT|VTEXTFIXED);
13219 setvareq((char*)defoptindvar, VTEXTFIXED);
13221 setvar0("PPID", utoa(getppid()));
13222 #if ENABLE_ASH_BASH_COMPAT
13223 p = lookupvar("SHLVL");
13224 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13225 if (!lookupvar("HOSTNAME")) {
13226 struct utsname uts;
13228 setvar0("HOSTNAME", uts.nodename);
13231 p = lookupvar("PWD");
13233 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13234 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13244 //usage:#define ash_trivial_usage
13245 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13246 //usage:#define ash_full_usage "\n\n"
13247 //usage: "Unix shell interpreter"
13249 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13250 //usage:# define sh_trivial_usage ash_trivial_usage
13251 //usage:# define sh_full_usage ash_full_usage
13253 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13254 //usage:# define bash_trivial_usage ash_trivial_usage
13255 //usage:# define bash_full_usage ash_full_usage
13259 * Process the shell command line arguments.
13262 procargs(char **argv)
13265 const char *xminusc;
13270 /* if (xargv[0]) - mmm, this is always true! */
13272 for (i = 0; i < NOPTS; i++)
13275 if (options(/*cmdline:*/ 1)) {
13276 /* it already printed err message */
13277 raise_exception(EXERROR);
13281 if (*xargv == NULL) {
13283 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13286 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13290 for (i = 0; i < NOPTS; i++)
13291 if (optlist[i] == 2)
13296 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13301 } else if (!sflag) {
13302 setinputfile(*xargv, 0);
13305 commandname = arg0;
13308 shellparam.p = xargv;
13309 #if ENABLE_ASH_GETOPTS
13310 shellparam.optind = 1;
13311 shellparam.optoff = -1;
13313 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13315 shellparam.nparam++;
13322 * Read /etc/profile or .profile.
13325 read_profile(const char *name)
13327 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13334 * This routine is called when an error or an interrupt occurs in an
13335 * interactive shell and control is returned to the main command loop.
13343 /* from input.c: */
13344 g_parsefile->left_in_buffer = 0;
13345 g_parsefile->left_in_line = 0; /* clear input buffer */
13347 /* from parser.c: */
13350 /* from redir.c: */
13351 clearredir(/*drop:*/ 0);
13355 static short profile_buf[16384];
13356 extern int etext();
13360 * Main routine. We initialize things, parse the arguments, execute
13361 * profiles if we're a login shell, and then call cmdloop to execute
13362 * commands. The setjmp call sets up the location to jump to when an
13363 * exception occurs. When an exception occurs the variable "state"
13364 * is used to figure out how far we had gotten.
13366 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13367 int ash_main(int argc UNUSED_PARAM, char **argv)
13369 const char *shinit;
13370 volatile smallint state;
13371 struct jmploc jmploc;
13372 struct stackmark smark;
13374 /* Initialize global data */
13378 #if ENABLE_ASH_ALIAS
13384 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13387 #if ENABLE_FEATURE_EDITING
13388 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13391 if (setjmp(jmploc.loc)) {
13397 e = exception_type;
13401 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13405 newline_and_flush(stderr);
13408 popstackmark(&smark);
13409 FORCE_INT_ON; /* enable interrupts */
13418 exception_handler = &jmploc;
13421 TRACE(("Shell args: "));
13422 trace_puts_args(argv);
13424 rootpid = getpid();
13427 setstackmark(&smark);
13430 if (argv[0] && argv[0][0] == '-')
13436 read_profile("/etc/profile");
13439 hp = lookupvar("HOME");
13441 hp = concat_path_file(hp, ".profile");
13450 getuid() == geteuid() && getgid() == getegid() &&
13454 shinit = lookupvar("ENV");
13455 if (shinit != NULL && *shinit != '\0') {
13456 read_profile(shinit);
13462 /* evalstring pushes parsefile stack.
13463 * Ensure we don't falsely claim that 0 (stdin)
13464 * is one of stacked source fds.
13465 * Testcase: ash -c 'exec 1>&0' must not complain. */
13466 // if (!sflag) g_parsefile->pf_fd = -1;
13467 // ^^ not necessary since now we special-case fd 0
13468 // in is_hidden_fd() to not be considered "hidden fd"
13469 evalstring(minusc, 0);
13472 if (sflag || minusc == NULL) {
13473 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13475 const char *hp = lookupvar("HISTFILE");
13477 hp = lookupvar("HOME");
13479 hp = concat_path_file(hp, ".ash_history");
13480 setvar0("HISTFILE", hp);
13482 hp = lookupvar("HISTFILE");
13486 line_input_state->hist_file = hp;
13487 # if ENABLE_FEATURE_SH_HISTFILESIZE
13488 hp = lookupvar("HISTFILESIZE");
13489 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13493 state4: /* XXX ??? - why isn't this before the "if" statement */
13501 extern void _mcleanup(void);
13505 TRACE(("End of main reached\n"));
13512 * Copyright (c) 1989, 1991, 1993, 1994
13513 * The Regents of the University of California. All rights reserved.
13515 * This code is derived from software contributed to Berkeley by
13516 * Kenneth Almquist.
13518 * Redistribution and use in source and binary forms, with or without
13519 * modification, are permitted provided that the following conditions
13521 * 1. Redistributions of source code must retain the above copyright
13522 * notice, this list of conditions and the following disclaimer.
13523 * 2. Redistributions in binary form must reproduce the above copyright
13524 * notice, this list of conditions and the following disclaimer in the
13525 * documentation and/or other materials provided with the distribution.
13526 * 3. Neither the name of the University nor the names of its contributors
13527 * may be used to endorse or promote products derived from this software
13528 * without specific prior written permission.
13530 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13531 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13532 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13533 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13534 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13535 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13536 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13537 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13538 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13539 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF