1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
53 #if !ENABLE_ASH_INTERNAL_GLOB
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
62 #if ENABLE_ASH_RANDOM_SUPPORT
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
68 #include "NUM_APPLETS.h"
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
85 # error "Do not even bother, ash will not run on NOMMU machine"
91 //config: depends on !NOMMU
93 //config: Tha 'ash' shell adds about 60k in the default configuration and is
94 //config: the most complete and most pedantically correct shell included with
95 //config: busybox. This shell is actually a derivative of the Debian 'dash'
96 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config: (written by Kenneth Almquist) from NetBSD.
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config: bool "Optimize for size instead of speed"
102 //config: depends on ASH
104 //config: Compile ash for reduced size at the price of speed.
106 //config:config ASH_INTERNAL_GLOB
107 //config: bool "Use internal glob() implementation"
109 //config: depends on ASH
111 //config: Do not use glob() function from libc, use internal implementation.
112 //config: Use this if you are getting "glob.h: No such file or directory"
113 //config: or similar build errors.
115 //config:config ASH_RANDOM_SUPPORT
116 //config: bool "Pseudorandom generator and $RANDOM variable"
118 //config: depends on ASH
120 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config: You can reset the generator by using a specified start value.
123 //config: After "unset RANDOM" the generator will switch off and this
124 //config: variable will no longer have special treatment.
126 //config:config ASH_EXPAND_PRMT
127 //config: bool "Expand prompt string"
129 //config: depends on ASH
131 //config: "PS#" may contain volatile content, such as backquote commands.
132 //config: This option recreates the prompt string from the environment
133 //config: variable each time it is displayed.
135 //config:config ASH_BASH_COMPAT
136 //config: bool "bash-compatible extensions"
138 //config: depends on ASH
140 //config: Enable bash-compatible extensions.
142 //config:config ASH_IDLE_TIMEOUT
143 //config: bool "Idle timeout variable"
145 //config: depends on ASH
147 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
149 //config:config ASH_JOB_CONTROL
150 //config: bool "Job control"
152 //config: depends on ASH
154 //config: Enable job control in the ash shell.
156 //config:config ASH_ALIAS
157 //config: bool "Alias support"
159 //config: depends on ASH
161 //config: Enable alias support in the ash shell.
163 //config:config ASH_GETOPTS
164 //config: bool "Builtin getopt to parse positional parameters"
166 //config: depends on ASH
168 //config: Enable support for getopts builtin in ash.
170 //config:config ASH_BUILTIN_ECHO
171 //config: bool "Builtin version of 'echo'"
173 //config: depends on ASH
175 //config: Enable support for echo builtin in ash.
177 //config:config ASH_BUILTIN_PRINTF
178 //config: bool "Builtin version of 'printf'"
180 //config: depends on ASH
182 //config: Enable support for printf builtin in ash.
184 //config:config ASH_BUILTIN_TEST
185 //config: bool "Builtin version of 'test'"
187 //config: depends on ASH
189 //config: Enable support for test builtin in ash.
191 //config:config ASH_HELP
192 //config: bool "help builtin"
194 //config: depends on ASH
196 //config: Enable help builtin in ash.
198 //config:config ASH_CMDCMD
199 //config: bool "'command' command to override shell builtins"
201 //config: depends on ASH
203 //config: Enable support for the ash 'command' builtin, which allows
204 //config: you to run the specified command with the specified arguments,
205 //config: even when there is an ash builtin command with the same name.
207 //config:config ASH_MAIL
208 //config: bool "Check for new mail on interactive shells"
210 //config: depends on ASH
212 //config: Enable "check for new mail" function in the ash shell.
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
223 /* ============ Hash table sizes. Configurable. */
227 #define CMDTABLESIZE 31 /* should be prime */
230 /* ============ Shell options */
232 static const char *const optletters_optnames[] = {
247 #if ENABLE_ASH_BASH_COMPAT
256 #define optletters(n) optletters_optnames[n][0]
257 #define optnames(n) (optletters_optnames[n] + 1)
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
262 /* ============ Misc data */
264 #define msg_illnum "Illegal number: %s"
267 * We enclose jmp_buf in a structure so that we can declare pointers to
268 * jump locations. The global variable handler contains the location to
269 * jump to when an exception occurs, and the global variable exception_type
270 * contains a code identifying the exception. To implement nested
271 * exception handlers, the user should save the value of handler on entry
272 * to an inner scope, set handler to point to a jmploc structure for the
273 * inner scope, and restore handler on exit from the scope.
279 struct globals_misc {
280 uint8_t exitstatus; /* exit status of last command */
281 uint8_t back_exitstatus;/* exit status of backquoted command */
282 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
283 int rootpid; /* pid of main shell */
284 /* shell level: 0 for the main shell, 1 for its children, and so on */
286 #define rootshell (!shlvl)
287 char *minusc; /* argument to -c option */
289 char *curdir; // = nullstr; /* current working directory */
290 char *physdir; // = nullstr; /* physical working directory */
292 char *arg0; /* value of $0 */
294 struct jmploc *exception_handler;
296 volatile int suppress_int; /* counter */
297 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
298 /* last pending signal */
299 volatile /*sig_atomic_t*/ smallint pending_sig;
300 smallint exception_type; /* kind of exception (0..5) */
302 #define EXINT 0 /* SIGINT received */
303 #define EXERROR 1 /* a generic error */
304 #define EXEXIT 4 /* exit the shell */
307 char nullstr[1]; /* zero length string */
310 #define eflag optlist[0]
311 #define fflag optlist[1]
312 #define Iflag optlist[2]
313 #define iflag optlist[3]
314 #define mflag optlist[4]
315 #define nflag optlist[5]
316 #define sflag optlist[6]
317 #define xflag optlist[7]
318 #define vflag optlist[8]
319 #define Cflag optlist[9]
320 #define aflag optlist[10]
321 #define bflag optlist[11]
322 #define uflag optlist[12]
323 #define viflag optlist[13]
324 #if ENABLE_ASH_BASH_COMPAT
325 # define pipefail optlist[14]
330 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
331 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
334 /* trap handler commands */
336 * Sigmode records the current value of the signal handlers for the various
337 * modes. A value of zero means that the current handler is not known.
338 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
340 char sigmode[NSIG - 1];
341 #define S_DFL 1 /* default signal handling (SIG_DFL) */
342 #define S_CATCH 2 /* signal is caught */
343 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
344 #define S_HARD_IGN 4 /* signal is ignored permanently */
346 /* indicates specified signal received */
347 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
348 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
350 char **trap_ptr; /* used only by "trap hack" */
352 /* Rarely referenced stuff */
353 #if ENABLE_ASH_RANDOM_SUPPORT
356 pid_t backgndpid; /* pid of last background process */
358 extern struct globals_misc *const ash_ptr_to_globals_misc;
359 #define G_misc (*ash_ptr_to_globals_misc)
360 #define exitstatus (G_misc.exitstatus )
361 #define back_exitstatus (G_misc.back_exitstatus )
362 #define job_warning (G_misc.job_warning)
363 #define rootpid (G_misc.rootpid )
364 #define shlvl (G_misc.shlvl )
365 #define minusc (G_misc.minusc )
366 #define curdir (G_misc.curdir )
367 #define physdir (G_misc.physdir )
368 #define arg0 (G_misc.arg0 )
369 #define exception_handler (G_misc.exception_handler)
370 #define exception_type (G_misc.exception_type )
371 #define suppress_int (G_misc.suppress_int )
372 #define pending_int (G_misc.pending_int )
373 #define pending_sig (G_misc.pending_sig )
374 #define isloginsh (G_misc.isloginsh )
375 #define nullstr (G_misc.nullstr )
376 #define optlist (G_misc.optlist )
377 #define sigmode (G_misc.sigmode )
378 #define gotsig (G_misc.gotsig )
379 #define may_have_traps (G_misc.may_have_traps )
380 #define trap (G_misc.trap )
381 #define trap_ptr (G_misc.trap_ptr )
382 #define random_gen (G_misc.random_gen )
383 #define backgndpid (G_misc.backgndpid )
384 #define INIT_G_misc() do { \
385 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
393 /* ============ DEBUG */
395 static void trace_printf(const char *fmt, ...);
396 static void trace_vprintf(const char *fmt, va_list va);
397 # define TRACE(param) trace_printf param
398 # define TRACEV(param) trace_vprintf param
399 # define close(fd) do { \
401 if (close(dfd) < 0) \
402 bb_error_msg("bug on %d: closing %d(0x%x)", \
403 __LINE__, dfd, dfd); \
406 # define TRACE(param)
407 # define TRACEV(param)
411 /* ============ Utility functions */
412 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
413 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
416 isdigit_str9(const char *str)
418 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
419 while (--maxlen && isdigit(*str))
421 return (*str == '\0');
425 var_end(const char *var)
434 /* ============ Interrupts / exceptions */
436 static void exitshell(void) NORETURN;
439 * These macros allow the user to suspend the handling of interrupt signals
440 * over a period of time. This is similar to SIGHOLD or to sigblock, but
441 * much more efficient and portable. (But hacking the kernel is so much
442 * more fun than worrying about efficiency and portability. :-))
444 #define INT_OFF do { \
450 * Called to raise an exception. Since C doesn't include exceptions, we
451 * just do a longjmp to the exception handler. The type of exception is
452 * stored in the global variable "exception_type".
454 static void raise_exception(int) NORETURN;
456 raise_exception(int e)
459 if (exception_handler == NULL)
464 longjmp(exception_handler->loc, 1);
467 #define raise_exception(e) do { \
468 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
469 raise_exception(e); \
474 * Called when a SIGINT is received. (If the user specifies
475 * that SIGINT is to be trapped or ignored using the trap builtin, then
476 * this routine is not called.) Suppressint is nonzero when interrupts
477 * are held using the INT_OFF macro. (The test for iflag is just
478 * defensive programming.)
480 static void raise_interrupt(void) NORETURN;
482 raise_interrupt(void)
485 /* Signal is not automatically unmasked after it is raised,
486 * do it ourself - unmask all signals */
487 sigprocmask_allsigs(SIG_UNBLOCK);
488 /* pending_sig = 0; - now done in signal_handler() */
490 if (!(rootshell && iflag)) {
491 /* Kill ourself with SIGINT */
492 signal(SIGINT, SIG_DFL);
495 /* bash: ^C even on empty command line sets $? */
496 exitstatus = SIGINT + 128;
497 raise_exception(EXINT);
501 #define raise_interrupt() do { \
502 TRACE(("raising interrupt on line %d\n", __LINE__)); \
507 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
511 if (--suppress_int == 0 && pending_int) {
515 #define INT_ON int_on()
516 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
524 #define FORCE_INT_ON force_int_on()
526 #define SAVE_INT(v) ((v) = suppress_int)
528 #define RESTORE_INT(v) do { \
530 suppress_int = (v); \
531 if (suppress_int == 0 && pending_int) \
536 /* ============ Stdout/stderr output */
539 outstr(const char *p, FILE *file)
547 flush_stdout_stderr(void)
554 /* Was called outcslow(c,FILE*), but c was always '\n' */
556 newline_and_flush(FILE *dest)
564 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
566 out1fmt(const char *fmt, ...)
573 r = vprintf(fmt, ap);
579 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
581 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
588 ret = vsnprintf(outbuf, length, fmt, ap);
595 out1str(const char *p)
601 out2str(const char *p)
604 flush_stdout_stderr();
608 /* ============ Parser structures */
610 /* control characters in argument strings */
611 #define CTL_FIRST CTLESC
612 #define CTLESC ((unsigned char)'\201') /* escape next character */
613 #define CTLVAR ((unsigned char)'\202') /* variable defn */
614 #define CTLENDVAR ((unsigned char)'\203')
615 #define CTLBACKQ ((unsigned char)'\204')
616 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
617 #define CTLENDARI ((unsigned char)'\207')
618 #define CTLQUOTEMARK ((unsigned char)'\210')
619 #define CTL_LAST CTLQUOTEMARK
621 /* variable substitution byte (follows CTLVAR) */
622 #define VSTYPE 0x0f /* type of variable substitution */
623 #define VSNUL 0x10 /* colon--treat the empty string as unset */
625 /* values of VSTYPE field */
626 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
627 #define VSMINUS 0x2 /* ${var-text} */
628 #define VSPLUS 0x3 /* ${var+text} */
629 #define VSQUESTION 0x4 /* ${var?message} */
630 #define VSASSIGN 0x5 /* ${var=text} */
631 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
632 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
633 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
634 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
635 #define VSLENGTH 0xa /* ${#var} */
636 #if ENABLE_ASH_BASH_COMPAT
637 #define VSSUBSTR 0xc /* ${var:position:length} */
638 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
639 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
642 static const char dolatstr[] ALIGN1 = {
643 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
645 #define DOLATSTRLEN 6
664 #if ENABLE_ASH_BASH_COMPAT
681 smallint type; /* Nxxxx */
684 union node *redirect;
689 smallint pipe_backgnd;
690 struct nodelist *cmdlist;
696 union node *redirect;
709 union node *elsepart;
736 struct nodelist *backquote;
739 /* nfile and ndup layout must match!
740 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
741 * that it is actually NTO2 (>&file), and change its type.
758 char *_unused_expfname;
777 struct nredir nredir;
778 struct nbinary nbinary;
782 struct nclist nclist;
791 * NODE_EOF is returned by parsecmd when it encounters an end of file.
792 * It must be distinct from NULL.
794 #define NODE_EOF ((union node *) -1L)
797 struct nodelist *next;
810 freefunc(struct funcnode *f)
812 if (f && --f->count < 0)
817 /* ============ Debugging output */
821 static FILE *tracefile;
824 trace_printf(const char *fmt, ...)
831 fprintf(tracefile, "%u ", (int) time(NULL));
833 fprintf(tracefile, "[%u] ", (int) getpid());
835 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
837 vfprintf(tracefile, fmt, va);
842 trace_vprintf(const char *fmt, va_list va)
847 fprintf(tracefile, "%u ", (int) time(NULL));
849 fprintf(tracefile, "[%u] ", (int) getpid());
851 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
852 vfprintf(tracefile, fmt, va);
856 trace_puts(const char *s)
864 trace_puts_quoted(char *s)
871 putc('"', tracefile);
872 for (p = s; *p; p++) {
873 switch ((unsigned char)*p) {
874 case '\n': c = 'n'; goto backslash;
875 case '\t': c = 't'; goto backslash;
876 case '\r': c = 'r'; goto backslash;
877 case '\"': c = '\"'; goto backslash;
878 case '\\': c = '\\'; goto backslash;
879 case CTLESC: c = 'e'; goto backslash;
880 case CTLVAR: c = 'v'; goto backslash;
881 case CTLBACKQ: c = 'q'; goto backslash;
883 putc('\\', tracefile);
887 if (*p >= ' ' && *p <= '~')
890 putc('\\', tracefile);
891 putc((*p >> 6) & 03, tracefile);
892 putc((*p >> 3) & 07, tracefile);
893 putc(*p & 07, tracefile);
898 putc('"', tracefile);
902 trace_puts_args(char **ap)
909 trace_puts_quoted(*ap);
911 putc('\n', tracefile);
914 putc(' ', tracefile);
929 /* leave open because libedit might be using it */
932 strcpy(s, "./trace");
934 if (!freopen(s, "a", tracefile)) {
935 fprintf(stderr, "Can't re-open %s\n", s);
940 tracefile = fopen(s, "a");
941 if (tracefile == NULL) {
942 fprintf(stderr, "Can't open %s\n", s);
948 flags = fcntl(fileno(tracefile), F_GETFL);
950 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
952 setlinebuf(tracefile);
953 fputs("\nTracing started.\n", tracefile);
957 indent(int amount, char *pfx, FILE *fp)
961 for (i = 0; i < amount; i++) {
962 if (pfx && i == amount - 1)
968 /* little circular references here... */
969 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
972 sharg(union node *arg, FILE *fp)
975 struct nodelist *bqlist;
976 unsigned char subtype;
978 if (arg->type != NARG) {
979 out1fmt("<node type %d>\n", arg->type);
982 bqlist = arg->narg.backquote;
983 for (p = arg->narg.text; *p; p++) {
984 switch ((unsigned char)*p) {
993 if (subtype == VSLENGTH)
1001 if (subtype & VSNUL)
1004 switch (subtype & VSTYPE) {
1030 case VSTRIMRIGHTMAX:
1037 out1fmt("<subtype %d>", subtype);
1046 shtree(bqlist->n, -1, NULL, fp);
1057 shcmd(union node *cmd, FILE *fp)
1065 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1071 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1075 switch (np->nfile.type) {
1076 case NTO: s = ">>"+1; dftfd = 1; break;
1077 case NCLOBBER: s = ">|"; dftfd = 1; break;
1078 case NAPPEND: s = ">>"; dftfd = 1; break;
1079 #if ENABLE_ASH_BASH_COMPAT
1082 case NTOFD: s = ">&"; dftfd = 1; break;
1083 case NFROM: s = "<"; break;
1084 case NFROMFD: s = "<&"; break;
1085 case NFROMTO: s = "<>"; break;
1086 default: s = "*error*"; break;
1088 if (np->nfile.fd != dftfd)
1089 fprintf(fp, "%d", np->nfile.fd);
1091 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1092 fprintf(fp, "%d", np->ndup.dupfd);
1094 sharg(np->nfile.fname, fp);
1101 shtree(union node *n, int ind, char *pfx, FILE *fp)
1103 struct nodelist *lp;
1109 indent(ind, pfx, fp);
1111 if (n == NODE_EOF) {
1126 shtree(n->nbinary.ch1, ind, NULL, fp);
1129 shtree(n->nbinary.ch2, ind, NULL, fp);
1137 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1138 shtree(lp->n, 0, NULL, fp);
1142 if (n->npipe.pipe_backgnd)
1148 fprintf(fp, "<node type %d>", n->type);
1156 showtree(union node *n)
1158 trace_puts("showtree called\n");
1159 shtree(n, 1, NULL, stderr);
1165 /* ============ Parser data */
1168 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1171 struct strlist *next;
1178 struct strpush *prev; /* preceding string on stack */
1180 int prev_left_in_line;
1181 #if ENABLE_ASH_ALIAS
1182 struct alias *ap; /* if push was associated with an alias */
1184 char *string; /* remember the string since it may change */
1186 /* Remember last two characters for pungetc. */
1189 /* Number of outstanding calls to pungetc. */
1194 struct parsefile *prev; /* preceding file on stack */
1195 int linno; /* current line */
1196 int pf_fd; /* file descriptor (or -1 if string) */
1197 int left_in_line; /* number of chars left in this line */
1198 int left_in_buffer; /* number of chars left in this buffer past the line */
1199 char *next_to_pgetc; /* next char in buffer */
1200 char *buf; /* input buffer */
1201 struct strpush *strpush; /* for pushing strings at this level */
1202 struct strpush basestrpush; /* so pushing one is fast */
1204 /* Remember last two characters for pungetc. */
1207 /* Number of outstanding calls to pungetc. */
1211 static struct parsefile basepf; /* top level input file */
1212 static struct parsefile *g_parsefile = &basepf; /* current input file */
1213 static int startlinno; /* line # where last token started */
1214 static char *commandname; /* currently executing command */
1215 static struct strlist *cmdenviron; /* environment for builtin command */
1218 /* ============ Message printing */
1221 ash_vmsg(const char *msg, va_list ap)
1223 fprintf(stderr, "%s: ", arg0);
1225 if (strcmp(arg0, commandname))
1226 fprintf(stderr, "%s: ", commandname);
1227 if (!iflag || g_parsefile->pf_fd > 0)
1228 fprintf(stderr, "line %d: ", startlinno);
1230 vfprintf(stderr, msg, ap);
1231 newline_and_flush(stderr);
1235 * Exverror is called to raise the error exception. If the second argument
1236 * is not NULL then error prints an error message using printf style
1237 * formatting. It then raises the error exception.
1239 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1241 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1245 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1247 TRACE(("\") pid=%d\n", getpid()));
1249 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1254 flush_stdout_stderr();
1255 raise_exception(cond);
1259 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1261 ash_msg_and_raise_error(const char *msg, ...)
1266 ash_vmsg_and_raise(EXERROR, msg, ap);
1271 static void raise_error_syntax(const char *) NORETURN;
1273 raise_error_syntax(const char *msg)
1275 ash_msg_and_raise_error("syntax error: %s", msg);
1279 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1281 ash_msg_and_raise(int cond, const char *msg, ...)
1286 ash_vmsg_and_raise(cond, msg, ap);
1292 * error/warning routines for external builtins
1295 ash_msg(const char *fmt, ...)
1305 * Return a string describing an error. The returned string may be a
1306 * pointer to a static buffer that will be overwritten on the next call.
1307 * Action describes the operation that got the error.
1310 errmsg(int e, const char *em)
1312 if (e == ENOENT || e == ENOTDIR) {
1319 /* ============ Memory allocation */
1322 /* I consider these wrappers nearly useless:
1323 * ok, they return you to nearest exception handler, but
1324 * how much memory do you leak in the process, making
1325 * memory starvation worse?
1328 ckrealloc(void * p, size_t nbytes)
1330 p = realloc(p, nbytes);
1332 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1337 ckmalloc(size_t nbytes)
1339 return ckrealloc(NULL, nbytes);
1343 ckzalloc(size_t nbytes)
1345 return memset(ckmalloc(nbytes), 0, nbytes);
1349 ckstrdup(const char *s)
1351 char *p = strdup(s);
1353 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1357 /* Using bbox equivalents. They exit if out of memory */
1358 # define ckrealloc xrealloc
1359 # define ckmalloc xmalloc
1360 # define ckzalloc xzalloc
1361 # define ckstrdup xstrdup
1365 * It appears that grabstackstr() will barf with such alignments
1366 * because stalloc() will return a string allocated in a new stackblock.
1368 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1370 /* Most machines require the value returned from malloc to be aligned
1371 * in some way. The following macro will get this right
1372 * on many machines. */
1373 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1374 /* Minimum size of a block */
1375 MINSIZE = SHELL_ALIGN(504),
1378 struct stack_block {
1379 struct stack_block *prev;
1380 char space[MINSIZE];
1384 struct stack_block *stackp;
1390 struct globals_memstack {
1391 struct stack_block *g_stackp; // = &stackbase;
1392 char *g_stacknxt; // = stackbase.space;
1393 char *sstrend; // = stackbase.space + MINSIZE;
1394 size_t g_stacknleft; // = MINSIZE;
1395 struct stack_block stackbase;
1397 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1398 #define G_memstack (*ash_ptr_to_globals_memstack)
1399 #define g_stackp (G_memstack.g_stackp )
1400 #define g_stacknxt (G_memstack.g_stacknxt )
1401 #define sstrend (G_memstack.sstrend )
1402 #define g_stacknleft (G_memstack.g_stacknleft)
1403 #define stackbase (G_memstack.stackbase )
1404 #define INIT_G_memstack() do { \
1405 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1407 g_stackp = &stackbase; \
1408 g_stacknxt = stackbase.space; \
1409 g_stacknleft = MINSIZE; \
1410 sstrend = stackbase.space + MINSIZE; \
1414 #define stackblock() ((void *)g_stacknxt)
1415 #define stackblocksize() g_stacknleft
1418 * Parse trees for commands are allocated in lifo order, so we use a stack
1419 * to make this more efficient, and also to avoid all sorts of exception
1420 * handling code to handle interrupts in the middle of a parse.
1422 * The size 504 was chosen because the Ultrix malloc handles that size
1426 stalloc(size_t nbytes)
1431 aligned = SHELL_ALIGN(nbytes);
1432 if (aligned > g_stacknleft) {
1435 struct stack_block *sp;
1437 blocksize = aligned;
1438 if (blocksize < MINSIZE)
1439 blocksize = MINSIZE;
1440 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1441 if (len < blocksize)
1442 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1445 sp->prev = g_stackp;
1446 g_stacknxt = sp->space;
1447 g_stacknleft = blocksize;
1448 sstrend = g_stacknxt + blocksize;
1453 g_stacknxt += aligned;
1454 g_stacknleft -= aligned;
1459 stzalloc(size_t nbytes)
1461 return memset(stalloc(nbytes), 0, nbytes);
1468 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1469 write(STDERR_FILENO, "stunalloc\n", 10);
1473 g_stacknleft += g_stacknxt - (char *)p;
1478 * Like strdup but works with the ash stack.
1481 sstrdup(const char *p)
1483 size_t len = strlen(p) + 1;
1484 return memcpy(stalloc(len), p, len);
1488 grabstackblock(size_t len)
1494 pushstackmark(struct stackmark *mark, size_t len)
1496 mark->stackp = g_stackp;
1497 mark->stacknxt = g_stacknxt;
1498 mark->stacknleft = g_stacknleft;
1499 grabstackblock(len);
1503 setstackmark(struct stackmark *mark)
1505 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1509 popstackmark(struct stackmark *mark)
1511 struct stack_block *sp;
1517 while (g_stackp != mark->stackp) {
1519 g_stackp = sp->prev;
1522 g_stacknxt = mark->stacknxt;
1523 g_stacknleft = mark->stacknleft;
1524 sstrend = mark->stacknxt + mark->stacknleft;
1529 * When the parser reads in a string, it wants to stick the string on the
1530 * stack and only adjust the stack pointer when it knows how big the
1531 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1532 * of space on top of the stack and stackblocklen returns the length of
1533 * this block. Growstackblock will grow this space by at least one byte,
1534 * possibly moving it (like realloc). Grabstackblock actually allocates the
1535 * part of the block that has been used.
1538 growstackblock(void)
1542 newlen = g_stacknleft * 2;
1543 if (newlen < g_stacknleft)
1544 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1548 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1549 struct stack_block *sp;
1550 struct stack_block *prevstackp;
1555 prevstackp = sp->prev;
1556 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1557 sp = ckrealloc(sp, grosslen);
1558 sp->prev = prevstackp;
1560 g_stacknxt = sp->space;
1561 g_stacknleft = newlen;
1562 sstrend = sp->space + newlen;
1565 char *oldspace = g_stacknxt;
1566 size_t oldlen = g_stacknleft;
1567 char *p = stalloc(newlen);
1569 /* free the space we just allocated */
1570 g_stacknxt = memcpy(p, oldspace, oldlen);
1571 g_stacknleft += newlen;
1576 * The following routines are somewhat easier to use than the above.
1577 * The user declares a variable of type STACKSTR, which may be declared
1578 * to be a register. The macro STARTSTACKSTR initializes things. Then
1579 * the user uses the macro STPUTC to add characters to the string. In
1580 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1581 * grown as necessary. When the user is done, she can just leave the
1582 * string there and refer to it using stackblock(). Or she can allocate
1583 * the space for it using grabstackstr(). If it is necessary to allow
1584 * someone else to use the stack temporarily and then continue to grow
1585 * the string, the user should use grabstack to allocate the space, and
1586 * then call ungrabstr(p) to return to the previous mode of operation.
1588 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1589 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1590 * is space for at least one character.
1595 size_t len = stackblocksize();
1597 return (char *)stackblock() + len;
1601 * Called from CHECKSTRSPACE.
1604 makestrspace(size_t newlen, char *p)
1606 size_t len = p - g_stacknxt;
1612 size = stackblocksize();
1614 if (nleft >= newlen)
1618 return (char *)stackblock() + len;
1622 stack_nputstr(const char *s, size_t n, char *p)
1624 p = makestrspace(n, p);
1625 p = (char *)memcpy(p, s, n) + n;
1630 stack_putstr(const char *s, char *p)
1632 return stack_nputstr(s, strlen(s), p);
1636 _STPUTC(int c, char *p)
1644 #define STARTSTACKSTR(p) ((p) = stackblock())
1645 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1646 #define CHECKSTRSPACE(n, p) do { \
1649 size_t m = sstrend - q; \
1651 (p) = makestrspace(l, q); \
1653 #define USTPUTC(c, p) (*(p)++ = (c))
1654 #define STACKSTRNUL(p) do { \
1655 if ((p) == sstrend) \
1656 (p) = growstackstr(); \
1659 #define STUNPUTC(p) (--(p))
1660 #define STTOPC(p) ((p)[-1])
1661 #define STADJUST(amount, p) ((p) += (amount))
1663 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1664 #define ungrabstackstr(s, p) stunalloc(s)
1665 #define stackstrend() ((void *)sstrend)
1668 /* ============ String helpers */
1671 * prefix -- see if pfx is a prefix of string.
1674 prefix(const char *string, const char *pfx)
1677 if (*pfx++ != *string++)
1680 return (char *) string;
1684 * Check for a valid number. This should be elsewhere.
1687 is_number(const char *p)
1692 } while (*++p != '\0');
1697 * Convert a string of digits to an integer, printing an error message on
1701 number(const char *s)
1704 ash_msg_and_raise_error(msg_illnum, s);
1709 * Produce a possibly single quoted string suitable as input to the shell.
1710 * The return string is allocated on the stack.
1713 single_quote(const char *s)
1723 len = strchrnul(s, '\'') - s;
1725 q = p = makestrspace(len + 3, p);
1728 q = (char *)memcpy(q, s, len) + len;
1737 do len++; while (*++s == '\'');
1739 q = p = makestrspace(len + 3, p);
1742 q = (char *)memcpy(q, s - len, len) + len;
1750 return stackblock();
1754 /* ============ nextopt */
1756 static char **argptr; /* argument list for builtin commands */
1757 static char *optionarg; /* set by nextopt (like getopt) */
1758 static char *optptr; /* used by nextopt */
1761 * XXX - should get rid of. Have all builtins use getopt(3).
1762 * The library getopt must have the BSD extension static variable
1763 * "optreset", otherwise it can't be used within the shell safely.
1765 * Standard option processing (a la getopt) for builtin routines.
1766 * The only argument that is passed to nextopt is the option string;
1767 * the other arguments are unnecessary. It returns the character,
1768 * or '\0' on end of input.
1771 nextopt(const char *optstring)
1778 if (p == NULL || *p == '\0') {
1779 /* We ate entire "-param", take next one */
1785 if (*++p == '\0') /* just "-" ? */
1788 if (LONE_DASH(p)) /* "--" ? */
1790 /* p => next "-param" */
1792 /* p => some option char in the middle of a "-param" */
1794 for (q = optstring; *q != c;) {
1796 ash_msg_and_raise_error("illegal option -%c", c);
1804 ash_msg_and_raise_error("no arg for -%c option", c);
1814 /* ============ Shell variables */
1817 * The parsefile structure pointed to by the global variable parsefile
1818 * contains information about the current file being read.
1821 int nparam; /* # of positional parameters (without $0) */
1822 #if ENABLE_ASH_GETOPTS
1823 int optind; /* next parameter to be processed by getopts */
1824 int optoff; /* used by getopts */
1826 unsigned char malloced; /* if parameter list dynamically allocated */
1827 char **p; /* parameter list */
1831 * Free the list of positional parameters.
1834 freeparam(volatile struct shparam *param)
1836 if (param->malloced) {
1838 ap = ap1 = param->p;
1845 #if ENABLE_ASH_GETOPTS
1846 static void FAST_FUNC getoptsreset(const char *value);
1850 struct var *next; /* next entry in hash list */
1851 int flags; /* flags are defined above */
1852 const char *var_text; /* name=value */
1853 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1854 /* the variable gets set/unset */
1858 struct localvar *next; /* next local variable in list */
1859 struct var *vp; /* the variable that was made local */
1860 int flags; /* saved flags */
1861 const char *text; /* saved text */
1865 #define VEXPORT 0x01 /* variable is exported */
1866 #define VREADONLY 0x02 /* variable cannot be modified */
1867 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1868 #define VTEXTFIXED 0x08 /* text is statically allocated */
1869 #define VSTACK 0x10 /* text is allocated on the stack */
1870 #define VUNSET 0x20 /* the variable is not set */
1871 #define VNOFUNC 0x40 /* don't call the callback function */
1872 #define VNOSET 0x80 /* do not set variable - just readonly test */
1873 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1874 #if ENABLE_ASH_RANDOM_SUPPORT
1875 # define VDYNAMIC 0x200 /* dynamic variable */
1881 /* Need to be before varinit_data[] */
1882 #if ENABLE_LOCALE_SUPPORT
1883 static void FAST_FUNC
1884 change_lc_all(const char *value)
1886 if (value && *value != '\0')
1887 setlocale(LC_ALL, value);
1889 static void FAST_FUNC
1890 change_lc_ctype(const char *value)
1892 if (value && *value != '\0')
1893 setlocale(LC_CTYPE, value);
1897 static void chkmail(void);
1898 static void changemail(const char *var_value) FAST_FUNC;
1900 # define chkmail() ((void)0)
1902 static void changepath(const char *) FAST_FUNC;
1903 #if ENABLE_ASH_RANDOM_SUPPORT
1904 static void change_random(const char *) FAST_FUNC;
1907 static const struct {
1909 const char *var_text;
1910 void (*var_func)(const char *) FAST_FUNC;
1911 } varinit_data[] = {
1913 * Note: VEXPORT would not work correctly here for NOFORK applets:
1914 * some environment strings may be constant.
1916 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1918 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1919 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1921 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1922 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1923 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1924 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1925 #if ENABLE_ASH_GETOPTS
1926 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1928 #if ENABLE_ASH_RANDOM_SUPPORT
1929 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1931 #if ENABLE_LOCALE_SUPPORT
1932 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1933 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1935 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1936 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1942 struct globals_var {
1943 struct shparam shellparam; /* $@ current positional parameters */
1944 struct redirtab *redirlist;
1945 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1946 struct var *vartab[VTABSIZE];
1947 struct var varinit[ARRAY_SIZE(varinit_data)];
1949 extern struct globals_var *const ash_ptr_to_globals_var;
1950 #define G_var (*ash_ptr_to_globals_var)
1951 #define shellparam (G_var.shellparam )
1952 //#define redirlist (G_var.redirlist )
1953 #define preverrout_fd (G_var.preverrout_fd)
1954 #define vartab (G_var.vartab )
1955 #define varinit (G_var.varinit )
1956 #define INIT_G_var() do { \
1958 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1960 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1961 varinit[i].flags = varinit_data[i].flags; \
1962 varinit[i].var_text = varinit_data[i].var_text; \
1963 varinit[i].var_func = varinit_data[i].var_func; \
1967 #define vifs varinit[0]
1969 # define vmail (&vifs)[1]
1970 # define vmpath (&vmail)[1]
1971 # define vpath (&vmpath)[1]
1973 # define vpath (&vifs)[1]
1975 #define vps1 (&vpath)[1]
1976 #define vps2 (&vps1)[1]
1977 #define vps4 (&vps2)[1]
1978 #if ENABLE_ASH_GETOPTS
1979 # define voptind (&vps4)[1]
1980 # if ENABLE_ASH_RANDOM_SUPPORT
1981 # define vrandom (&voptind)[1]
1984 # if ENABLE_ASH_RANDOM_SUPPORT
1985 # define vrandom (&vps4)[1]
1990 * The following macros access the values of the above variables.
1991 * They have to skip over the name. They return the null string
1992 * for unset variables.
1994 #define ifsval() (vifs.var_text + 4)
1995 #define ifsset() ((vifs.flags & VUNSET) == 0)
1997 # define mailval() (vmail.var_text + 5)
1998 # define mpathval() (vmpath.var_text + 9)
1999 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2001 #define pathval() (vpath.var_text + 5)
2002 #define ps1val() (vps1.var_text + 4)
2003 #define ps2val() (vps2.var_text + 4)
2004 #define ps4val() (vps4.var_text + 4)
2005 #if ENABLE_ASH_GETOPTS
2006 # define optindval() (voptind.var_text + 7)
2009 #if ENABLE_ASH_GETOPTS
2010 static void FAST_FUNC
2011 getoptsreset(const char *value)
2013 shellparam.optind = number(value) ?: 1;
2014 shellparam.optoff = -1;
2019 * Compares two strings up to the first = or '\0'. The first
2020 * string must be terminated by '='; the second may be terminated by
2021 * either '=' or '\0'.
2024 varcmp(const char *p, const char *q)
2028 while ((c = *p) == (d = *q)) {
2029 if (c == '\0' || c == '=')
2043 * Find the appropriate entry in the hash table from the name.
2045 static struct var **
2046 hashvar(const char *p)
2050 hashval = ((unsigned char) *p) << 4;
2051 while (*p && *p != '=')
2052 hashval += (unsigned char) *p++;
2053 return &vartab[hashval % VTABSIZE];
2057 vpcmp(const void *a, const void *b)
2059 return varcmp(*(const char **)a, *(const char **)b);
2063 * This routine initializes the builtin variables.
2073 * PS1 depends on uid
2075 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2076 vps1.var_text = "PS1=\\w \\$ ";
2079 vps1.var_text = "PS1=# ";
2082 end = vp + ARRAY_SIZE(varinit);
2084 vpp = hashvar(vp->var_text);
2087 } while (++vp < end);
2090 static struct var **
2091 findvar(struct var **vpp, const char *name)
2093 for (; *vpp; vpp = &(*vpp)->next) {
2094 if (varcmp((*vpp)->var_text, name) == 0) {
2102 * Find the value of a variable. Returns NULL if not set.
2104 static const char* FAST_FUNC
2105 lookupvar(const char *name)
2109 v = *findvar(hashvar(name), name);
2111 #if ENABLE_ASH_RANDOM_SUPPORT
2113 * Dynamic variables are implemented roughly the same way they are
2114 * in bash. Namely, they're "special" so long as they aren't unset.
2115 * As soon as they're unset, they're no longer dynamic, and dynamic
2116 * lookup will no longer happen at that point. -- PFM.
2118 if (v->flags & VDYNAMIC)
2121 if (!(v->flags & VUNSET))
2122 return var_end(v->var_text);
2128 reinit_unicode_for_ash(void)
2130 /* Unicode support should be activated even if LANG is set
2131 * _during_ shell execution, not only if it was set when
2132 * shell was started. Therefore, re-check LANG every time:
2134 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2135 || ENABLE_UNICODE_USING_LOCALE
2137 const char *s = lookupvar("LC_ALL");
2138 if (!s) s = lookupvar("LC_CTYPE");
2139 if (!s) s = lookupvar("LANG");
2145 * Search the environment of a builtin command.
2148 bltinlookup(const char *name)
2152 for (sp = cmdenviron; sp; sp = sp->next) {
2153 if (varcmp(sp->text, name) == 0)
2154 return var_end(sp->text);
2156 return lookupvar(name);
2160 * Same as setvar except that the variable and value are passed in
2161 * the first argument as name=value. Since the first argument will
2162 * be actually stored in the table, it should not be a string that
2164 * Called with interrupts off.
2167 setvareq(char *s, int flags)
2169 struct var *vp, **vpp;
2172 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2173 vp = *findvar(vpp, s);
2175 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2178 if (flags & VNOSAVE)
2181 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2187 if (vp->var_func && !(flags & VNOFUNC))
2188 vp->var_func(var_end(s));
2190 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2191 free((char*)vp->var_text);
2193 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2195 /* variable s is not found */
2198 vp = ckzalloc(sizeof(*vp));
2200 /*vp->func = NULL; - ckzalloc did it */
2203 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2210 * Set the value of a variable. The flags argument is ored with the
2211 * flags of the variable. If val is NULL, the variable is unset.
2214 setvar(const char *name, const char *val, int flags)
2222 q = endofname(name);
2223 p = strchrnul(q, '=');
2225 if (!namelen || p != q)
2226 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2231 vallen = strlen(val);
2235 nameeq = ckmalloc(namelen + vallen + 2);
2236 p = memcpy(nameeq, name, namelen) + namelen;
2239 p = memcpy(p, val, vallen) + vallen;
2242 setvareq(nameeq, flags | VNOSAVE);
2246 static void FAST_FUNC
2247 setvar0(const char *name, const char *val)
2249 setvar(name, val, 0);
2253 * Unset the specified variable.
2256 unsetvar(const char *s)
2262 vpp = findvar(hashvar(s), s);
2266 int flags = vp->flags;
2269 if (flags & VREADONLY)
2271 #if ENABLE_ASH_RANDOM_SUPPORT
2272 vp->flags &= ~VDYNAMIC;
2276 if ((flags & VSTRFIXED) == 0) {
2278 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2279 free((char*)vp->var_text);
2285 vp->flags &= ~VEXPORT;
2295 * Process a linked list of variable assignments.
2298 listsetvar(struct strlist *list_set_var, int flags)
2300 struct strlist *lp = list_set_var;
2306 setvareq(lp->text, flags);
2313 * Generate a list of variables satisfying the given conditions.
2316 listvars(int on, int off, char ***end)
2327 for (vp = *vpp; vp; vp = vp->next) {
2328 if ((vp->flags & mask) == on) {
2329 if (ep == stackstrend())
2330 ep = growstackstr();
2331 *ep++ = (char*)vp->var_text;
2334 } while (++vpp < vartab + VTABSIZE);
2335 if (ep == stackstrend())
2336 ep = growstackstr();
2340 return grabstackstr(ep);
2344 /* ============ Path search helper
2346 * The variable path (passed by reference) should be set to the start
2347 * of the path before the first call; path_advance will update
2348 * this value as it proceeds. Successive calls to path_advance will return
2349 * the possible path expansions in sequence. If an option (indicated by
2350 * a percent sign) appears in the path entry then the global variable
2351 * pathopt will be set to point to it; otherwise pathopt will be set to
2354 static const char *pathopt; /* set by path_advance */
2357 path_advance(const char **path, const char *name)
2367 for (p = start; *p && *p != ':' && *p != '%'; p++)
2369 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2370 while (stackblocksize() < len)
2374 memcpy(q, start, p - start);
2382 while (*p && *p != ':')
2389 return stalloc(len);
2393 /* ============ Prompt */
2395 static smallint doprompt; /* if set, prompt the user */
2396 static smallint needprompt; /* true if interactive and at start of line */
2398 #if ENABLE_FEATURE_EDITING
2399 static line_input_t *line_input_state;
2400 static const char *cmdedit_prompt;
2402 putprompt(const char *s)
2404 if (ENABLE_ASH_EXPAND_PRMT) {
2405 free((char*)cmdedit_prompt);
2406 cmdedit_prompt = ckstrdup(s);
2413 putprompt(const char *s)
2419 #if ENABLE_ASH_EXPAND_PRMT
2420 /* expandstr() needs parsing machinery, so it is far away ahead... */
2421 static const char *expandstr(const char *ps);
2423 #define expandstr(s) s
2427 setprompt_if(smallint do_set, int whichprompt)
2430 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2437 switch (whichprompt) {
2447 #if ENABLE_ASH_EXPAND_PRMT
2448 pushstackmark(&smark, stackblocksize());
2450 putprompt(expandstr(prompt));
2451 #if ENABLE_ASH_EXPAND_PRMT
2452 popstackmark(&smark);
2457 /* ============ The cd and pwd commands */
2459 #define CD_PHYSICAL 1
2469 while ((i = nextopt("LP")) != '\0') {
2471 flags ^= CD_PHYSICAL;
2480 * Update curdir (the name of the current directory) in response to a
2484 updatepwd(const char *dir)
2491 cdcomppath = sstrdup(dir);
2494 if (curdir == nullstr)
2496 new = stack_putstr(curdir, new);
2498 new = makestrspace(strlen(dir) + 2, new);
2499 lim = (char *)stackblock() + 1;
2503 if (new > lim && *lim == '/')
2508 if (dir[1] == '/' && dir[2] != '/') {
2514 p = strtok(cdcomppath, "/");
2518 if (p[1] == '.' && p[2] == '\0') {
2530 new = stack_putstr(p, new);
2533 p = strtok(NULL, "/");
2538 return stackblock();
2542 * Find out what the current directory is. If we already know the current
2543 * directory, this routine returns immediately.
2548 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2549 return dir ? dir : nullstr;
2553 setpwd(const char *val, int setold)
2557 oldcur = dir = curdir;
2560 setvar("OLDPWD", oldcur, VEXPORT);
2563 if (physdir != nullstr) {
2564 if (physdir != oldcur)
2568 if (oldcur == val || !val) {
2574 dir = ckstrdup(val);
2575 if (oldcur != dir && oldcur != nullstr) {
2580 setvar("PWD", dir, VEXPORT);
2583 static void hashcd(void);
2586 * Actually do the chdir. We also call hashcd to let other routines
2587 * know that the current directory has changed.
2590 docd(const char *dest, int flags)
2592 const char *dir = NULL;
2595 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2598 if (!(flags & CD_PHYSICAL)) {
2599 dir = updatepwd(dest);
2613 static int FAST_FUNC
2614 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2626 dest = bltinlookup("HOME");
2627 else if (LONE_DASH(dest)) {
2628 dest = bltinlookup("OLDPWD");
2650 path = bltinlookup("CDPATH");
2653 p = path_advance(&path, dest);
2654 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2658 if (!docd(p, flags))
2669 ash_msg_and_raise_error("can't cd to %s", dest);
2672 if (flags & CD_PRINT)
2673 out1fmt("%s\n", curdir);
2677 static int FAST_FUNC
2678 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2681 const char *dir = curdir;
2685 if (physdir == nullstr)
2689 out1fmt("%s\n", dir);
2694 /* ============ ... */
2697 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2699 /* Syntax classes */
2700 #define CWORD 0 /* character is nothing special */
2701 #define CNL 1 /* newline character */
2702 #define CBACK 2 /* a backslash character */
2703 #define CSQUOTE 3 /* single quote */
2704 #define CDQUOTE 4 /* double quote */
2705 #define CENDQUOTE 5 /* a terminating quote */
2706 #define CBQUOTE 6 /* backwards single quote */
2707 #define CVAR 7 /* a dollar sign */
2708 #define CENDVAR 8 /* a '}' character */
2709 #define CLP 9 /* a left paren in arithmetic */
2710 #define CRP 10 /* a right paren in arithmetic */
2711 #define CENDFILE 11 /* end of file */
2712 #define CCTL 12 /* like CWORD, except it must be escaped */
2713 #define CSPCL 13 /* these terminate a word */
2714 #define CIGN 14 /* character should be ignored */
2717 #if ENABLE_ASH_ALIAS
2721 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2723 #if ENABLE_SH_MATH_SUPPORT
2724 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2726 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2728 static const uint16_t S_I_T[] ALIGN2 = {
2729 #if ENABLE_ASH_ALIAS
2730 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2732 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2733 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2734 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2735 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2736 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2737 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2738 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2739 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2740 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2741 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2742 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2743 #if !USE_SIT_FUNCTION
2744 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2745 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2746 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2750 /* Constants below must match table above */
2752 #if ENABLE_ASH_ALIAS
2753 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2755 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2756 CNL_CNL_CNL_CNL , /* 2 */
2757 CWORD_CCTL_CCTL_CWORD , /* 3 */
2758 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2759 CVAR_CVAR_CWORD_CVAR , /* 5 */
2760 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2761 CSPCL_CWORD_CWORD_CLP , /* 7 */
2762 CSPCL_CWORD_CWORD_CRP , /* 8 */
2763 CBACK_CBACK_CCTL_CBACK , /* 9 */
2764 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2765 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2766 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2767 CWORD_CWORD_CWORD_CWORD , /* 13 */
2768 CCTL_CCTL_CCTL_CCTL , /* 14 */
2771 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2772 * caller must ensure proper cast on it if c is *char_ptr!
2774 /* Values for syntax param */
2775 #define BASESYNTAX 0 /* not in quotes */
2776 #define DQSYNTAX 1 /* in double quotes */
2777 #define SQSYNTAX 2 /* in single quotes */
2778 #define ARISYNTAX 3 /* in arithmetic */
2779 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2781 #if USE_SIT_FUNCTION
2784 SIT(int c, int syntax)
2786 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2787 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2789 * This causes '/' to be prepended with CTLESC in dquoted string,
2790 * making "./file"* treated incorrectly because we feed
2791 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2792 * The "homegrown" glob implementation is okay with that,
2793 * but glibc one isn't. With '/' always treated as CWORD,
2796 # if ENABLE_ASH_ALIAS
2797 static const uint8_t syntax_index_table[] ALIGN1 = {
2798 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2799 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2800 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2804 static const uint8_t syntax_index_table[] ALIGN1 = {
2805 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2806 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2807 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2816 # if ENABLE_ASH_ALIAS
2822 /* Cast is purely for paranoia here,
2823 * just in case someone passed signed char to us */
2824 if ((unsigned char)c >= CTL_FIRST
2825 && (unsigned char)c <= CTL_LAST
2829 s = strchrnul(spec_symbls, c);
2832 indx = syntax_index_table[s - spec_symbls];
2834 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2837 #else /* !USE_SIT_FUNCTION */
2839 static const uint8_t syntax_index_table[] ALIGN1 = {
2840 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2841 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2851 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2852 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2874 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2875 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2876 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2877 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2878 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2880 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2881 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2882 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2883 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2884 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2885 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2886 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2887 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2888 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2889 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2901 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2934 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2935 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2939 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2967 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2968 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2969 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2970 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2972 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2973 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2974 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2975 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2976 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2977 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2978 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2979 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3098 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3099 # if ENABLE_ASH_ALIAS
3100 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3104 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3106 #endif /* !USE_SIT_FUNCTION */
3109 /* ============ Alias handling */
3111 #if ENABLE_ASH_ALIAS
3113 #define ALIASINUSE 1
3124 static struct alias **atab; // [ATABSIZE];
3125 #define INIT_G_alias() do { \
3126 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3130 static struct alias **
3131 __lookupalias(const char *name)
3133 unsigned int hashval;
3140 ch = (unsigned char)*p;
3144 ch = (unsigned char)*++p;
3146 app = &atab[hashval % ATABSIZE];
3148 for (; *app; app = &(*app)->next) {
3149 if (strcmp(name, (*app)->name) == 0) {
3157 static struct alias *
3158 lookupalias(const char *name, int check)
3160 struct alias *ap = *__lookupalias(name);
3162 if (check && ap && (ap->flag & ALIASINUSE))
3167 static struct alias *
3168 freealias(struct alias *ap)
3172 if (ap->flag & ALIASINUSE) {
3173 ap->flag |= ALIASDEAD;
3185 setalias(const char *name, const char *val)
3187 struct alias *ap, **app;
3189 app = __lookupalias(name);
3193 if (!(ap->flag & ALIASINUSE)) {
3196 ap->val = ckstrdup(val);
3197 ap->flag &= ~ALIASDEAD;
3200 ap = ckzalloc(sizeof(struct alias));
3201 ap->name = ckstrdup(name);
3202 ap->val = ckstrdup(val);
3203 /*ap->flag = 0; - ckzalloc did it */
3204 /*ap->next = NULL;*/
3211 unalias(const char *name)
3215 app = __lookupalias(name);
3219 *app = freealias(*app);
3230 struct alias *ap, **app;
3234 for (i = 0; i < ATABSIZE; i++) {
3236 for (ap = *app; ap; ap = *app) {
3237 *app = freealias(*app);
3247 printalias(const struct alias *ap)
3249 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3253 * TODO - sort output
3255 static int FAST_FUNC
3256 aliascmd(int argc UNUSED_PARAM, char **argv)
3265 for (i = 0; i < ATABSIZE; i++) {
3266 for (ap = atab[i]; ap; ap = ap->next) {
3272 while ((n = *++argv) != NULL) {
3273 v = strchr(n+1, '=');
3274 if (v == NULL) { /* n+1: funny ksh stuff */
3275 ap = *__lookupalias(n);
3277 fprintf(stderr, "%s: %s not found\n", "alias", n);
3290 static int FAST_FUNC
3291 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3295 while ((i = nextopt("a")) != '\0') {
3301 for (i = 0; *argptr; argptr++) {
3302 if (unalias(*argptr)) {
3303 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3311 #endif /* ASH_ALIAS */
3314 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3317 #define FORK_NOJOB 2
3319 /* mode flags for showjob(s) */
3320 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3321 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3322 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3323 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3326 * A job structure contains information about a job. A job is either a
3327 * single process or a set of processes contained in a pipeline. In the
3328 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3332 pid_t ps_pid; /* process id */
3333 int ps_status; /* last process status from wait() */
3334 char *ps_cmd; /* text of command being run */
3338 struct procstat ps0; /* status of process */
3339 struct procstat *ps; /* status or processes when more than one */
3341 int stopstatus; /* status of a stopped job */
3344 nprocs: 16, /* number of processes */
3346 #define JOBRUNNING 0 /* at least one proc running */
3347 #define JOBSTOPPED 1 /* all procs are stopped */
3348 #define JOBDONE 2 /* all procs are completed */
3350 sigint: 1, /* job was killed by SIGINT */
3351 jobctl: 1, /* job running under job control */
3353 waited: 1, /* true if this entry has been waited for */
3354 used: 1, /* true if this entry is in used */
3355 changed: 1; /* true if status has changed */
3356 struct job *prev_job; /* previous job */
3359 static struct job *makejob(/*union node *,*/ int);
3360 static int forkshell(struct job *, union node *, int);
3361 static int waitforjob(struct job *);
3364 enum { doing_jobctl = 0 };
3365 #define setjobctl(on) do {} while (0)
3367 static smallint doing_jobctl; //references:8
3368 static void setjobctl(int);
3375 ignoresig(int signo)
3377 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3378 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3379 /* No, need to do it */
3380 signal(signo, SIG_IGN);
3382 sigmode[signo - 1] = S_HARD_IGN;
3386 * Only one usage site - in setsignal()
3389 signal_handler(int signo)
3391 gotsig[signo - 1] = 1;
3393 if (signo == SIGINT && !trap[SIGINT]) {
3394 if (!suppress_int) {
3396 raise_interrupt(); /* does not return */
3400 pending_sig = signo;
3405 * Set the signal handler for the specified signal. The routine figures
3406 * out what it should be set to.
3409 setsignal(int signo)
3412 char cur_act, new_act;
3413 struct sigaction act;
3417 if (t != NULL) { /* trap for this sig is set */
3419 if (t[0] == '\0') /* trap is "": ignore this sig */
3423 if (rootshell && new_act == S_DFL) {
3426 if (iflag || minusc || sflag == 0)
3435 * "In all cases, bash ignores SIGQUIT. Non-builtin
3436 * commands run by bash have signal handlers
3437 * set to the values inherited by the shell
3438 * from its parent". */
3454 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3455 //whereas we have to restore it to what shell got on entry
3456 //from the parent. See comment above
3458 t = &sigmode[signo - 1];
3461 /* current setting is not yet known */
3462 if (sigaction(signo, NULL, &act)) {
3463 /* pretend it worked; maybe we should give a warning,
3464 * but other shells don't. We don't alter sigmode,
3465 * so we retry every time.
3466 * btw, in Linux it never fails. --vda */
3469 if (act.sa_handler == SIG_IGN) {
3470 cur_act = S_HARD_IGN;
3472 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3474 cur_act = S_IGN; /* don't hard ignore these */
3478 if (cur_act == S_HARD_IGN || cur_act == new_act)
3481 act.sa_handler = SIG_DFL;
3484 act.sa_handler = signal_handler;
3487 act.sa_handler = SIG_IGN;
3491 /* flags and mask matter only if !DFL and !IGN, but we do it
3492 * for all cases for more deterministic behavior:
3495 sigfillset(&act.sa_mask);
3497 sigaction_set(signo, &act);
3502 /* mode flags for set_curjob */
3503 #define CUR_DELETE 2
3504 #define CUR_RUNNING 1
3505 #define CUR_STOPPED 0
3507 /* mode flags for dowait */
3508 #define DOWAIT_NONBLOCK 0
3509 #define DOWAIT_BLOCK 1
3512 /* pgrp of shell on invocation */
3513 static int initialpgrp; //references:2
3514 static int ttyfd = -1; //5
3517 static struct job *jobtab; //5
3519 static unsigned njobs; //4
3521 static struct job *curjob; //lots
3522 /* number of presumed living untracked jobs */
3523 static int jobless; //4
3526 set_curjob(struct job *jp, unsigned mode)
3529 struct job **jpp, **curp;
3531 /* first remove from list */
3532 jpp = curp = &curjob;
3537 jpp = &jp1->prev_job;
3539 *jpp = jp1->prev_job;
3541 /* Then re-insert in correct position */
3549 /* job being deleted */
3552 /* newly created job or backgrounded job,
3553 * put after all stopped jobs.
3558 if (!jp1 || jp1->state != JOBSTOPPED)
3561 jpp = &jp1->prev_job;
3567 /* newly stopped job - becomes curjob */
3568 jp->prev_job = *jpp;
3576 jobno(const struct job *jp)
3578 return jp - jobtab + 1;
3583 * Convert a job name to a job structure.
3586 #define getjob(name, getctl) getjob(name)
3589 getjob(const char *name, int getctl)
3593 const char *err_msg = "%s: no such job";
3597 char *(*match)(const char *, const char *);
3612 if (c == '+' || c == '%') {
3614 err_msg = "No current job";
3620 err_msg = "No previous job";
3630 if (num > 0 && num <= njobs) {
3631 jp = jobtab + num - 1;
3646 if (match(jp->ps[0].ps_cmd, p)) {
3650 err_msg = "%s: ambiguous";
3660 err_msg = "job %s not created under job control";
3661 if (getctl && jp->jobctl == 0)
3666 ash_msg_and_raise_error(err_msg, name);
3670 * Mark a job structure as unused.
3673 freejob(struct job *jp)
3675 struct procstat *ps;
3679 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3680 if (ps->ps_cmd != nullstr)
3683 if (jp->ps != &jp->ps0)
3686 set_curjob(jp, CUR_DELETE);
3692 xtcsetpgrp(int fd, pid_t pgrp)
3694 if (tcsetpgrp(fd, pgrp))
3695 ash_msg_and_raise_error("can't set tty process group (%m)");
3699 * Turn job control on and off.
3701 * Note: This code assumes that the third arg to ioctl is a character
3702 * pointer, which is true on Berkeley systems but not System V. Since
3703 * System V doesn't have job control yet, this isn't a problem now.
3705 * Called with interrupts off.
3713 if (on == doing_jobctl || rootshell == 0)
3717 ofd = fd = open(_PATH_TTY, O_RDWR);
3719 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3720 * That sometimes helps to acquire controlling tty.
3721 * Obviously, a workaround for bugs when someone
3722 * failed to provide a controlling tty to bash! :) */
3728 /* fd is a tty at this point */
3729 fd = fcntl(fd, F_DUPFD, 10);
3730 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3733 goto out; /* F_DUPFD failed */
3734 close_on_exec_on(fd);
3735 while (1) { /* while we are in the background */
3736 pgrp = tcgetpgrp(fd);
3739 ash_msg("can't access tty; job control turned off");
3743 if (pgrp == getpgrp())
3754 xtcsetpgrp(fd, pgrp);
3756 /* turning job control off */
3759 /* was xtcsetpgrp, but this can make exiting ash
3760 * loop forever if pty is already deleted */
3761 tcsetpgrp(fd, pgrp);
3775 static int FAST_FUNC
3776 killcmd(int argc, char **argv)
3778 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3781 if (argv[i][0] == '%') {
3783 * "kill %N" - job kill
3784 * Converting to pgrp / pid kill
3790 jp = getjob(argv[i], 0);
3792 * In jobs started under job control, we signal
3793 * entire process group by kill -PGRP_ID.
3794 * This happens, f.e., in interactive shell.
3796 * Otherwise, we signal each child via
3797 * kill PID1 PID2 PID3.
3799 * sh -c 'sleep 1|sleep 1 & kill %1'
3800 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3801 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3803 n = jp->nprocs; /* can't be 0 (I hope) */
3806 dst = alloca(n * sizeof(int)*4);
3808 for (j = 0; j < n; j++) {
3809 struct procstat *ps = &jp->ps[j];
3810 /* Skip non-running and not-stopped members
3811 * (i.e. dead members) of the job
3813 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3816 * kill_main has matching code to expect
3817 * leading space. Needed to not confuse
3818 * negative pids with "kill -SIGNAL_NO" syntax
3820 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3824 } while (argv[++i]);
3826 return kill_main(argc, argv);
3830 showpipe(struct job *jp /*, FILE *out*/)
3832 struct procstat *ps;
3833 struct procstat *psend;
3835 psend = jp->ps + jp->nprocs;
3836 for (ps = jp->ps + 1; ps < psend; ps++)
3837 printf(" | %s", ps->ps_cmd);
3838 newline_and_flush(stdout);
3839 flush_stdout_stderr();
3844 restartjob(struct job *jp, int mode)
3846 struct procstat *ps;
3852 if (jp->state == JOBDONE)
3854 jp->state = JOBRUNNING;
3855 pgid = jp->ps[0].ps_pid;
3856 if (mode == FORK_FG)
3857 xtcsetpgrp(ttyfd, pgid);
3858 killpg(pgid, SIGCONT);
3862 if (WIFSTOPPED(ps->ps_status)) {
3868 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3873 static int FAST_FUNC
3874 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3880 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3884 jp = getjob(*argv, 1);
3885 if (mode == FORK_BG) {
3886 set_curjob(jp, CUR_RUNNING);
3887 printf("[%d] ", jobno(jp));
3889 out1str(jp->ps[0].ps_cmd);
3890 showpipe(jp /*, stdout*/);
3891 retval = restartjob(jp, mode);
3892 } while (*argv && *++argv);
3898 sprint_status48(char *s, int status, int sigonly)
3904 if (!WIFEXITED(status)) {
3905 if (JOBS && WIFSTOPPED(status))
3906 st = WSTOPSIG(status);
3908 st = WTERMSIG(status);
3910 if (st == SIGINT || st == SIGPIPE)
3912 if (JOBS && WIFSTOPPED(status))
3916 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3917 col = fmtstr(s, 32, strsignal(st));
3918 if (WCOREDUMP(status)) {
3919 strcpy(s + col, " (core dumped)");
3920 col += sizeof(" (core dumped)")-1;
3922 } else if (!sigonly) {
3923 st = WEXITSTATUS(status);
3924 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3931 dowait(int block, struct job *job)
3937 struct job *thisjob;
3939 TRACE(("dowait(0x%x) called\n", block));
3941 /* Do a wait system call. If job control is compiled in, we accept
3942 * stopped processes.
3943 * NB: _not_ safe_waitpid, we need to detect EINTR.
3946 if (block == DOWAIT_NONBLOCK)
3947 wait_flags = WNOHANG;
3949 wait_flags |= WUNTRACED;
3950 pid = waitpid(-1, &status, wait_flags);
3951 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3952 pid, status, errno, strerror(errno)));
3958 for (jp = curjob; jp; jp = jp->prev_job) {
3960 struct procstat *ps;
3961 struct procstat *psend;
3962 if (jp->state == JOBDONE)
3966 psend = ps + jp->nprocs;
3968 if (ps->ps_pid == pid) {
3969 TRACE(("Job %d: changing status of proc %d "
3970 "from 0x%x to 0x%x\n",
3971 jobno(jp), pid, ps->ps_status, status));
3972 ps->ps_status = status;
3975 if (ps->ps_status == -1)
3976 jobstate = JOBRUNNING;
3978 if (jobstate == JOBRUNNING)
3980 if (WIFSTOPPED(ps->ps_status)) {
3981 jp->stopstatus = ps->ps_status;
3982 jobstate = JOBSTOPPED;
3985 } while (++ps < psend);
3989 /* Found the job where one of its processes changed its state.
3990 * Is there at least one live and running process in this job? */
3991 if (jobstate != JOBRUNNING) {
3992 /* No. All live processes in the job are stopped
3993 * (JOBSTOPPED) or there are no live processes (JOBDONE)
3995 thisjob->changed = 1;
3996 if (thisjob->state != jobstate) {
3997 TRACE(("Job %d: changing state from %d to %d\n",
3998 jobno(thisjob), thisjob->state, jobstate));
3999 thisjob->state = jobstate;
4001 if (jobstate == JOBSTOPPED)
4002 set_curjob(thisjob, CUR_STOPPED);
4008 /* The process wasn't found in job list */
4009 if (JOBS && !WIFSTOPPED(status))
4014 if (thisjob && thisjob == job) {
4018 len = sprint_status48(s, status, 1);
4030 showjob(struct job *jp, int mode)
4032 struct procstat *ps;
4033 struct procstat *psend;
4036 char s[16 + 16 + 48];
4037 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4041 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4042 /* just output process (group) id of pipeline */
4043 fprintf(out, "%d\n", ps->ps_pid);
4047 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4052 else if (curjob && jp == curjob->prev_job)
4055 if (mode & SHOW_PIDS)
4056 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4058 psend = ps + jp->nprocs;
4060 if (jp->state == JOBRUNNING) {
4061 strcpy(s + col, "Running");
4062 col += sizeof("Running") - 1;
4064 int status = psend[-1].ps_status;
4065 if (jp->state == JOBSTOPPED)
4066 status = jp->stopstatus;
4067 col += sprint_status48(s + col, status, 0);
4069 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4071 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4072 * or prints several "PID | <cmdN>" lines,
4073 * depending on SHOW_PIDS bit.
4074 * We do not print status of individual processes
4075 * between PID and <cmdN>. bash does it, but not very well:
4076 * first line shows overall job status, not process status,
4077 * making it impossible to know 1st process status.
4081 /* for each process */
4084 if (mode & SHOW_PIDS)
4085 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4087 fprintf(out, "%s%*c%s%s",
4089 33 - col >= 0 ? 33 - col : 0, ' ',
4090 ps == jp->ps ? "" : "| ",
4093 } while (++ps != psend);
4094 newline_and_flush(out);
4098 if (jp->state == JOBDONE) {
4099 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4105 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4106 * statuses have changed since the last call to showjobs.
4113 TRACE(("showjobs(0x%x) called\n", mode));
4115 /* Handle all finished jobs */
4116 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4119 for (jp = curjob; jp; jp = jp->prev_job) {
4120 if (!(mode & SHOW_CHANGED) || jp->changed) {
4126 static int FAST_FUNC
4127 jobscmd(int argc UNUSED_PARAM, char **argv)
4132 while ((m = nextopt("lp")) != '\0') {
4136 mode |= SHOW_ONLY_PGID;
4142 showjob(getjob(*argv, 0), mode);
4152 /* Called only on finished or stopped jobs (no members are running) */
4154 getstatus(struct job *job)
4158 struct procstat *ps;
4160 /* Fetch last member's status */
4161 ps = job->ps + job->nprocs - 1;
4162 status = ps->ps_status;
4164 /* "set -o pipefail" mode: use last _nonzero_ status */
4165 while (status == 0 && --ps >= job->ps)
4166 status = ps->ps_status;
4169 retval = WEXITSTATUS(status);
4170 if (!WIFEXITED(status)) {
4172 retval = WSTOPSIG(status);
4173 if (!WIFSTOPPED(status))
4176 /* XXX: limits number of signals */
4177 retval = WTERMSIG(status);
4179 if (retval == SIGINT)
4185 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4186 jobno(job), job->nprocs, status, retval));
4190 static int FAST_FUNC
4191 waitcmd(int argc UNUSED_PARAM, char **argv)
4202 /* wait for all jobs */
4206 if (!jp) /* no running procs */
4208 if (jp->state == JOBRUNNING)
4214 * "When bash is waiting for an asynchronous command via
4215 * the wait builtin, the reception of a signal for which a trap
4216 * has been set will cause the wait builtin to return immediately
4217 * with an exit status greater than 128, immediately after which
4218 * the trap is executed."
4220 dowait(DOWAIT_BLOCK, NULL); ///DOWAIT_WAITCMD
4221 /* if child sends us a signal *and immediately exits*,
4222 * dowait() returns pid > 0. Check this case,
4223 * not "if (dowait() < 0)"!
4232 if (**argv != '%') {
4233 pid_t pid = number(*argv);
4238 if (job->ps[job->nprocs - 1].ps_pid == pid)
4240 job = job->prev_job;
4243 job = getjob(*argv, 0);
4245 /* loop until process terminated or stopped */
4246 while (job->state == JOBRUNNING) {
4247 dowait(DOWAIT_BLOCK, NULL); ///DOWAIT_WAITCMD
4252 retval = getstatus(job);
4259 retval = 128 + pending_sig;
4268 struct job *jp, *jq;
4270 len = njobs * sizeof(*jp);
4272 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4274 offset = (char *)jp - (char *)jq;
4276 /* Relocate pointers */
4279 jq = (struct job *)((char *)jq + l);
4283 #define joff(p) ((struct job *)((char *)(p) + l))
4284 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4285 if (joff(jp)->ps == &jq->ps0)
4286 jmove(joff(jp)->ps);
4287 if (joff(jp)->prev_job)
4288 jmove(joff(jp)->prev_job);
4298 jp = (struct job *)((char *)jp + len);
4302 } while (--jq >= jp);
4307 * Return a new job structure.
4308 * Called with interrupts off.
4311 makejob(/*union node *node,*/ int nprocs)
4316 for (i = njobs, jp = jobtab; ; jp++) {
4323 if (jp->state != JOBDONE || !jp->waited)
4332 memset(jp, 0, sizeof(*jp));
4334 /* jp->jobctl is a bitfield.
4335 * "jp->jobctl |= jobctl" likely to give awful code */
4339 jp->prev_job = curjob;
4344 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4346 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4353 * Return a string identifying a command (to be printed by the
4356 static char *cmdnextc;
4359 cmdputs(const char *s)
4361 static const char vstype[VSTYPE + 1][3] = {
4362 "", "}", "-", "+", "?", "=",
4363 "%", "%%", "#", "##"
4364 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4367 const char *p, *str;
4371 unsigned char subtype = 0;
4375 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4377 while ((c = *p++) != '\0') {
4385 if ((subtype & VSTYPE) == VSLENGTH)
4391 str = "\"}" + !(quoted & 1);
4398 #if ENABLE_SH_MATH_SUPPORT
4413 if ((subtype & VSTYPE) != VSNORMAL)
4415 str = vstype[subtype & VSTYPE];
4416 if (subtype & VSNUL)
4425 /* These can only happen inside quotes */
4438 while ((c = *str++) != '\0') {
4441 } /* while *p++ not NUL */
4444 USTPUTC('"', nextc);
4450 /* cmdtxt() and cmdlist() call each other */
4451 static void cmdtxt(union node *n);
4454 cmdlist(union node *np, int sep)
4456 for (; np; np = np->narg.next) {
4460 if (sep && np->narg.next)
4466 cmdtxt(union node *n)
4469 struct nodelist *lp;
4480 lp = n->npipe.cmdlist;
4498 cmdtxt(n->nbinary.ch1);
4514 cmdtxt(n->nif.test);
4516 if (n->nif.elsepart) {
4517 cmdtxt(n->nif.ifpart);
4519 n = n->nif.elsepart;
4537 cmdtxt(n->nbinary.ch1);
4547 cmdputs(n->nfor.var);
4549 cmdlist(n->nfor.args, 1);
4554 cmdputs(n->narg.text);
4558 cmdlist(n->ncmd.args, 1);
4559 cmdlist(n->ncmd.redirect, 0);
4572 cmdputs(n->ncase.expr->narg.text);
4574 for (np = n->ncase.cases; np; np = np->nclist.next) {
4575 cmdtxt(np->nclist.pattern);
4577 cmdtxt(np->nclist.body);
4591 #if ENABLE_ASH_BASH_COMPAT
4606 cmdputs(utoa(n->nfile.fd));
4608 if (n->type == NTOFD || n->type == NFROMFD) {
4609 cmdputs(utoa(n->ndup.dupfd));
4618 commandtext(union node *n)
4622 STARTSTACKSTR(cmdnextc);
4624 name = stackblock();
4625 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4626 return ckstrdup(name);
4631 * Fork off a subshell. If we are doing job control, give the subshell its
4632 * own process group. Jp is a job structure that the job is to be added to.
4633 * N is the command that will be evaluated by the child. Both jp and n may
4634 * be NULL. The mode parameter can be one of the following:
4635 * FORK_FG - Fork off a foreground process.
4636 * FORK_BG - Fork off a background process.
4637 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4638 * process group even if job control is on.
4640 * When job control is turned off, background processes have their standard
4641 * input redirected to /dev/null (except for the second and later processes
4644 * Called with interrupts off.
4647 * Clear traps on a fork.
4655 for (tp = trap; tp < &trap[NSIG]; tp++) {
4656 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4657 if (trap_ptr == trap)
4659 /* else: it "belongs" to trap_ptr vector, don't free */
4661 if ((tp - trap) != 0)
4662 setsignal(tp - trap);
4669 /* Lives far away from here, needed for forkchild */
4670 static void closescript(void);
4672 /* Called after fork(), in child */
4673 /* jp and n are NULL when called by openhere() for heredoc support */
4674 static NOINLINE void
4675 forkchild(struct job *jp, union node *n, int mode)
4679 TRACE(("Child shell %d\n", getpid()));
4683 /* man bash: "Non-builtin commands run by bash have signal handlers
4684 * set to the values inherited by the shell from its parent".
4685 * Do we do it correctly? */
4689 if (mode == FORK_NOJOB /* is it `xxx` ? */
4690 && n && n->type == NCMD /* is it single cmd? */
4691 /* && n->ncmd.args->type == NARG - always true? */
4692 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4693 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4694 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4696 TRACE(("Trap hack\n"));
4697 /* Awful hack for `trap` or $(trap).
4699 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4700 * contains an example where "trap" is executed in a subshell:
4702 * save_traps=$(trap)
4704 * eval "$save_traps"
4706 * Standard does not say that "trap" in subshell shall print
4707 * parent shell's traps. It only says that its output
4708 * must have suitable form, but then, in the above example
4709 * (which is not supposed to be normative), it implies that.
4711 * bash (and probably other shell) does implement it
4712 * (traps are reset to defaults, but "trap" still shows them),
4713 * but as a result, "trap" logic is hopelessly messed up:
4716 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4717 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4718 * # true | trap <--- trap is in subshell - no output (ditto)
4719 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4720 * trap -- 'echo Ho' SIGWINCH
4721 * # echo `(trap)` <--- in subshell in subshell - output
4722 * trap -- 'echo Ho' SIGWINCH
4723 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4724 * trap -- 'echo Ho' SIGWINCH
4726 * The rules when to forget and when to not forget traps
4727 * get really complex and nonsensical.
4729 * Our solution: ONLY bare $(trap) or `trap` is special.
4731 /* Save trap handler strings for trap builtin to print */
4732 trap_ptr = xmemdup(trap, sizeof(trap));
4733 /* Fall through into clearing traps */
4737 /* do job control only in root shell */
4739 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4742 if (jp->nprocs == 0)
4745 pgrp = jp->ps[0].ps_pid;
4746 /* this can fail because we are doing it in the parent also */
4748 if (mode == FORK_FG)
4749 xtcsetpgrp(ttyfd, pgrp);
4754 if (mode == FORK_BG) {
4755 /* man bash: "When job control is not in effect,
4756 * asynchronous commands ignore SIGINT and SIGQUIT" */
4759 if (jp->nprocs == 0) {
4761 if (open(bb_dev_null, O_RDONLY) != 0)
4762 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4766 if (iflag) { /* why if iflag only? */
4771 * "In all cases, bash ignores SIGQUIT. Non-builtin
4772 * commands run by bash have signal handlers
4773 * set to the values inherited by the shell
4775 * Take care of the second rule: */
4779 if (n && n->type == NCMD
4780 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4782 TRACE(("Job hack\n"));
4783 /* "jobs": we do not want to clear job list for it,
4784 * instead we remove only _its_ own_ job from job list.
4785 * This makes "jobs .... | cat" more useful.
4791 for (jp = curjob; jp; jp = jp->prev_job)
4796 /* Called after fork(), in parent */
4798 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4801 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4803 TRACE(("In parent shell: child = %d\n", pid));
4805 /* jp is NULL when called by openhere() for heredoc support */
4806 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4812 if (mode != FORK_NOJOB && jp->jobctl) {
4815 if (jp->nprocs == 0)
4818 pgrp = jp->ps[0].ps_pid;
4819 /* This can fail because we are doing it in the child also */
4823 if (mode == FORK_BG) {
4824 backgndpid = pid; /* set $! */
4825 set_curjob(jp, CUR_RUNNING);
4828 struct procstat *ps = &jp->ps[jp->nprocs++];
4831 ps->ps_cmd = nullstr;
4833 if (doing_jobctl && n)
4834 ps->ps_cmd = commandtext(n);
4839 /* jp and n are NULL when called by openhere() for heredoc support */
4841 forkshell(struct job *jp, union node *n, int mode)
4845 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4848 TRACE(("Fork failed, errno=%d", errno));
4851 ash_msg_and_raise_error("can't fork");
4854 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4855 forkchild(jp, n, mode);
4857 forkparent(jp, n, mode, pid);
4863 * Wait for job to finish.
4865 * Under job control we have the problem that while a child process
4866 * is running interrupts generated by the user are sent to the child
4867 * but not to the shell. This means that an infinite loop started by
4868 * an interactive user may be hard to kill. With job control turned off,
4869 * an interactive user may place an interactive program inside a loop.
4870 * If the interactive program catches interrupts, the user doesn't want
4871 * these interrupts to also abort the loop. The approach we take here
4872 * is to have the shell ignore interrupt signals while waiting for a
4873 * foreground process to terminate, and then send itself an interrupt
4874 * signal if the child process was terminated by an interrupt signal.
4875 * Unfortunately, some programs want to do a bit of cleanup and then
4876 * exit on interrupt; unless these processes terminate themselves by
4877 * sending a signal to themselves (instead of calling exit) they will
4878 * confuse this approach.
4880 * Called with interrupts off.
4883 waitforjob(struct job *jp)
4887 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4890 while (jp->state == JOBRUNNING) {
4891 /* In non-interactive shells, we _can_ get
4892 * a keyboard signal here and be EINTRed,
4893 * but we just loop back, waiting for command to complete.
4896 * "If bash is waiting for a command to complete and receives
4897 * a signal for which a trap has been set, the trap
4898 * will not be executed until the command completes."
4900 * Reality is that even if trap is not set, bash
4901 * will not act on the signal until command completes.
4902 * Try this. sleep5intoff.c:
4903 * #include <signal.h>
4904 * #include <unistd.h>
4907 * sigemptyset(&set);
4908 * sigaddset(&set, SIGINT);
4909 * sigaddset(&set, SIGQUIT);
4910 * sigprocmask(SIG_BLOCK, &set, NULL);
4914 * $ bash -c './sleep5intoff; echo hi'
4915 * ^C^C^C^C <--- pressing ^C once a second
4917 * $ bash -c './sleep5intoff; echo hi'
4918 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4921 dowait(DOWAIT_BLOCK, jp);
4928 xtcsetpgrp(ttyfd, rootpid);
4930 * This is truly gross.
4931 * If we're doing job control, then we did a TIOCSPGRP which
4932 * caused us (the shell) to no longer be in the controlling
4933 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4934 * intuit from the subprocess exit status whether a SIGINT
4935 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4937 if (jp->sigint) /* TODO: do the same with all signals */
4938 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4940 if (jp->state == JOBDONE)
4947 * return 1 if there are stopped jobs, otherwise 0
4959 if (jp && jp->state == JOBSTOPPED) {
4960 out2str("You have stopped jobs.\n");
4970 * Code for dealing with input/output redirection.
4975 #define EMPTY -2 /* marks an unused slot in redirtab */
4976 #define CLOSED -3 /* marks a slot of previously-closed fd */
4979 * Open a file in noclobber mode.
4980 * The code was copied from bash.
4983 noclobberopen(const char *fname)
4986 struct stat finfo, finfo2;
4989 * If the file exists and is a regular file, return an error
4992 r = stat(fname, &finfo);
4993 if (r == 0 && S_ISREG(finfo.st_mode)) {
4999 * If the file was not present (r != 0), make sure we open it
5000 * exclusively so that if it is created before we open it, our open
5001 * will fail. Make sure that we do not truncate an existing file.
5002 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5003 * file was not a regular file, we leave O_EXCL off.
5006 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5007 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5009 /* If the open failed, return the file descriptor right away. */
5014 * OK, the open succeeded, but the file may have been changed from a
5015 * non-regular file to a regular file between the stat and the open.
5016 * We are assuming that the O_EXCL open handles the case where FILENAME
5017 * did not exist and is symlinked to an existing file between the stat
5022 * If we can open it and fstat the file descriptor, and neither check
5023 * revealed that it was a regular file, and the file has not been
5024 * replaced, return the file descriptor.
5026 if (fstat(fd, &finfo2) == 0
5027 && !S_ISREG(finfo2.st_mode)
5028 && finfo.st_dev == finfo2.st_dev
5029 && finfo.st_ino == finfo2.st_ino
5034 /* The file has been replaced. badness. */
5041 * Handle here documents. Normally we fork off a process to write the
5042 * data to a pipe. If the document is short, we can stuff the data in
5043 * the pipe without forking.
5045 /* openhere needs this forward reference */
5046 static void expandhere(union node *arg, int fd);
5048 openhere(union node *redir)
5054 ash_msg_and_raise_error("pipe call failed");
5055 if (redir->type == NHERE) {
5056 len = strlen(redir->nhere.doc->narg.text);
5057 if (len <= PIPE_BUF) {
5058 full_write(pip[1], redir->nhere.doc->narg.text, len);
5062 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5065 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5066 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5067 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5068 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5069 signal(SIGPIPE, SIG_DFL);
5070 if (redir->type == NHERE)
5071 full_write(pip[1], redir->nhere.doc->narg.text, len);
5073 expandhere(redir->nhere.doc, pip[1]);
5074 _exit(EXIT_SUCCESS);
5082 openredirect(union node *redir)
5087 switch (redir->nfile.type) {
5088 /* Can't happen, our single caller does this itself */
5094 return openhere(redir);
5097 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5098 * allocated space. Do it only when we know it is safe.
5100 fname = redir->nfile.expfname;
5102 switch (redir->nfile.type) {
5108 f = open(fname, O_RDONLY);
5113 f = open(fname, O_RDWR|O_CREAT, 0666);
5118 #if ENABLE_ASH_BASH_COMPAT
5121 /* Take care of noclobber mode. */
5123 f = noclobberopen(fname);
5130 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5135 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5143 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5145 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5149 * Copy a file descriptor to be >= 10. Throws exception on error.
5157 newfd = fcntl(from, F_DUPFD, 10);
5158 err = newfd < 0 ? errno : 0;
5161 ash_msg_and_raise_error("%d: %m", from);
5163 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5169 dup2_or_raise(int from, int to)
5173 newfd = (from != to) ? dup2(from, to) : to;
5175 /* Happens when source fd is not open: try "echo >&99" */
5176 ash_msg_and_raise_error("%d: %m", from);
5181 /* Struct def and variable are moved down to the first usage site */
5186 struct redirtab *next;
5188 struct two_fd_t two_fd[];
5190 #define redirlist (G_var.redirlist)
5192 COPYFD_RESTORE = (int)~(INT_MAX),
5196 need_to_remember(struct redirtab *rp, int fd)
5200 if (!rp) /* remembering was not requested */
5203 for (i = 0; i < rp->pair_count; i++) {
5204 if (rp->two_fd[i].orig == fd) {
5205 /* already remembered */
5212 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5214 is_hidden_fd(struct redirtab *rp, int fd)
5217 struct parsefile *pf;
5221 /* Check open scripts' fds */
5224 /* We skip pf_fd == 0 case because of the following case:
5225 * $ ash # running ash interactively
5227 * and in script.sh: "exec 9>&0".
5228 * Even though top-level pf_fd _is_ 0,
5229 * it's still ok to use it: "read" builtin uses it,
5230 * why should we cripple "exec" builtin?
5232 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5240 /* Check saved fds of redirects */
5241 fd |= COPYFD_RESTORE;
5242 for (i = 0; i < rp->pair_count; i++) {
5243 if (rp->two_fd[i].copy == fd) {
5251 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5252 * old file descriptors are stashed away so that the redirection can be
5253 * undone by calling popredir.
5255 /* flags passed to redirect */
5256 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5257 #define REDIR_SAVEFD2 03 /* set preverrout */
5259 redirect(union node *redir, int flags)
5261 struct redirtab *sv;
5266 int copied_fd2 = -1;
5275 if (flags & REDIR_PUSH) {
5276 union node *tmp = redir;
5279 #if ENABLE_ASH_BASH_COMPAT
5280 if (tmp->nfile.type == NTO2)
5283 tmp = tmp->nfile.next;
5285 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5286 sv->next = redirlist;
5287 sv->pair_count = sv_pos;
5289 while (sv_pos > 0) {
5291 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5297 fd = redir->nfile.fd;
5298 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5299 right_fd = redir->ndup.dupfd;
5300 //bb_error_msg("doing %d > %d", fd, right_fd);
5301 /* redirect from/to same file descriptor? */
5304 /* "echo >&10" and 10 is a fd opened to a sh script? */
5305 if (is_hidden_fd(sv, right_fd)) {
5306 errno = EBADF; /* as if it is closed */
5307 ash_msg_and_raise_error("%d: %m", right_fd);
5311 newfd = openredirect(redir); /* always >= 0 */
5313 /* Descriptor wasn't open before redirect.
5314 * Mark it for close in the future */
5315 if (need_to_remember(sv, fd)) {
5316 goto remember_to_close;
5321 #if ENABLE_ASH_BASH_COMPAT
5324 if (need_to_remember(sv, fd)) {
5325 /* Copy old descriptor */
5326 /* Careful to not accidentally "save"
5327 * to the same fd as right side fd in N>&M */
5328 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5329 i = fcntl(fd, F_DUPFD, minfd);
5330 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5331 * are closed in popredir() in the child, preventing them from leaking
5332 * into child. (popredir() also cleans up the mess in case of failures)
5337 /* Strange error (e.g. "too many files" EMFILE?) */
5341 ash_msg_and_raise_error("%d: %m", fd);
5344 /* EBADF: it is not open - good, remember to close it */
5347 } else { /* fd is open, save its copy */
5348 /* "exec fd>&-" should not close fds
5349 * which point to script file(s).
5350 * Force them to be restored afterwards */
5351 if (is_hidden_fd(sv, fd))
5352 i |= COPYFD_RESTORE;
5356 sv->two_fd[sv_pos].orig = fd;
5357 sv->two_fd[sv_pos].copy = i;
5361 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5362 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5363 /* Don't want to trigger debugging */
5367 dup2_or_raise(redir->ndup.dupfd, fd);
5369 } else if (fd != newfd) { /* move newfd to fd */
5370 dup2_or_raise(newfd, fd);
5371 #if ENABLE_ASH_BASH_COMPAT
5372 if (!(redir->nfile.type == NTO2 && fd == 2))
5376 #if ENABLE_ASH_BASH_COMPAT
5377 if (redir->nfile.type == NTO2 && fd == 1) {
5378 /* We already redirected it to fd 1, now copy it to 2 */
5384 } while ((redir = redir->nfile.next) != NULL);
5387 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5388 preverrout_fd = copied_fd2;
5392 * Undo the effects of the last redirection.
5395 popredir(int drop, int restore)
5397 struct redirtab *rp;
5400 if (redirlist == NULL)
5404 for (i = 0; i < rp->pair_count; i++) {
5405 int fd = rp->two_fd[i].orig;
5406 int copy = rp->two_fd[i].copy;
5407 if (copy == CLOSED) {
5412 if (copy != EMPTY) {
5413 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5414 copy &= ~COPYFD_RESTORE;
5416 dup2_or_raise(copy, fd);
5418 close(copy & ~COPYFD_RESTORE);
5421 redirlist = rp->next;
5427 * Undo all redirections. Called on error or interrupt.
5431 redirectsafe(union node *redir, int flags)
5434 volatile int saveint;
5435 struct jmploc *volatile savehandler = exception_handler;
5436 struct jmploc jmploc;
5439 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5440 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5442 exception_handler = &jmploc;
5443 redirect(redir, flags);
5445 exception_handler = savehandler;
5446 if (err && exception_type != EXERROR)
5447 longjmp(exception_handler->loc, 1);
5448 RESTORE_INT(saveint);
5453 /* ============ Routines to expand arguments to commands
5455 * We have to deal with backquotes, shell variables, and file metacharacters.
5458 #if ENABLE_SH_MATH_SUPPORT
5460 ash_arith(const char *s)
5462 arith_state_t math_state;
5465 math_state.lookupvar = lookupvar;
5466 math_state.setvar = setvar0;
5467 //math_state.endofname = endofname;
5470 result = arith(&math_state, s);
5471 if (math_state.errmsg)
5472 ash_msg_and_raise_error(math_state.errmsg);
5482 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5483 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5484 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5485 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5486 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5487 * POSIX says for this case:
5488 * Pathname expansion shall not be performed on the word by a
5489 * non-interactive shell; an interactive shell may perform it, but shall
5490 * do so only when the expansion would result in one word.
5491 * Currently, our code complies to the above rule by never globbing
5492 * redirection filenames.
5493 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5494 * (this means that on a typical Linux distro, bash almost always
5495 * performs globbing, and thus diverges from what we do).
5497 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5498 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5499 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5500 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5501 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5505 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5506 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5507 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5508 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5509 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5511 /* Add CTLESC when necessary. */
5512 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5513 /* Do not skip NUL characters. */
5514 #define QUOTES_KEEPNUL EXP_TILDE
5517 * Structure specifying which parts of the string should be searched
5518 * for IFS characters.
5521 struct ifsregion *next; /* next region in list */
5522 int begoff; /* offset of start of region */
5523 int endoff; /* offset of end of region */
5524 int nulonly; /* search for nul bytes only */
5528 struct strlist *list;
5529 struct strlist **lastp;
5532 /* output of current string */
5533 static char *expdest;
5534 /* list of back quote expressions */
5535 static struct nodelist *argbackq;
5536 /* first struct in list of ifs regions */
5537 static struct ifsregion ifsfirst;
5538 /* last struct in list */
5539 static struct ifsregion *ifslastp;
5540 /* holds expanded arg list */
5541 static struct arglist exparg;
5546 #if !ENABLE_SH_MATH_SUPPORT
5547 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5548 typedef long arith_t;
5549 # define ARITH_FMT "%ld"
5556 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5557 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5558 STADJUST(len, expdest);
5563 * Break the argument string into pieces based upon IFS and add the
5564 * strings to the argument list. The regions of the string to be
5565 * searched for IFS characters have been stored by recordregion.
5568 ifsbreakup(char *string, struct arglist *arglist)
5570 struct ifsregion *ifsp;
5575 const char *ifs, *realifs;
5580 if (ifslastp != NULL) {
5583 realifs = ifsset() ? ifsval() : defifs;
5586 p = string + ifsp->begoff;
5587 nulonly = ifsp->nulonly;
5588 ifs = nulonly ? nullstr : realifs;
5590 while (p < string + ifsp->endoff) {
5592 if ((unsigned char)*p == CTLESC)
5594 if (!strchr(ifs, *p)) {
5599 ifsspc = (strchr(defifs, *p) != NULL);
5600 /* Ignore IFS whitespace at start */
5601 if (q == start && ifsspc) {
5607 sp = stzalloc(sizeof(*sp));
5609 *arglist->lastp = sp;
5610 arglist->lastp = &sp->next;
5614 if (p >= string + ifsp->endoff) {
5618 if ((unsigned char)*p == CTLESC)
5620 if (strchr(ifs, *p) == NULL) {
5624 if (strchr(defifs, *p) == NULL) {
5639 } while (ifsp != NULL);
5648 sp = stzalloc(sizeof(*sp));
5650 *arglist->lastp = sp;
5651 arglist->lastp = &sp->next;
5657 struct ifsregion *p = ifsfirst.next;
5664 struct ifsregion *ifsp;
5669 ifsfirst.next = NULL;
5676 esclen(const char *start, const char *p)
5680 while (p > start && (unsigned char)*--p == CTLESC) {
5687 * Remove any CTLESC characters from a string.
5690 rmescapes(char *str, int flag)
5692 static const char qchars[] ALIGN1 = {
5693 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5697 unsigned protect_against_glob;
5699 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5701 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5707 if (flag & RMESCAPE_ALLOC) {
5708 size_t len = p - str;
5709 size_t fulllen = len + strlen(p) + 1;
5711 if (flag & RMESCAPE_GROW) {
5712 int strloc = str - (char *)stackblock();
5713 r = makestrspace(fulllen, expdest);
5714 /* p and str may be invalidated by makestrspace */
5715 str = (char *)stackblock() + strloc;
5717 } else if (flag & RMESCAPE_HEAP) {
5718 r = ckmalloc(fulllen);
5720 r = stalloc(fulllen);
5724 q = (char *)memcpy(q, str, len) + len;
5729 globbing = flag & RMESCAPE_GLOB;
5730 protect_against_glob = globbing;
5732 if ((unsigned char)*p == CTLQUOTEMARK) {
5733 // Note: both inquotes and protect_against_glob only affect whether
5734 inquotes = ~inquotes;
5736 protect_against_glob = globbing;
5739 if ((unsigned char)*p == CTLESC) {
5743 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5745 if (protect_against_glob) {
5748 } else if (*p == '\\' && !inquotes) {
5749 /* naked back slash */
5750 protect_against_glob = 0;
5753 #if ENABLE_ASH_BASH_COMPAT
5754 else if (*p == '/' && slash) {
5755 /* stop handling globbing and mark location of slash */
5756 globbing = slash = 0;
5760 protect_against_glob = globbing;
5765 if (flag & RMESCAPE_GROW) {
5767 STADJUST(q - r + 1, expdest);
5771 #define pmatch(a, b) !fnmatch((a), (b), 0)
5774 * Prepare a pattern for a expmeta (internal glob(3)) call.
5776 * Returns an stalloced string.
5779 preglob(const char *pattern, int flag)
5781 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5785 * Put a string on the stack.
5788 memtodest(const char *p, size_t len, int syntax, int quotes)
5795 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5798 unsigned char c = *p++;
5800 int n = SIT(c, syntax);
5801 if ((quotes & QUOTES_ESC)
5803 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5809 } else if (!(quotes & QUOTES_KEEPNUL))
5818 strtodest(const char *p, int syntax, int quotes)
5820 size_t len = strlen(p);
5821 memtodest(p, len, syntax, quotes);
5826 * Record the fact that we have to scan this region of the
5827 * string for IFS characters.
5830 recordregion(int start, int end, int nulonly)
5832 struct ifsregion *ifsp;
5834 if (ifslastp == NULL) {
5838 ifsp = ckzalloc(sizeof(*ifsp));
5839 /*ifsp->next = NULL; - ckzalloc did it */
5840 ifslastp->next = ifsp;
5844 ifslastp->begoff = start;
5845 ifslastp->endoff = end;
5846 ifslastp->nulonly = nulonly;
5850 removerecordregions(int endoff)
5852 if (ifslastp == NULL)
5855 if (ifsfirst.endoff > endoff) {
5856 while (ifsfirst.next) {
5857 struct ifsregion *ifsp;
5859 ifsp = ifsfirst.next->next;
5860 free(ifsfirst.next);
5861 ifsfirst.next = ifsp;
5864 if (ifsfirst.begoff > endoff) {
5867 ifslastp = &ifsfirst;
5868 ifsfirst.endoff = endoff;
5873 ifslastp = &ifsfirst;
5874 while (ifslastp->next && ifslastp->next->begoff < endoff)
5875 ifslastp = ifslastp->next;
5876 while (ifslastp->next) {
5877 struct ifsregion *ifsp;
5879 ifsp = ifslastp->next->next;
5880 free(ifslastp->next);
5881 ifslastp->next = ifsp;
5884 if (ifslastp->endoff > endoff)
5885 ifslastp->endoff = endoff;
5889 exptilde(char *startp, char *p, int flags)
5895 int quotes = flags & QUOTES_ESC;
5899 while ((c = *++p) != '\0') {
5906 if (flags & EXP_VARTILDE)
5916 if (*name == '\0') {
5917 home = lookupvar("HOME");
5919 pw = getpwnam(name);
5924 if (!home || !*home)
5927 strtodest(home, SQSYNTAX, quotes);
5935 * Execute a command inside back quotes. If it's a builtin command, we
5936 * want to save its output in a block obtained from malloc. Otherwise
5937 * we fork off a subprocess and get the output of the command via a pipe.
5938 * Should be called with interrupts off.
5940 struct backcmd { /* result of evalbackcmd */
5941 int fd; /* file descriptor to read from */
5942 int nleft; /* number of chars in buffer */
5943 char *buf; /* buffer */
5944 struct job *jp; /* job structure for command */
5947 /* These forward decls are needed to use "eval" code for backticks handling: */
5948 #define EV_EXIT 01 /* exit after evaluating tree */
5949 static int evaltree(union node *, int);
5951 static void FAST_FUNC
5952 evalbackcmd(union node *n, struct backcmd *result)
5966 ash_msg_and_raise_error("pipe call failed");
5967 jp = makejob(/*n,*/ 1);
5968 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5974 dup2_or_raise(pip[1], 1);
5977 /* TODO: eflag clearing makes the following not abort:
5978 * ash -c 'set -e; z=$(false;echo foo); echo $z'
5979 * which is what bash does (unless it is in POSIX mode).
5980 * dash deleted "eflag = 0" line in the commit
5981 * Date: Mon, 28 Jun 2010 17:11:58 +1000
5982 * [EVAL] Don't clear eflag in evalbackcmd
5983 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
5987 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5992 result->fd = pip[0];
5996 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5997 result->fd, result->buf, result->nleft, result->jp));
6001 * Expand stuff in backwards quotes.
6004 expbackq(union node *cmd, int flag)
6012 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6013 struct stackmark smark;
6016 startloc = expdest - (char *)stackblock();
6017 pushstackmark(&smark, startloc);
6018 evalbackcmd(cmd, &in);
6019 popstackmark(&smark);
6026 memtodest(p, i, syntax, flag & QUOTES_ESC);
6030 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6031 TRACE(("expbackq: read returns %d\n", i));
6040 back_exitstatus = waitforjob(in.jp);
6044 /* Eat all trailing newlines */
6046 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6050 if (!(flag & EXP_QUOTED))
6051 recordregion(startloc, dest - (char *)stackblock(), 0);
6052 TRACE(("evalbackq: size:%d:'%.*s'\n",
6053 (int)((dest - (char *)stackblock()) - startloc),
6054 (int)((dest - (char *)stackblock()) - startloc),
6055 stackblock() + startloc));
6058 #if ENABLE_SH_MATH_SUPPORT
6060 * Expand arithmetic expression. Backup to start of expression,
6061 * evaluate, place result in (backed up) result, adjust string position.
6073 * This routine is slightly over-complicated for
6074 * efficiency. Next we scan backwards looking for the
6075 * start of arithmetic.
6077 start = stackblock();
6084 while ((unsigned char)*p != CTLARI) {
6088 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6093 esc = esclen(start, p);
6103 removerecordregions(begoff);
6107 if (flag & QUOTES_ESC)
6108 rmescapes(p + 1, 0);
6110 len = cvtnum(ash_arith(p + 1));
6112 if (!(flag & EXP_QUOTED))
6113 recordregion(begoff, begoff + len, 0);
6117 /* argstr needs it */
6118 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6121 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6122 * characters to allow for further processing. Otherwise treat
6123 * $@ like $* since no splitting will be performed.
6125 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6126 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6127 * for correct expansion of "B=$A" word.
6130 argstr(char *p, int flags, struct strlist *var_str_list)
6132 static const char spclchars[] ALIGN1 = {
6140 #if ENABLE_SH_MATH_SUPPORT
6145 const char *reject = spclchars;
6146 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6151 if (!(flags & EXP_VARTILDE)) {
6153 } else if (flags & EXP_VARTILDE2) {
6158 if (flags & EXP_TILDE) {
6161 flags &= ~EXP_TILDE;
6165 p = exptilde(p, q, flags);
6168 startloc = expdest - (char *)stackblock();
6172 length += strcspn(p + length, reject);
6176 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6178 /* c == '=' || c == ':' || c == CTLENDARI */
6184 expdest = stack_nputstr(p, length, expdest);
6185 newloc = expdest - (char *)stackblock();
6186 if (breakall && !inquotes && newloc > startloc) {
6187 recordregion(startloc, newloc, 0);
6198 if (flags & EXP_VARTILDE2) {
6202 flags |= EXP_VARTILDE2;
6207 * sort of a hack - expand tildes in variable
6208 * assignments (after the first '=' and after ':'s).
6217 case CTLENDVAR: /* ??? */
6220 inquotes ^= EXP_QUOTED;
6221 /* "$@" syntax adherence hack */
6222 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6223 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6227 if (flags & QUOTES_ESC) {
6238 * Quoted parameter expansion pattern: remove quote
6239 * unless inside inner quotes or we have a literal
6242 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6243 EXP_QPAT && *p != '\\')
6248 TRACE(("argstr: evalvar('%s')\n", p));
6249 p = evalvar(p, flags | inquotes, var_str_list);
6250 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6253 expbackq(argbackq->n, flags | inquotes);
6254 argbackq = argbackq->next;
6256 #if ENABLE_SH_MATH_SUPPORT
6259 expari(flags | inquotes);
6268 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6269 char *pattern, int quotes, int zero)
6278 const char *s = loc2;
6285 match = pmatch(pattern, s);
6290 if (quotes && (unsigned char)*loc == CTLESC)
6299 scanright(char *startp, char *rmesc, char *rmescend,
6300 char *pattern, int quotes, int match_at_start)
6302 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6303 int try2optimize = match_at_start;
6309 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6310 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6311 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6313 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6314 * and on each iteration they go back two/one char until they reach the beginning.
6315 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6317 /* TODO: document in what other circumstances we are called. */
6319 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6322 const char *s = loc2;
6323 if (match_at_start) {
6327 match = pmatch(pattern, s);
6328 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6332 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6334 /* Maybe we can optimize this:
6335 * if pattern ends with unescaped *, we can avoid checking
6336 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6337 * it wont match truncated "raw_value_of_" strings too.
6339 unsigned plen = strlen(pattern);
6340 /* Does it end with "*"? */
6341 if (plen != 0 && pattern[--plen] == '*') {
6342 /* "xxxx*" is not escaped */
6343 /* "xxx\*" is escaped */
6344 /* "xx\\*" is not escaped */
6345 /* "x\\\*" is escaped */
6347 while (plen != 0 && pattern[--plen] == '\\')
6350 break; /* ends with unescaped "*" */
6358 esc = esclen(startp, loc);
6369 static void varunset(const char *, const char *, const char *, int) NORETURN;
6371 varunset(const char *end, const char *var, const char *umsg, int varflags)
6377 msg = "parameter not set";
6379 if ((unsigned char)*end == CTLENDVAR) {
6380 if (varflags & VSNUL)
6386 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6390 subevalvar(char *p, char *varname, int strloc, int subtype,
6391 int startloc, int varflags, int flag, struct strlist *var_str_list)
6393 struct nodelist *saveargbackq = argbackq;
6394 int quotes = flag & QUOTES_ESC;
6397 char *rmesc, *rmescend;
6399 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6400 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6401 int amount, resetloc;
6402 IF_ASH_BASH_COMPAT(int workloc;)
6404 char *(*scan)(char*, char*, char*, char*, int, int);
6406 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6407 // p, varname, strloc, subtype, startloc, varflags, quotes);
6409 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6410 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6412 STPUTC('\0', expdest);
6413 argbackq = saveargbackq;
6414 startp = (char *)stackblock() + startloc;
6418 setvar0(varname, startp);
6419 amount = startp - expdest;
6420 STADJUST(amount, expdest);
6424 varunset(p, varname, startp, varflags);
6427 #if ENABLE_ASH_BASH_COMPAT
6429 //TODO: support more general format ${v:EXPR:EXPR},
6430 // where EXPR follows $(()) rules
6431 loc = str = stackblock() + strloc;
6432 /* Read POS in ${var:POS:LEN} */
6433 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6434 len = str - startp - 1;
6436 /* *loc != '\0', guaranteed by parser */
6440 /* Adjust the length by the number of escapes */
6441 for (ptr = startp; ptr < (str - 1); ptr++) {
6442 if ((unsigned char)*ptr == CTLESC) {
6450 if (*loc++ == ':') {
6454 /* Skip POS in ${var:POS:LEN} */
6456 while (*loc && *loc != ':') {
6458 * bash complains on: var=qwe; echo ${var:1a:123}
6460 ash_msg_and_raise_error(msg_illnum, str);
6464 if (*loc++ == ':') {
6469 /* ${VAR:$((-n)):l} starts n chars from the end */
6470 pos = orig_len + pos;
6472 if ((unsigned)pos >= orig_len) {
6473 /* apart from obvious ${VAR:999999:l},
6474 * covers ${VAR:$((-9999999)):l} - result is ""
6480 if (len > (orig_len - pos))
6481 len = orig_len - pos;
6483 for (str = startp; pos; str++, pos--) {
6484 if (quotes && (unsigned char)*str == CTLESC)
6487 for (loc = startp; len; len--) {
6488 if (quotes && (unsigned char)*str == CTLESC)
6493 amount = loc - expdest;
6494 STADJUST(amount, expdest);
6499 resetloc = expdest - (char *)stackblock();
6501 /* We'll comeback here if we grow the stack while handling
6502 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6503 * stack will need rebasing, and we'll need to remove our work
6506 IF_ASH_BASH_COMPAT(restart:)
6508 amount = expdest - ((char *)stackblock() + resetloc);
6509 STADJUST(-amount, expdest);
6510 startp = (char *)stackblock() + startloc;
6513 rmescend = (char *)stackblock() + strloc;
6515 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6516 if (rmesc != startp) {
6518 startp = (char *)stackblock() + startloc;
6522 str = (char *)stackblock() + strloc;
6524 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6525 * The result is a_\_z_c (not a\_\_z_c)!
6527 * The search pattern and replace string treat backslashes differently!
6528 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6529 * and string. It's only used on the first call.
6531 preglob(str, IF_ASH_BASH_COMPAT(
6532 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6533 RMESCAPE_SLASH :) 0);
6535 #if ENABLE_ASH_BASH_COMPAT
6536 workloc = expdest - (char *)stackblock();
6537 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6541 repl = strchr(str, CTLESC);
6547 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6549 /* If there's no pattern to match, return the expansion unmolested */
6558 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6559 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6561 /* No match, advance */
6562 char *restart_detect = stackblock();
6564 STPUTC(*idx, expdest);
6565 if (quotes && (unsigned char)*idx == CTLESC) {
6568 STPUTC(*idx, expdest);
6570 if (stackblock() != restart_detect)
6575 /* continue; - prone to quadratic behavior, smarter code: */
6578 if (str[0] == '*') {
6579 /* Pattern is "*foo". If "*foo" does not match "long_string",
6580 * it would never match "ong_string" etc, no point in trying.
6587 if (subtype == VSREPLACEALL) {
6589 if (quotes && (unsigned char)*idx == CTLESC)
6598 //bb_error_msg("repl:'%s'", repl);
6599 for (loc = (char*)repl; *loc; loc++) {
6600 char *restart_detect = stackblock();
6601 if (quotes && *loc == '\\') {
6602 STPUTC(CTLESC, expdest);
6605 STPUTC(*loc, expdest);
6606 if (stackblock() != restart_detect)
6611 if (subtype == VSREPLACE) {
6612 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6614 char *restart_detect = stackblock();
6615 STPUTC(*idx, expdest);
6616 if (stackblock() != restart_detect)
6625 /* We've put the replaced text into a buffer at workloc, now
6626 * move it to the right place and adjust the stack.
6628 STPUTC('\0', expdest);
6629 startp = (char *)stackblock() + startloc;
6630 memmove(startp, (char *)stackblock() + workloc, len + 1);
6631 //bb_error_msg("startp:'%s'", startp);
6632 amount = expdest - (startp + len);
6633 STADJUST(-amount, expdest);
6636 #endif /* ENABLE_ASH_BASH_COMPAT */
6638 subtype -= VSTRIMRIGHT;
6640 if (subtype < 0 || subtype > 7)
6643 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6644 zero = subtype >> 1;
6645 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6646 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6648 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6651 memmove(startp, loc, str - loc);
6652 loc = startp + (str - loc) - 1;
6655 amount = loc - expdest;
6656 STADJUST(amount, expdest);
6662 * Add the value of a specialized variable to the stack string.
6663 * name parameter (examples):
6664 * ash -c 'echo $1' name:'1='
6665 * ash -c 'echo $qwe' name:'qwe='
6666 * ash -c 'echo $$' name:'$='
6667 * ash -c 'echo ${$}' name:'$='
6668 * ash -c 'echo ${$##q}' name:'$=q'
6669 * ash -c 'echo ${#$}' name:'$='
6670 * note: examples with bad shell syntax:
6671 * ash -c 'echo ${#$1}' name:'$=1'
6672 * ash -c 'echo ${#1#}' name:'1=#'
6674 static NOINLINE ssize_t
6675 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6682 int quoted = *quotedp;
6683 int subtype = varflags & VSTYPE;
6684 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6685 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6688 sep = (flags & EXP_FULL) << CHAR_BIT;
6689 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6699 num = shellparam.nparam;
6707 goto check_1char_name;
6709 expdest = makestrspace(NOPTS, expdest);
6710 for (i = NOPTS - 1; i >= 0; i--) {
6712 USTPUTC(optletters(i), expdest);
6718 /* handles cases similar to ${#$1} */
6719 if (name[2] != '\0')
6720 raise_error_syntax("bad substitution");
6733 sep |= ifsset() ? ifsval()[0] : ' ';
6740 while ((p = *ap++) != NULL) {
6741 len += strtodest(p, syntax, quotes);
6745 memtodest(&sepc, 1, syntax, quotes);
6760 num = atoi(name); /* number(name) fails on ${N#str} etc */
6761 if (num < 0 || num > shellparam.nparam)
6763 p = num ? shellparam.p[num - 1] : arg0;
6766 /* NB: name has form "VAR=..." */
6768 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6769 * which should be considered before we check variables. */
6771 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6775 str = var_str_list->text;
6776 eq = strchr(str, '=');
6777 if (!eq) /* stop at first non-assignment */
6780 if (name_len == (unsigned)(eq - str)
6781 && strncmp(str, name, name_len) == 0
6784 /* goto value; - WRONG! */
6785 /* think "A=1 A=2 B=$A" */
6787 var_str_list = var_str_list->next;
6788 } while (var_str_list);
6792 p = lookupvar(name);
6797 len = strtodest(p, syntax, quotes);
6798 #if ENABLE_UNICODE_SUPPORT
6799 if (subtype == VSLENGTH && len > 0) {
6800 reinit_unicode_for_ash();
6801 if (unicode_status == UNICODE_ON) {
6802 STADJUST(-len, expdest);
6804 len = unicode_strlen(p);
6812 STADJUST(-len, expdest);
6817 * Expand a variable, and return a pointer to the next character in the
6821 evalvar(char *p, int flag, struct strlist *var_str_list)
6832 varflags = (unsigned char) *p++;
6833 subtype = varflags & VSTYPE;
6836 raise_error_syntax("bad substitution");
6838 quoted = flag & EXP_QUOTED;
6840 easy = (!quoted || (*var == '@' && shellparam.nparam));
6841 startloc = expdest - (char *)stackblock();
6842 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6845 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6846 if (varflags & VSNUL)
6849 if (subtype == VSPLUS) {
6850 varlen = -1 - varlen;
6854 if (subtype == VSMINUS) {
6859 flag | EXP_TILDE | EXP_WORD,
6867 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6871 subevalvar(p, var, 0, subtype, startloc, varflags,
6872 flag & ~QUOTES_ESC, var_str_list);
6875 * Remove any recorded regions beyond
6878 removerecordregions(startloc);
6882 if (varlen < 0 && uflag)
6883 varunset(p, var, 0, 0);
6885 if (subtype == VSLENGTH) {
6886 cvtnum(varlen > 0 ? varlen : 0);
6890 if (subtype == VSNORMAL) {
6894 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6903 case VSTRIMRIGHTMAX:
6904 #if ENABLE_ASH_BASH_COMPAT
6917 * Terminate the string and start recording the pattern
6920 STPUTC('\0', expdest);
6921 patloc = expdest - (char *)stackblock();
6922 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6923 startloc, varflags, flag, var_str_list)) {
6924 int amount = expdest - (
6925 (char *)stackblock() + patloc - 1
6927 STADJUST(-amount, expdest);
6929 /* Remove any recorded regions beyond start of variable */
6930 removerecordregions(startloc);
6935 if (subtype != VSNORMAL) { /* skip to end of alternative */
6938 unsigned char c = *p++;
6941 else if (c == CTLBACKQ) {
6943 argbackq = argbackq->next;
6944 } else if (c == CTLVAR) {
6945 if ((*p++ & VSTYPE) != VSNORMAL)
6947 } else if (c == CTLENDVAR) {
6957 * Add a file name to the list.
6960 addfname(const char *name)
6964 sp = stzalloc(sizeof(*sp));
6965 sp->text = sstrdup(name);
6967 exparg.lastp = &sp->next;
6970 /* If we want to use glob() from libc... */
6971 #if !ENABLE_ASH_INTERNAL_GLOB
6973 /* Add the result of glob() to the list */
6975 addglob(const glob_t *pglob)
6977 char **p = pglob->gl_pathv;
6984 expandmeta(struct strlist *str /*, int flag*/)
6986 /* TODO - EXP_REDIR */
6996 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6997 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
6998 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7000 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7001 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7002 // Which means you need to unescape the string, right? Not so fast:
7003 // if there _is_ a file named "file\?" (with backslash), it is returned
7004 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7005 // You DONT KNOW by looking at the result whether you need to unescape it.
7007 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7008 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7009 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7010 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7011 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7012 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7013 i = glob(p, 0, NULL, &pglob);
7014 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7019 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7020 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7021 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7033 *exparg.lastp = str;
7034 rmescapes(str->text, 0);
7035 exparg.lastp = &str->next;
7037 default: /* GLOB_NOSPACE */
7040 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7047 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7050 * Do metacharacter (i.e. *, ?, [...]) expansion.
7053 expmeta(char *expdir, char *enddir, char *name)
7069 for (p = name; esc = 0, *p; p += esc + 1) {
7070 if (*p == '*' || *p == '?')
7072 else if (*p == '[') {
7079 if (*q == '/' || *q == '\0')
7089 if (p[esc] == '/') {
7092 start = p + esc + 1;
7096 if (metaflag == 0) { /* we've reached the end of the file name */
7097 if (enddir != expdir)
7105 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7116 } while (p < start);
7118 if (enddir == expdir) {
7120 } else if (enddir == expdir + 1 && *expdir == '/') {
7129 if (enddir != expdir)
7131 if (*endname == 0) {
7144 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7145 if (dp->d_name[0] == '.' && !matchdot)
7147 if (pmatch(start, dp->d_name)) {
7149 strcpy(enddir, dp->d_name);
7152 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7155 expmeta(expdir, p, endname);
7161 endname[-esc - 1] = esc ? '\\' : '/';
7164 static struct strlist *
7165 msort(struct strlist *list, int len)
7167 struct strlist *p, *q = NULL;
7168 struct strlist **lpp;
7176 for (n = half; --n >= 0;) {
7180 q->next = NULL; /* terminate first half of list */
7181 q = msort(list, half); /* sort first half of list */
7182 p = msort(p, len - half); /* sort second half */
7185 #if ENABLE_LOCALE_SUPPORT
7186 if (strcoll(p->text, q->text) < 0)
7188 if (strcmp(p->text, q->text) < 0)
7212 * Sort the results of file name expansion. It calculates the number of
7213 * strings to sort and then calls msort (short for merge sort) to do the
7216 static struct strlist *
7217 expsort(struct strlist *str)
7223 for (sp = str; sp; sp = sp->next)
7225 return msort(str, len);
7229 expandmeta(struct strlist *str /*, int flag*/)
7231 static const char metachars[] ALIGN1 = {
7234 /* TODO - EXP_REDIR */
7238 struct strlist **savelastp;
7244 if (!strpbrk(str->text, metachars))
7246 savelastp = exparg.lastp;
7249 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7251 int i = strlen(str->text);
7252 //BUGGY estimation of how long expanded name can be
7253 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7255 expmeta(expdir, expdir, p);
7260 if (exparg.lastp == savelastp) {
7265 *exparg.lastp = str;
7266 rmescapes(str->text, 0);
7267 exparg.lastp = &str->next;
7269 *exparg.lastp = NULL;
7270 *savelastp = sp = expsort(*savelastp);
7271 while (sp->next != NULL)
7273 exparg.lastp = &sp->next;
7278 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7281 * Perform variable substitution and command substitution on an argument,
7282 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7283 * perform splitting and file name expansion. When arglist is NULL, perform
7284 * here document expansion.
7287 expandarg(union node *arg, struct arglist *arglist, int flag)
7292 argbackq = arg->narg.backquote;
7293 STARTSTACKSTR(expdest);
7294 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7295 argstr(arg->narg.text, flag,
7296 /* var_str_list: */ arglist ? arglist->list : NULL);
7297 p = _STPUTC('\0', expdest);
7299 if (arglist == NULL) {
7300 /* here document expanded */
7303 p = grabstackstr(p);
7304 TRACE(("expandarg: p:'%s'\n", p));
7305 exparg.lastp = &exparg.list;
7309 if (flag & EXP_FULL) {
7310 ifsbreakup(p, &exparg);
7311 *exparg.lastp = NULL;
7312 exparg.lastp = &exparg.list;
7313 expandmeta(exparg.list /*, flag*/);
7315 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7317 TRACE(("expandarg: rmescapes:'%s'\n", p));
7319 sp = stzalloc(sizeof(*sp));
7322 exparg.lastp = &sp->next;
7324 *exparg.lastp = NULL;
7326 *arglist->lastp = exparg.list;
7327 arglist->lastp = exparg.lastp;
7335 * Expand shell variables and backquotes inside a here document.
7338 expandhere(union node *arg, int fd)
7340 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7341 full_write(fd, stackblock(), expdest - (char *)stackblock());
7345 * Returns true if the pattern matches the string.
7348 patmatch(char *pattern, const char *string)
7350 return pmatch(preglob(pattern, 0), string);
7354 * See if a pattern matches in a case statement.
7357 casematch(union node *pattern, char *val)
7359 struct stackmark smark;
7362 setstackmark(&smark);
7363 argbackq = pattern->narg.backquote;
7364 STARTSTACKSTR(expdest);
7365 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7366 /* var_str_list: */ NULL);
7367 STACKSTRNUL(expdest);
7369 result = patmatch(stackblock(), val);
7370 popstackmark(&smark);
7375 /* ============ find_command */
7379 int (*builtin)(int, char **) FAST_FUNC;
7380 /* unsigned flags; */
7382 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7383 /* "regular" builtins always take precedence over commands,
7384 * regardless of PATH=....%builtin... position */
7385 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7386 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7389 smallint cmdtype; /* CMDxxx */
7392 /* index >= 0 for commands without path (slashes) */
7393 /* (TODO: what exactly does the value mean? PATH position?) */
7394 /* index == -1 for commands with slashes */
7395 /* index == (-2 - applet_no) for NOFORK applets */
7396 const struct builtincmd *cmd;
7397 struct funcnode *func;
7400 /* values of cmdtype */
7401 #define CMDUNKNOWN -1 /* no entry in table for command */
7402 #define CMDNORMAL 0 /* command is an executable program */
7403 #define CMDFUNCTION 1 /* command is a shell function */
7404 #define CMDBUILTIN 2 /* command is a shell builtin */
7406 /* action to find_command() */
7407 #define DO_ERR 0x01 /* prints errors */
7408 #define DO_ABS 0x02 /* checks absolute paths */
7409 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7410 #define DO_ALTPATH 0x08 /* using alternate path */
7411 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7413 static void find_command(char *, struct cmdentry *, int, const char *);
7416 /* ============ Hashing commands */
7419 * When commands are first encountered, they are entered in a hash table.
7420 * This ensures that a full path search will not have to be done for them
7421 * on each invocation.
7423 * We should investigate converting to a linear search, even though that
7424 * would make the command name "hash" a misnomer.
7428 struct tblentry *next; /* next entry in hash chain */
7429 union param param; /* definition of builtin function */
7430 smallint cmdtype; /* CMDxxx */
7431 char rehash; /* if set, cd done since entry created */
7432 char cmdname[1]; /* name of command */
7435 static struct tblentry **cmdtable;
7436 #define INIT_G_cmdtable() do { \
7437 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7440 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7444 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7446 #if ENABLE_FEATURE_SH_STANDALONE
7447 if (applet_no >= 0) {
7448 if (APPLET_IS_NOEXEC(applet_no)) {
7452 run_applet_no_and_exit(applet_no, argv);
7454 /* re-exec ourselves with the new arguments */
7455 execve(bb_busybox_exec_path, argv, envp);
7456 /* If they called chroot or otherwise made the binary no longer
7457 * executable, fall through */
7464 execve(cmd, argv, envp);
7465 } while (errno == EINTR);
7467 execve(cmd, argv, envp);
7469 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7470 /* Run "cmd" as a shell script:
7471 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7472 * "If the execve() function fails with ENOEXEC, the shell
7473 * shall execute a command equivalent to having a shell invoked
7474 * with the command name as its first operand,
7475 * with any remaining arguments passed to the new shell"
7477 * That is, do not use $SHELL, user's shell, or /bin/sh;
7478 * just call ourselves.
7480 * Note that bash reads ~80 chars of the file, and if it sees
7481 * a zero byte before it sees newline, it doesn't try to
7482 * interpret it, but fails with "cannot execute binary file"
7483 * message and exit code 126. For one, this prevents attempts
7484 * to interpret foreign ELF binaries as shell scripts.
7487 cmd = (char*) bb_busybox_exec_path;
7488 /* NB: this is only possible because all callers of shellexec()
7489 * ensure that the argv[-1] slot exists!
7492 argv[0] = (char*) "ash";
7498 * Exec a program. Never returns. If you change this routine, you may
7499 * have to change the find_command routine as well.
7500 * argv[-1] must exist and be writable! See tryexec() for why.
7502 static void shellexec(char **, const char *, int) NORETURN;
7504 shellexec(char **argv, const char *path, int idx)
7510 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7512 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7513 if (strchr(argv[0], '/') != NULL
7514 #if ENABLE_FEATURE_SH_STANDALONE
7515 || (applet_no = find_applet_by_name(argv[0])) >= 0
7518 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7519 if (applet_no >= 0) {
7520 /* We tried execing ourself, but it didn't work.
7521 * Maybe /proc/self/exe doesn't exist?
7530 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7531 if (--idx < 0 && pathopt == NULL) {
7532 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7533 if (errno != ENOENT && errno != ENOTDIR)
7540 /* Map to POSIX errors */
7552 exitstatus = exerrno;
7553 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7554 argv[0], e, suppress_int));
7555 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7560 printentry(struct tblentry *cmdp)
7566 idx = cmdp->param.index;
7569 name = path_advance(&path, cmdp->cmdname);
7571 } while (--idx >= 0);
7572 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7576 * Clear out command entries. The argument specifies the first entry in
7577 * PATH which has changed.
7580 clearcmdentry(int firstchange)
7582 struct tblentry **tblp;
7583 struct tblentry **pp;
7584 struct tblentry *cmdp;
7587 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7589 while ((cmdp = *pp) != NULL) {
7590 if ((cmdp->cmdtype == CMDNORMAL &&
7591 cmdp->param.index >= firstchange)
7592 || (cmdp->cmdtype == CMDBUILTIN &&
7593 builtinloc >= firstchange)
7606 * Locate a command in the command hash table. If "add" is nonzero,
7607 * add the command to the table if it is not already present. The
7608 * variable "lastcmdentry" is set to point to the address of the link
7609 * pointing to the entry, so that delete_cmd_entry can delete the
7612 * Interrupts must be off if called with add != 0.
7614 static struct tblentry **lastcmdentry;
7616 static struct tblentry *
7617 cmdlookup(const char *name, int add)
7619 unsigned int hashval;
7621 struct tblentry *cmdp;
7622 struct tblentry **pp;
7625 hashval = (unsigned char)*p << 4;
7627 hashval += (unsigned char)*p++;
7629 pp = &cmdtable[hashval % CMDTABLESIZE];
7630 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7631 if (strcmp(cmdp->cmdname, name) == 0)
7635 if (add && cmdp == NULL) {
7636 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7638 /* + 1 - already done because
7639 * tblentry::cmdname is char[1] */);
7640 /*cmdp->next = NULL; - ckzalloc did it */
7641 cmdp->cmdtype = CMDUNKNOWN;
7642 strcpy(cmdp->cmdname, name);
7649 * Delete the command entry returned on the last lookup.
7652 delete_cmd_entry(void)
7654 struct tblentry *cmdp;
7657 cmdp = *lastcmdentry;
7658 *lastcmdentry = cmdp->next;
7659 if (cmdp->cmdtype == CMDFUNCTION)
7660 freefunc(cmdp->param.func);
7666 * Add a new command entry, replacing any existing command entry for
7667 * the same name - except special builtins.
7670 addcmdentry(char *name, struct cmdentry *entry)
7672 struct tblentry *cmdp;
7674 cmdp = cmdlookup(name, 1);
7675 if (cmdp->cmdtype == CMDFUNCTION) {
7676 freefunc(cmdp->param.func);
7678 cmdp->cmdtype = entry->cmdtype;
7679 cmdp->param = entry->u;
7683 static int FAST_FUNC
7684 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7686 struct tblentry **pp;
7687 struct tblentry *cmdp;
7689 struct cmdentry entry;
7692 if (nextopt("r") != '\0') {
7697 if (*argptr == NULL) {
7698 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7699 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7700 if (cmdp->cmdtype == CMDNORMAL)
7708 while ((name = *argptr) != NULL) {
7709 cmdp = cmdlookup(name, 0);
7711 && (cmdp->cmdtype == CMDNORMAL
7712 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7716 find_command(name, &entry, DO_ERR, pathval());
7717 if (entry.cmdtype == CMDUNKNOWN)
7725 * Called when a cd is done. Marks all commands so the next time they
7726 * are executed they will be rehashed.
7731 struct tblentry **pp;
7732 struct tblentry *cmdp;
7734 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7735 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7736 if (cmdp->cmdtype == CMDNORMAL
7737 || (cmdp->cmdtype == CMDBUILTIN
7738 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7748 * Fix command hash table when PATH changed.
7749 * Called before PATH is changed. The argument is the new value of PATH;
7750 * pathval() still returns the old value at this point.
7751 * Called with interrupts off.
7753 static void FAST_FUNC
7754 changepath(const char *new)
7762 firstchange = 9999; /* assume no change */
7768 if ((*old == '\0' && *new == ':')
7769 || (*old == ':' && *new == '\0')
7773 old = new; /* ignore subsequent differences */
7777 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7784 if (builtinloc < 0 && idx_bltin >= 0)
7785 builtinloc = idx_bltin; /* zap builtins */
7786 if (builtinloc >= 0 && idx_bltin < 0)
7788 clearcmdentry(firstchange);
7789 builtinloc = idx_bltin;
7814 #if ENABLE_ASH_BASH_COMPAT
7825 typedef smallint token_id_t;
7827 /* Nth bit indicates if token marks the end of a list */
7830 /* 0 */ | (1u << TEOF)
7831 /* 1 */ | (0u << TNL)
7832 /* 2 */ | (0u << TREDIR)
7833 /* 3 */ | (0u << TWORD)
7834 /* 4 */ | (0u << TSEMI)
7835 /* 5 */ | (0u << TBACKGND)
7836 /* 6 */ | (0u << TAND)
7837 /* 7 */ | (0u << TOR)
7838 /* 8 */ | (0u << TPIPE)
7839 /* 9 */ | (0u << TLP)
7840 /* 10 */ | (1u << TRP)
7841 /* 11 */ | (1u << TENDCASE)
7842 /* 12 */ | (1u << TENDBQUOTE)
7843 /* 13 */ | (0u << TNOT)
7844 /* 14 */ | (0u << TCASE)
7845 /* 15 */ | (1u << TDO)
7846 /* 16 */ | (1u << TDONE)
7847 /* 17 */ | (1u << TELIF)
7848 /* 18 */ | (1u << TELSE)
7849 /* 19 */ | (1u << TESAC)
7850 /* 20 */ | (1u << TFI)
7851 /* 21 */ | (0u << TFOR)
7852 #if ENABLE_ASH_BASH_COMPAT
7853 /* 22 */ | (0u << TFUNCTION)
7855 /* 23 */ | (0u << TIF)
7856 /* 24 */ | (0u << TIN)
7857 /* 25 */ | (1u << TTHEN)
7858 /* 26 */ | (0u << TUNTIL)
7859 /* 27 */ | (0u << TWHILE)
7860 /* 28 */ | (0u << TBEGIN)
7861 /* 29 */ | (1u << TEND)
7862 , /* thus far 29 bits used */
7865 static const char *const tokname_array[] = {
7879 #define KWDOFFSET 13
7880 /* the following are keywords */
7890 #if ENABLE_ASH_BASH_COMPAT
7902 /* Wrapper around strcmp for qsort/bsearch/... */
7904 pstrcmp(const void *a, const void *b)
7906 return strcmp((char*)a, *(char**)b);
7909 static const char *const *
7910 findkwd(const char *s)
7912 return bsearch(s, tokname_array + KWDOFFSET,
7913 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7914 sizeof(tokname_array[0]), pstrcmp);
7918 * Locate and print what a word is...
7921 describe_command(char *command, const char *path, int describe_command_verbose)
7923 struct cmdentry entry;
7924 struct tblentry *cmdp;
7925 #if ENABLE_ASH_ALIAS
7926 const struct alias *ap;
7929 path = path ? path : pathval();
7931 if (describe_command_verbose) {
7935 /* First look at the keywords */
7936 if (findkwd(command)) {
7937 out1str(describe_command_verbose ? " is a shell keyword" : command);
7941 #if ENABLE_ASH_ALIAS
7942 /* Then look at the aliases */
7943 ap = lookupalias(command, 0);
7945 if (!describe_command_verbose) {
7950 out1fmt(" is an alias for %s", ap->val);
7954 /* Then check if it is a tracked alias */
7955 cmdp = cmdlookup(command, 0);
7957 entry.cmdtype = cmdp->cmdtype;
7958 entry.u = cmdp->param;
7960 /* Finally use brute force */
7961 find_command(command, &entry, DO_ABS, path);
7964 switch (entry.cmdtype) {
7966 int j = entry.u.index;
7972 p = path_advance(&path, command);
7976 if (describe_command_verbose) {
7978 (cmdp ? " a tracked alias for" : nullstr), p
7987 if (describe_command_verbose) {
7988 out1str(" is a shell function");
7995 if (describe_command_verbose) {
7996 out1fmt(" is a %sshell builtin",
7997 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7998 "special " : nullstr
8006 if (describe_command_verbose) {
8007 out1str(": not found\n");
8016 static int FAST_FUNC
8017 typecmd(int argc UNUSED_PARAM, char **argv)
8023 /* type -p ... ? (we don't bother checking for 'p') */
8024 if (argv[1] && argv[1][0] == '-') {
8029 err |= describe_command(argv[i++], NULL, verbose);
8034 #if ENABLE_ASH_CMDCMD
8035 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8037 parse_command_args(char **argv, const char **path)
8050 if (c == '-' && !*cp) {
8058 *path = bb_default_path;
8061 /* run 'typecmd' for other options */
8070 static int FAST_FUNC
8071 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8079 const char *path = NULL;
8081 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8082 * never reaches this function.
8085 while ((c = nextopt("pvV")) != '\0')
8087 verify |= VERIFY_VERBOSE;
8089 /*verify |= VERIFY_BRIEF*/;
8095 path = bb_default_path;
8097 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8099 if (/*verify && */ cmd)
8100 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8107 /*static int funcblocksize; // size of structures in function */
8108 /*static int funcstringsize; // size of strings in node */
8109 static void *funcblock; /* block to allocate function from */
8110 static char *funcstring_end; /* end of block to allocate strings from */
8112 /* flags in argument to evaltree */
8113 #define EV_EXIT 01 /* exit after evaluating tree */
8114 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8116 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8117 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8118 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8119 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8120 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8121 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8122 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8123 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8124 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8125 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8126 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8127 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8128 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8129 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8130 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8131 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8132 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8133 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8134 #if ENABLE_ASH_BASH_COMPAT
8135 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8137 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8138 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8139 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8140 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8141 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8142 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8143 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8144 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8145 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8148 static int calcsize(int funcblocksize, union node *n);
8151 sizenodelist(int funcblocksize, struct nodelist *lp)
8154 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8155 funcblocksize = calcsize(funcblocksize, lp->n);
8158 return funcblocksize;
8162 calcsize(int funcblocksize, union node *n)
8165 return funcblocksize;
8166 funcblocksize += nodesize[n->type];
8169 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8170 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8171 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8174 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8179 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8180 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8187 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8188 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8191 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8192 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8193 funcblocksize = calcsize(funcblocksize, n->nif.test);
8196 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8197 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8198 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8201 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8202 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8205 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8206 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8207 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8211 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8212 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8213 funcblocksize = calcsize(funcblocksize, n->narg.next);
8216 #if ENABLE_ASH_BASH_COMPAT
8223 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8224 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8228 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8229 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8233 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8234 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8237 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8240 return funcblocksize;
8244 nodeckstrdup(char *s)
8246 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8247 return strcpy(funcstring_end, s);
8250 static union node *copynode(union node *);
8252 static struct nodelist *
8253 copynodelist(struct nodelist *lp)
8255 struct nodelist *start;
8256 struct nodelist **lpp;
8261 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8262 (*lpp)->n = copynode(lp->n);
8264 lpp = &(*lpp)->next;
8271 copynode(union node *n)
8278 funcblock = (char *) funcblock + nodesize[n->type];
8282 new->ncmd.redirect = copynode(n->ncmd.redirect);
8283 new->ncmd.args = copynode(n->ncmd.args);
8284 new->ncmd.assign = copynode(n->ncmd.assign);
8287 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8288 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8293 new->nredir.redirect = copynode(n->nredir.redirect);
8294 new->nredir.n = copynode(n->nredir.n);
8301 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8302 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8305 new->nif.elsepart = copynode(n->nif.elsepart);
8306 new->nif.ifpart = copynode(n->nif.ifpart);
8307 new->nif.test = copynode(n->nif.test);
8310 new->nfor.var = nodeckstrdup(n->nfor.var);
8311 new->nfor.body = copynode(n->nfor.body);
8312 new->nfor.args = copynode(n->nfor.args);
8315 new->ncase.cases = copynode(n->ncase.cases);
8316 new->ncase.expr = copynode(n->ncase.expr);
8319 new->nclist.body = copynode(n->nclist.body);
8320 new->nclist.pattern = copynode(n->nclist.pattern);
8321 new->nclist.next = copynode(n->nclist.next);
8325 new->narg.backquote = copynodelist(n->narg.backquote);
8326 new->narg.text = nodeckstrdup(n->narg.text);
8327 new->narg.next = copynode(n->narg.next);
8330 #if ENABLE_ASH_BASH_COMPAT
8337 new->nfile.fname = copynode(n->nfile.fname);
8338 new->nfile.fd = n->nfile.fd;
8339 new->nfile.next = copynode(n->nfile.next);
8343 new->ndup.vname = copynode(n->ndup.vname);
8344 new->ndup.dupfd = n->ndup.dupfd;
8345 new->ndup.fd = n->ndup.fd;
8346 new->ndup.next = copynode(n->ndup.next);
8350 new->nhere.doc = copynode(n->nhere.doc);
8351 new->nhere.fd = n->nhere.fd;
8352 new->nhere.next = copynode(n->nhere.next);
8355 new->nnot.com = copynode(n->nnot.com);
8358 new->type = n->type;
8363 * Make a copy of a parse tree.
8365 static struct funcnode *
8366 copyfunc(union node *n)
8371 /*funcstringsize = 0;*/
8372 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8373 f = ckzalloc(blocksize /* + funcstringsize */);
8374 funcblock = (char *) f + offsetof(struct funcnode, n);
8375 funcstring_end = (char *) f + blocksize;
8377 /* f->count = 0; - ckzalloc did it */
8382 * Define a shell function.
8385 defun(union node *func)
8387 struct cmdentry entry;
8390 entry.cmdtype = CMDFUNCTION;
8391 entry.u.func = copyfunc(func);
8392 addcmdentry(func->narg.text, &entry);
8396 /* Reasons for skipping commands (see comment on breakcmd routine) */
8397 #define SKIPBREAK (1 << 0)
8398 #define SKIPCONT (1 << 1)
8399 #define SKIPFUNC (1 << 2)
8400 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8401 static int skipcount; /* number of levels to skip */
8402 static int funcnest; /* depth of function calls */
8403 static int loopnest; /* current loop nesting level */
8405 /* Forward decl way out to parsing code - dotrap needs it */
8406 static int evalstring(char *s, int flags);
8408 /* Called to execute a trap.
8409 * Single callsite - at the end of evaltree().
8410 * If we return non-zero, evaltree raises EXEXIT exception.
8412 * Perhaps we should avoid entering new trap handlers
8413 * while we are executing a trap handler. [is it a TODO?]
8420 uint8_t last_status;
8425 last_status = exitstatus;
8429 TRACE(("dotrap entered\n"));
8430 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8442 /* non-trapped SIGINT is handled separately by raise_interrupt,
8443 * don't upset it by resetting gotsig[SIGINT-1] */
8444 if (sig == SIGINT && !p)
8447 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8453 exitstatus = last_status;
8454 TRACE(("dotrap returns\n"));
8457 /* forward declarations - evaluation is fairly recursive business... */
8458 static int evalloop(union node *, int);
8459 static int evalfor(union node *, int);
8460 static int evalcase(union node *, int);
8461 static int evalsubshell(union node *, int);
8462 static void expredir(union node *);
8463 static int evalpipe(union node *, int);
8464 static int evalcommand(union node *, int);
8465 static int evalbltin(const struct builtincmd *, int, char **, int);
8466 static void prehash(union node *);
8469 * Evaluate a parse tree. The value is left in the global variable
8473 evaltree(union node *n, int flags)
8476 int (*evalfn)(union node *, int);
8480 TRACE(("evaltree(NULL) called\n"));
8483 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8490 out1fmt("Node type = %d\n", n->type);
8495 status = !evaltree(n->nnot.com, EV_TESTED);
8498 expredir(n->nredir.redirect);
8499 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8501 status = evaltree(n->nredir.n, flags & EV_TESTED);
8503 if (n->nredir.redirect)
8504 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8507 evalfn = evalcommand;
8509 if (eflag && !(flags & EV_TESTED))
8521 evalfn = evalsubshell;
8534 #error NAND + 1 != NOR
8536 #if NOR + 1 != NSEMI
8537 #error NOR + 1 != NSEMI
8539 unsigned is_or = n->type - NAND;
8542 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8544 if ((!status) == is_or || evalskip)
8550 status = evalfn(n, flags);
8554 status = evaltree(n->nif.test, EV_TESTED);
8561 if (n->nif.elsepart) {
8562 n = n->nif.elsepart;
8569 /* Not necessary. To test it:
8570 * "false; f() { qwerty; }; echo $?" should print 0.
8574 exitstatus = status;
8578 /* Order of checks below is important:
8579 * signal handlers trigger before exit caused by "set -e".
8583 if (checkexit & status)
8584 raise_exception(EXEXIT);
8585 if (flags & EV_EXIT)
8586 raise_exception(EXEXIT);
8588 TRACE(("leaving evaltree (no interrupts)\n"));
8592 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8595 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8600 int skip = evalskip;
8607 if (--skipcount <= 0) {
8618 evalloop(union node *n, int flags)
8629 i = evaltree(n->nbinary.ch1, EV_TESTED);
8631 if (skip == SKIPFUNC)
8635 if (n->type != NWHILE)
8639 status = evaltree(n->nbinary.ch2, flags);
8641 } while (!(skip & ~SKIPCONT));
8648 evalfor(union node *n, int flags)
8650 struct arglist arglist;
8653 struct stackmark smark;
8656 setstackmark(&smark);
8657 arglist.list = NULL;
8658 arglist.lastp = &arglist.list;
8659 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8660 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8662 *arglist.lastp = NULL;
8666 for (sp = arglist.list; sp; sp = sp->next) {
8667 setvar0(n->nfor.var, sp->text);
8668 status = evaltree(n->nfor.body, flags);
8669 if (skiploop() & ~SKIPCONT)
8673 popstackmark(&smark);
8679 evalcase(union node *n, int flags)
8683 struct arglist arglist;
8684 struct stackmark smark;
8687 setstackmark(&smark);
8688 arglist.list = NULL;
8689 arglist.lastp = &arglist.list;
8690 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8691 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8692 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8693 if (casematch(patp, arglist.list->text)) {
8694 /* Ensure body is non-empty as otherwise
8695 * EV_EXIT may prevent us from setting the
8698 if (evalskip == 0 && cp->nclist.body) {
8699 status = evaltree(cp->nclist.body, flags);
8706 popstackmark(&smark);
8712 * Kick off a subshell to evaluate a tree.
8715 evalsubshell(union node *n, int flags)
8718 int backgnd = (n->type == NBACKGND);
8721 expredir(n->nredir.redirect);
8722 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8725 jp = makejob(/*n,*/ 1);
8726 if (forkshell(jp, n, backgnd) == 0) {
8731 flags &= ~EV_TESTED;
8733 redirect(n->nredir.redirect, 0);
8734 evaltreenr(n->nredir.n, flags);
8740 status = waitforjob(jp);
8746 * Compute the names of the files in a redirection list.
8748 static void fixredir(union node *, const char *, int);
8750 expredir(union node *n)
8754 for (redir = n; redir; redir = redir->nfile.next) {
8758 fn.lastp = &fn.list;
8759 switch (redir->type) {
8763 #if ENABLE_ASH_BASH_COMPAT
8768 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8769 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8770 #if ENABLE_ASH_BASH_COMPAT
8774 // By the design of stack allocator, the loop of this kind:
8775 // while true; do while true; do break; done </dev/null; done
8776 // will look like a memory leak: ash plans to free expfname's
8777 // of "/dev/null" as soon as it finishes running the loop
8778 // (in this case, never).
8779 // This "fix" is wrong:
8780 if (redir->nfile.expfname)
8781 stunalloc(redir->nfile.expfname);
8782 // It results in corrupted state of stacked allocations.
8784 redir->nfile.expfname = fn.list->text;
8787 case NTOFD: /* >& */
8788 if (redir->ndup.vname) {
8789 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8790 if (fn.list == NULL)
8791 ash_msg_and_raise_error("redir error");
8792 #if ENABLE_ASH_BASH_COMPAT
8793 //FIXME: we used expandarg with different args!
8794 if (!isdigit_str9(fn.list->text)) {
8795 /* >&file, not >&fd */
8796 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8797 ash_msg_and_raise_error("redir error");
8799 goto store_expfname;
8802 fixredir(redir, fn.list->text, 1);
8810 * Evaluate a pipeline. All the processes in the pipeline are children
8811 * of the process creating the pipeline. (This differs from some versions
8812 * of the shell, which make the last process in a pipeline the parent
8816 evalpipe(union node *n, int flags)
8819 struct nodelist *lp;
8825 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8827 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8831 jp = makejob(/*n,*/ pipelen);
8833 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8837 if (pipe(pip) < 0) {
8839 ash_msg_and_raise_error("pipe call failed");
8842 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8856 evaltreenr(lp->n, flags);
8863 /* Don't want to trigger debugging */
8867 if (n->npipe.pipe_backgnd == 0) {
8868 status = waitforjob(jp);
8869 TRACE(("evalpipe: job done exit status %d\n", status));
8877 * Controls whether the shell is interactive or not.
8880 setinteractive(int on)
8882 static smallint is_interactive;
8884 if (++on == is_interactive)
8886 is_interactive = on;
8890 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8891 if (is_interactive > 1) {
8892 /* Looks like they want an interactive shell */
8893 static smallint did_banner;
8896 /* note: ash and hush share this string */
8897 out1fmt("\n\n%s %s\n"
8898 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8901 "built-in shell (ash)"
8915 setinteractive(iflag);
8917 #if ENABLE_FEATURE_EDITING_VI
8919 line_input_state->flags |= VI_MODE;
8921 line_input_state->flags &= ~VI_MODE;
8923 viflag = 0; /* forcibly keep the option off */
8927 static struct localvar *localvars;
8930 * Called after a function returns.
8931 * Interrupts must be off.
8936 struct localvar *lvp;
8939 while ((lvp = localvars) != NULL) {
8940 localvars = lvp->next;
8942 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8943 if (vp == NULL) { /* $- saved */
8944 memcpy(optlist, lvp->text, sizeof(optlist));
8945 free((char*)lvp->text);
8947 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8948 unsetvar(vp->var_text);
8951 vp->var_func(var_end(lvp->text));
8952 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8953 free((char*)vp->var_text);
8954 vp->flags = lvp->flags;
8955 vp->var_text = lvp->text;
8962 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8964 volatile struct shparam saveparam;
8965 struct localvar *volatile savelocalvars;
8966 struct jmploc *volatile savehandler;
8967 struct jmploc jmploc;
8970 saveparam = shellparam;
8971 savelocalvars = localvars;
8972 savehandler = exception_handler;
8973 e = setjmp(jmploc.loc);
8978 exception_handler = &jmploc;
8980 shellparam.malloced = 0;
8984 shellparam.nparam = argc - 1;
8985 shellparam.p = argv + 1;
8986 #if ENABLE_ASH_GETOPTS
8987 shellparam.optind = 1;
8988 shellparam.optoff = -1;
8990 evaltree(func->n.narg.next, flags & EV_TESTED);
8996 localvars = savelocalvars;
8997 freeparam(&shellparam);
8998 shellparam = saveparam;
8999 exception_handler = savehandler;
9001 evalskip &= ~SKIPFUNC;
9006 * Make a variable a local variable. When a variable is made local, it's
9007 * value and flags are saved in a localvar structure. The saved values
9008 * will be restored when the shell function returns. We handle the name
9009 * "-" as a special case: it makes changes to "set +-options" local
9010 * (options will be restored on return from the function).
9015 struct localvar *lvp;
9018 char *eq = strchr(name, '=');
9021 /* Cater for duplicate "local". Examples:
9022 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9023 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9027 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9031 * it's a duplicate "local VAR" declaration, do nothing
9038 lvp = ckzalloc(sizeof(*lvp));
9039 if (LONE_DASH(name)) {
9041 p = ckmalloc(sizeof(optlist));
9042 lvp->text = memcpy(p, optlist, sizeof(optlist));
9045 vpp = hashvar(name);
9046 vp = *findvar(vpp, name);
9048 /* variable did not exist yet */
9050 setvareq(name, VSTRFIXED);
9052 setvar(name, NULL, VSTRFIXED);
9053 vp = *vpp; /* the new variable */
9054 lvp->flags = VUNSET;
9056 lvp->text = vp->var_text;
9057 lvp->flags = vp->flags;
9058 /* make sure neither "struct var" nor string gets freed
9059 * during (un)setting:
9061 vp->flags |= VSTRFIXED|VTEXTFIXED;
9065 /* "local VAR" unsets VAR: */
9066 setvar0(name, NULL);
9070 lvp->next = localvars;
9076 * The "local" command.
9078 static int FAST_FUNC
9079 localcmd(int argc UNUSED_PARAM, char **argv)
9084 ash_msg_and_raise_error("not in a function");
9087 while ((name = *argv++) != NULL) {
9093 static int FAST_FUNC
9094 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9099 static int FAST_FUNC
9100 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9105 static int FAST_FUNC
9106 execcmd(int argc UNUSED_PARAM, char **argv)
9109 iflag = 0; /* exit on error */
9112 /* We should set up signals for "exec CMD"
9113 * the same way as for "CMD" without "exec".
9114 * But optschanged->setinteractive->setsignal
9115 * still thought we are a root shell. Therefore, for example,
9116 * SIGQUIT is still set to IGN. Fix it:
9120 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9121 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9122 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9124 shellexec(argv + 1, pathval(), 0);
9131 * The return command.
9133 static int FAST_FUNC
9134 returncmd(int argc UNUSED_PARAM, char **argv)
9137 * If called outside a function, do what ksh does;
9138 * skip the rest of the file.
9140 evalskip = SKIPFUNC;
9141 return argv[1] ? number(argv[1]) : exitstatus;
9144 /* Forward declarations for builtintab[] */
9145 static int breakcmd(int, char **) FAST_FUNC;
9146 static int dotcmd(int, char **) FAST_FUNC;
9147 static int evalcmd(int, char **, int) FAST_FUNC;
9148 static int exitcmd(int, char **) FAST_FUNC;
9149 static int exportcmd(int, char **) FAST_FUNC;
9150 #if ENABLE_ASH_GETOPTS
9151 static int getoptscmd(int, char **) FAST_FUNC;
9154 static int helpcmd(int, char **) FAST_FUNC;
9157 static int historycmd(int, char **) FAST_FUNC;
9159 #if ENABLE_SH_MATH_SUPPORT
9160 static int letcmd(int, char **) FAST_FUNC;
9162 static int readcmd(int, char **) FAST_FUNC;
9163 static int setcmd(int, char **) FAST_FUNC;
9164 static int shiftcmd(int, char **) FAST_FUNC;
9165 static int timescmd(int, char **) FAST_FUNC;
9166 static int trapcmd(int, char **) FAST_FUNC;
9167 static int umaskcmd(int, char **) FAST_FUNC;
9168 static int unsetcmd(int, char **) FAST_FUNC;
9169 static int ulimitcmd(int, char **) FAST_FUNC;
9171 #define BUILTIN_NOSPEC "0"
9172 #define BUILTIN_SPECIAL "1"
9173 #define BUILTIN_REGULAR "2"
9174 #define BUILTIN_SPEC_REG "3"
9175 #define BUILTIN_ASSIGN "4"
9176 #define BUILTIN_SPEC_ASSG "5"
9177 #define BUILTIN_REG_ASSG "6"
9178 #define BUILTIN_SPEC_REG_ASSG "7"
9180 /* Stubs for calling non-FAST_FUNC's */
9181 #if ENABLE_ASH_BUILTIN_ECHO
9182 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9184 #if ENABLE_ASH_BUILTIN_PRINTF
9185 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9187 #if ENABLE_ASH_BUILTIN_TEST
9188 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9191 /* Keep these in proper order since it is searched via bsearch() */
9192 static const struct builtincmd builtintab[] = {
9193 { BUILTIN_SPEC_REG "." , dotcmd },
9194 { BUILTIN_SPEC_REG ":" , truecmd },
9195 #if ENABLE_ASH_BUILTIN_TEST
9196 { BUILTIN_REGULAR "[" , testcmd },
9197 #if ENABLE_ASH_BASH_COMPAT
9198 { BUILTIN_REGULAR "[[" , testcmd },
9201 #if ENABLE_ASH_ALIAS
9202 { BUILTIN_REG_ASSG "alias" , aliascmd },
9205 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9207 { BUILTIN_SPEC_REG "break" , breakcmd },
9208 { BUILTIN_REGULAR "cd" , cdcmd },
9209 { BUILTIN_NOSPEC "chdir" , cdcmd },
9210 #if ENABLE_ASH_CMDCMD
9211 { BUILTIN_REGULAR "command" , commandcmd },
9213 { BUILTIN_SPEC_REG "continue", breakcmd },
9214 #if ENABLE_ASH_BUILTIN_ECHO
9215 { BUILTIN_REGULAR "echo" , echocmd },
9217 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9218 { BUILTIN_SPEC_REG "exec" , execcmd },
9219 { BUILTIN_SPEC_REG "exit" , exitcmd },
9220 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9221 { BUILTIN_REGULAR "false" , falsecmd },
9223 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9225 #if ENABLE_ASH_GETOPTS
9226 { BUILTIN_REGULAR "getopts" , getoptscmd },
9228 { BUILTIN_NOSPEC "hash" , hashcmd },
9230 { BUILTIN_NOSPEC "help" , helpcmd },
9233 { BUILTIN_NOSPEC "history" , historycmd },
9236 { BUILTIN_REGULAR "jobs" , jobscmd },
9237 { BUILTIN_REGULAR "kill" , killcmd },
9239 #if ENABLE_SH_MATH_SUPPORT
9240 { BUILTIN_NOSPEC "let" , letcmd },
9242 { BUILTIN_ASSIGN "local" , localcmd },
9243 #if ENABLE_ASH_BUILTIN_PRINTF
9244 { BUILTIN_REGULAR "printf" , printfcmd },
9246 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9247 { BUILTIN_REGULAR "read" , readcmd },
9248 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9249 { BUILTIN_SPEC_REG "return" , returncmd },
9250 { BUILTIN_SPEC_REG "set" , setcmd },
9251 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9252 #if ENABLE_ASH_BASH_COMPAT
9253 { BUILTIN_SPEC_REG "source" , dotcmd },
9255 #if ENABLE_ASH_BUILTIN_TEST
9256 { BUILTIN_REGULAR "test" , testcmd },
9258 { BUILTIN_SPEC_REG "times" , timescmd },
9259 { BUILTIN_SPEC_REG "trap" , trapcmd },
9260 { BUILTIN_REGULAR "true" , truecmd },
9261 { BUILTIN_NOSPEC "type" , typecmd },
9262 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9263 { BUILTIN_REGULAR "umask" , umaskcmd },
9264 #if ENABLE_ASH_ALIAS
9265 { BUILTIN_REGULAR "unalias" , unaliascmd },
9267 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9268 { BUILTIN_REGULAR "wait" , waitcmd },
9271 /* Should match the above table! */
9272 #define COMMANDCMD (builtintab + \
9274 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9275 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9276 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9277 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9278 /* break cd cddir */ 3)
9279 #define EVALCMD (COMMANDCMD + \
9280 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9281 /* continue */ 1 + \
9282 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9284 #define EXECCMD (EVALCMD + \
9288 * Search the table of builtin commands.
9291 pstrcmp1(const void *a, const void *b)
9293 return strcmp((char*)a, *(char**)b + 1);
9295 static struct builtincmd *
9296 find_builtin(const char *name)
9298 struct builtincmd *bp;
9301 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9308 * Execute a simple command.
9311 isassignment(const char *p)
9313 const char *q = endofname(p);
9318 static int FAST_FUNC
9319 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9321 /* Preserve exitstatus of a previous possible redirection
9322 * as POSIX mandates */
9323 return back_exitstatus;
9326 evalcommand(union node *cmd, int flags)
9328 static const struct builtincmd null_bltin = {
9329 "\0\0", bltincmd /* why three NULs? */
9331 struct stackmark smark;
9333 struct arglist arglist;
9334 struct arglist varlist;
9337 const struct strlist *sp;
9338 struct cmdentry cmdentry;
9345 struct builtincmd *bcmd;
9346 smallint cmd_is_exec;
9347 smallint pseudovarflag = 0;
9349 /* First expand the arguments. */
9350 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9351 setstackmark(&smark);
9352 back_exitstatus = 0;
9354 cmdentry.cmdtype = CMDBUILTIN;
9355 cmdentry.u.cmd = &null_bltin;
9356 varlist.lastp = &varlist.list;
9357 *varlist.lastp = NULL;
9358 arglist.lastp = &arglist.list;
9359 *arglist.lastp = NULL;
9362 if (cmd->ncmd.args) {
9363 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9364 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9367 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9368 struct strlist **spp;
9370 spp = arglist.lastp;
9371 if (pseudovarflag && isassignment(argp->narg.text))
9372 expandarg(argp, &arglist, EXP_VARTILDE);
9374 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9376 for (sp = *spp; sp; sp = sp->next)
9380 /* Reserve one extra spot at the front for shellexec. */
9381 nargv = stalloc(sizeof(char *) * (argc + 2));
9383 for (sp = arglist.list; sp; sp = sp->next) {
9384 TRACE(("evalcommand arg: %s\n", sp->text));
9385 *nargv++ = sp->text;
9390 if (iflag && funcnest == 0 && argc > 0)
9391 lastarg = nargv[-1];
9394 expredir(cmd->ncmd.redirect);
9395 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9397 path = vpath.var_text;
9398 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9399 struct strlist **spp;
9402 spp = varlist.lastp;
9403 expandarg(argp, &varlist, EXP_VARTILDE);
9406 * Modify the command lookup path, if a PATH= assignment
9410 if (varcmp(p, path) == 0)
9414 /* Print the command if xflag is set. */
9417 const char *p = " %s" + 1;
9419 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9421 for (n = 0; n < 2; n++) {
9423 fdprintf(preverrout_fd, p, sp->text);
9429 safe_write(preverrout_fd, "\n", 1);
9435 /* Now locate the command. */
9437 int cmd_flag = DO_ERR;
9438 #if ENABLE_ASH_CMDCMD
9439 const char *oldpath = path + 5;
9443 find_command(argv[0], &cmdentry, cmd_flag, path);
9444 if (cmdentry.cmdtype == CMDUNKNOWN) {
9445 flush_stdout_stderr();
9450 /* implement bltin and command here */
9451 if (cmdentry.cmdtype != CMDBUILTIN)
9454 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9455 if (cmdentry.u.cmd == EXECCMD)
9457 #if ENABLE_ASH_CMDCMD
9458 if (cmdentry.u.cmd == COMMANDCMD) {
9460 nargv = parse_command_args(argv, &path);
9463 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9464 * nargv => "PROG". path is updated if -p.
9466 argc -= nargv - argv;
9468 cmd_flag |= DO_NOFUNC;
9476 /* We have a redirection error. */
9478 raise_exception(EXERROR);
9480 exitstatus = status;
9484 /* Execute the command. */
9485 switch (cmdentry.cmdtype) {
9488 #if ENABLE_FEATURE_SH_NOFORK
9489 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9490 * around run_nofork_applet() call.
9491 * (2) Should this check also be done in forkshell()?
9492 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9494 /* find_command() encodes applet_no as (-2 - applet_no) */
9495 int applet_no = (- cmdentry.u.index - 2);
9496 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9497 listsetvar(varlist.list, VEXPORT|VSTACK);
9498 /* run <applet>_main() */
9499 status = run_nofork_applet(applet_no, argv);
9503 /* Can we avoid forking off? For example, very last command
9504 * in a script or a subshell does not need forking,
9505 * we can just exec it.
9507 if (!(flags & EV_EXIT) || may_have_traps) {
9508 /* No, forking off a child is necessary */
9510 jp = makejob(/*cmd,*/ 1);
9511 if (forkshell(jp, cmd, FORK_FG) != 0) {
9513 status = waitforjob(jp);
9515 TRACE(("forked child exited with %d\n", status));
9520 /* fall through to exec'ing external program */
9522 listsetvar(varlist.list, VEXPORT|VSTACK);
9523 shellexec(argv, path, cmdentry.u.index);
9527 cmdenviron = varlist.list;
9529 struct strlist *list = cmdenviron;
9531 if (spclbltin > 0 || argc == 0) {
9533 if (cmd_is_exec && argc > 1)
9536 listsetvar(list, i);
9538 /* Tight loop with builtins only:
9539 * "while kill -0 $child; do true; done"
9540 * will never exit even if $child died, unless we do this
9541 * to reap the zombie and make kill detect that it's gone: */
9542 dowait(DOWAIT_NONBLOCK, NULL);
9544 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9545 if (exception_type == EXERROR && spclbltin <= 0) {
9550 longjmp(exception_handler->loc, 1);
9555 listsetvar(varlist.list, 0);
9556 /* See above for the rationale */
9557 dowait(DOWAIT_NONBLOCK, NULL);
9558 if (evalfun(cmdentry.u.func, argc, argv, flags))
9561 status = exitstatus;
9566 if (cmd->ncmd.redirect)
9567 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9569 /* dsl: I think this is intended to be used to support
9570 * '_' in 'vi' command mode during line editing...
9571 * However I implemented that within libedit itself.
9573 setvar0("_", lastarg);
9575 popstackmark(&smark);
9581 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9583 char *volatile savecmdname;
9584 struct jmploc *volatile savehandler;
9585 struct jmploc jmploc;
9589 savecmdname = commandname;
9590 savehandler = exception_handler;
9591 i = setjmp(jmploc.loc);
9594 exception_handler = &jmploc;
9595 commandname = argv[0];
9597 optptr = NULL; /* initialize nextopt */
9599 status = evalcmd(argc, argv, flags);
9601 status = (*cmd->builtin)(argc, argv);
9602 flush_stdout_stderr();
9603 status |= ferror(stdout);
9604 exitstatus = status;
9607 commandname = savecmdname;
9608 exception_handler = savehandler;
9614 goodname(const char *p)
9616 return endofname(p)[0] == '\0';
9621 * Search for a command. This is called before we fork so that the
9622 * location of the command will be available in the parent as well as
9623 * the child. The check for "goodname" is an overly conservative
9624 * check that the name will not be subject to expansion.
9627 prehash(union node *n)
9629 struct cmdentry entry;
9631 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9632 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9636 /* ============ Builtin commands
9638 * Builtin commands whose functions are closely tied to evaluation
9639 * are implemented here.
9643 * Handle break and continue commands. Break, continue, and return are
9644 * all handled by setting the evalskip flag. The evaluation routines
9645 * above all check this flag, and if it is set they start skipping
9646 * commands rather than executing them. The variable skipcount is
9647 * the number of loops to break/continue, or the number of function
9648 * levels to return. (The latter is always 1.) It should probably
9649 * be an error to break out of more loops than exist, but it isn't
9650 * in the standard shell so we don't make it one here.
9652 static int FAST_FUNC
9653 breakcmd(int argc UNUSED_PARAM, char **argv)
9655 int n = argv[1] ? number(argv[1]) : 1;
9658 ash_msg_and_raise_error(msg_illnum, argv[1]);
9662 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9670 * This implements the input routines used by the parser.
9674 INPUT_PUSH_FILE = 1,
9675 INPUT_NOFILE_OK = 2,
9678 static smallint checkkwd;
9679 /* values of checkkwd variable */
9680 #define CHKALIAS 0x1
9685 * Push a string back onto the input at this current parsefile level.
9686 * We handle aliases this way.
9688 #if !ENABLE_ASH_ALIAS
9689 #define pushstring(s, ap) pushstring(s)
9692 pushstring(char *s, struct alias *ap)
9699 if (g_parsefile->strpush) {
9700 sp = ckzalloc(sizeof(*sp));
9701 sp->prev = g_parsefile->strpush;
9703 sp = &(g_parsefile->basestrpush);
9705 g_parsefile->strpush = sp;
9706 sp->prev_string = g_parsefile->next_to_pgetc;
9707 sp->prev_left_in_line = g_parsefile->left_in_line;
9708 sp->unget = g_parsefile->unget;
9709 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9710 #if ENABLE_ASH_ALIAS
9713 ap->flag |= ALIASINUSE;
9717 g_parsefile->next_to_pgetc = s;
9718 g_parsefile->left_in_line = len;
9719 g_parsefile->unget = 0;
9726 struct strpush *sp = g_parsefile->strpush;
9729 #if ENABLE_ASH_ALIAS
9731 if (g_parsefile->next_to_pgetc[-1] == ' '
9732 || g_parsefile->next_to_pgetc[-1] == '\t'
9734 checkkwd |= CHKALIAS;
9736 if (sp->string != sp->ap->val) {
9739 sp->ap->flag &= ~ALIASINUSE;
9740 if (sp->ap->flag & ALIASDEAD) {
9741 unalias(sp->ap->name);
9745 g_parsefile->next_to_pgetc = sp->prev_string;
9746 g_parsefile->left_in_line = sp->prev_left_in_line;
9747 g_parsefile->unget = sp->unget;
9748 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9749 g_parsefile->strpush = sp->prev;
9750 if (sp != &(g_parsefile->basestrpush))
9759 char *buf = g_parsefile->buf;
9761 g_parsefile->next_to_pgetc = buf;
9762 #if ENABLE_FEATURE_EDITING
9764 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9765 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9768 # if ENABLE_ASH_IDLE_TIMEOUT
9770 const char *tmout_var = lookupvar("TMOUT");
9772 timeout = atoi(tmout_var) * 1000;
9778 # if ENABLE_FEATURE_TAB_COMPLETION
9779 line_input_state->path_lookup = pathval();
9781 reinit_unicode_for_ash();
9782 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9784 /* Ctrl+C pressed */
9795 /* Ctrl+D pressed */
9798 # if ENABLE_ASH_IDLE_TIMEOUT
9799 else if (errno == EAGAIN && timeout > 0) {
9800 puts("\007timed out waiting for input: auto-logout");
9807 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9810 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9812 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9813 int flags = fcntl(0, F_GETFL);
9814 if (flags >= 0 && (flags & O_NONBLOCK)) {
9815 flags &= ~O_NONBLOCK;
9816 if (fcntl(0, F_SETFL, flags) >= 0) {
9817 out2str("sh: turning off NDELAY mode\n");
9828 * Refill the input buffer and return the next input character:
9830 * 1) If a string was pushed back on the input, pop it;
9831 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9832 * or we are reading from a string so we can't refill the buffer,
9834 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9835 * 4) Process input up to the next newline, deleting nul characters.
9837 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9838 #define pgetc_debug(...) ((void)0)
9839 static int pgetc(void);
9846 if (g_parsefile->strpush) {
9847 #if ENABLE_ASH_ALIAS
9848 if (g_parsefile->left_in_line == -1
9849 && g_parsefile->strpush->ap
9850 && g_parsefile->next_to_pgetc[-1] != ' '
9851 && g_parsefile->next_to_pgetc[-1] != '\t'
9853 pgetc_debug("preadbuffer PEOA");
9860 /* on both branches above g_parsefile->left_in_line < 0.
9861 * "pgetc" needs refilling.
9864 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9865 * pungetc() may increment it a few times.
9866 * Assuming it won't increment it to less than -90.
9868 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9869 pgetc_debug("preadbuffer PEOF1");
9870 /* even in failure keep left_in_line and next_to_pgetc
9871 * in lock step, for correct multi-layer pungetc.
9872 * left_in_line was decremented before preadbuffer(),
9873 * must inc next_to_pgetc: */
9874 g_parsefile->next_to_pgetc++;
9878 more = g_parsefile->left_in_buffer;
9880 flush_stdout_stderr();
9884 /* don't try reading again */
9885 g_parsefile->left_in_line = -99;
9886 pgetc_debug("preadbuffer PEOF2");
9887 g_parsefile->next_to_pgetc++;
9892 /* Find out where's the end of line.
9893 * Set g_parsefile->left_in_line
9894 * and g_parsefile->left_in_buffer acordingly.
9895 * NUL chars are deleted.
9897 q = g_parsefile->next_to_pgetc;
9905 memmove(q, q + 1, more);
9909 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9915 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9916 if (g_parsefile->left_in_line < 0)
9921 g_parsefile->left_in_buffer = more;
9926 out2str(g_parsefile->next_to_pgetc);
9930 pgetc_debug("preadbuffer at %d:%p'%s'",
9931 g_parsefile->left_in_line,
9932 g_parsefile->next_to_pgetc,
9933 g_parsefile->next_to_pgetc);
9934 return (unsigned char)*g_parsefile->next_to_pgetc++;
9940 g_parsefile->linno++;
9941 setprompt_if(doprompt, 2);
9946 g_parsefile->linno++;
9947 needprompt = doprompt;
9955 pgetc_debug("pgetc at %d:%p'%s'",
9956 g_parsefile->left_in_line,
9957 g_parsefile->next_to_pgetc,
9958 g_parsefile->next_to_pgetc);
9959 if (g_parsefile->unget)
9960 return g_parsefile->lastc[--g_parsefile->unget];
9962 if (--g_parsefile->left_in_line >= 0)
9963 c = (signed char)*g_parsefile->next_to_pgetc++;
9967 g_parsefile->lastc[1] = g_parsefile->lastc[0];
9968 g_parsefile->lastc[0] = c;
9973 #if ENABLE_ASH_ALIAS
9975 pgetc_without_PEOA(void)
9979 pgetc_debug("pgetc at %d:%p'%s'",
9980 g_parsefile->left_in_line,
9981 g_parsefile->next_to_pgetc,
9982 g_parsefile->next_to_pgetc);
9984 } while (c == PEOA);
9988 # define pgetc_without_PEOA() pgetc()
9992 * Read a line from the script.
9995 pfgets(char *line, int len)
10001 while (--nleft > 0) {
10002 c = pgetc_without_PEOA();
10017 * Undo a call to pgetc. Only two characters may be pushed back.
10018 * PEOF may be pushed back.
10023 g_parsefile->unget++;
10026 /* This one eats backslash+newline */
10032 while ((c = pgetc()) == '\\') {
10033 if (pgetc() != '\n') {
10045 * To handle the "." command, a stack of input files is used. Pushfile
10046 * adds a new entry to the stack and popfile restores the previous level.
10051 struct parsefile *pf;
10053 pf = ckzalloc(sizeof(*pf));
10054 pf->prev = g_parsefile;
10056 /*pf->strpush = NULL; - ckzalloc did it */
10057 /*pf->basestrpush.prev = NULL;*/
10065 struct parsefile *pf = g_parsefile;
10068 if (pf->pf_fd >= 0)
10071 while (pf->strpush)
10073 g_parsefile = pf->prev;
10079 * Return to top level.
10084 while (g_parsefile != &basepf)
10089 * Close the file(s) that the shell is reading commands from. Called
10090 * after a fork is done.
10096 if (g_parsefile->pf_fd > 0) {
10097 close(g_parsefile->pf_fd);
10098 g_parsefile->pf_fd = 0;
10103 * Like setinputfile, but takes an open file descriptor. Call this with
10107 setinputfd(int fd, int push)
10111 g_parsefile->buf = NULL;
10113 g_parsefile->pf_fd = fd;
10114 if (g_parsefile->buf == NULL)
10115 g_parsefile->buf = ckmalloc(IBUFSIZ);
10116 g_parsefile->left_in_buffer = 0;
10117 g_parsefile->left_in_line = 0;
10118 g_parsefile->linno = 1;
10122 * Set the input to take input from a file. If push is set, push the
10123 * old input onto the stack first.
10126 setinputfile(const char *fname, int flags)
10131 fd = open(fname, O_RDONLY);
10133 if (flags & INPUT_NOFILE_OK)
10136 ash_msg_and_raise_error("can't open '%s'", fname);
10141 close_on_exec_on(fd);
10142 setinputfd(fd, flags & INPUT_PUSH_FILE);
10149 * Like setinputfile, but takes input from a string.
10152 setinputstring(char *string)
10156 g_parsefile->next_to_pgetc = string;
10157 g_parsefile->left_in_line = strlen(string);
10158 g_parsefile->buf = NULL;
10159 g_parsefile->linno = 1;
10165 * Routines to check for mail.
10168 #if ENABLE_ASH_MAIL
10170 /* Hash of mtimes of mailboxes */
10171 static unsigned mailtime_hash;
10172 /* Set if MAIL or MAILPATH is changed. */
10173 static smallint mail_var_path_changed;
10176 * Print appropriate message(s) if mail has arrived.
10177 * If mail_var_path_changed is set,
10178 * then the value of MAIL has mail_var_path_changed,
10179 * so we just update the values.
10188 struct stackmark smark;
10191 setstackmark(&smark);
10192 mpath = mpathset() ? mpathval() : mailval();
10195 p = path_advance(&mpath, nullstr);
10200 for (q = p; *q; q++)
10206 q[-1] = '\0'; /* delete trailing '/' */
10207 if (stat(p, &statb) < 0) {
10210 /* Very simplistic "hash": just a sum of all mtimes */
10211 new_hash += (unsigned)statb.st_mtime;
10213 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10214 if (mailtime_hash != 0)
10215 out2str("you have mail\n");
10216 mailtime_hash = new_hash;
10218 mail_var_path_changed = 0;
10219 popstackmark(&smark);
10222 static void FAST_FUNC
10223 changemail(const char *val UNUSED_PARAM)
10225 mail_var_path_changed = 1;
10228 #endif /* ASH_MAIL */
10231 /* ============ ??? */
10234 * Set the shell parameters.
10237 setparam(char **argv)
10243 for (nparam = 0; argv[nparam]; nparam++)
10245 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10247 *ap++ = ckstrdup(*argv++);
10250 freeparam(&shellparam);
10251 shellparam.malloced = 1;
10252 shellparam.nparam = nparam;
10253 shellparam.p = newparam;
10254 #if ENABLE_ASH_GETOPTS
10255 shellparam.optind = 1;
10256 shellparam.optoff = -1;
10261 * Process shell options. The global variable argptr contains a pointer
10262 * to the argument list; we advance it past the options.
10264 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10265 * For a non-interactive shell, an error condition encountered
10266 * by a special built-in ... shall cause the shell to write a diagnostic message
10267 * to standard error and exit as shown in the following table:
10268 * Error Special Built-In
10270 * Utility syntax error (option or operand error) Shall exit
10272 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10273 * we see that bash does not do that (set "finishes" with error code 1 instead,
10274 * and shell continues), and people rely on this behavior!
10276 * set -o barfoo 2>/dev/null
10279 * Oh well. Let's mimic that.
10282 plus_minus_o(char *name, int val)
10287 for (i = 0; i < NOPTS; i++) {
10288 if (strcmp(name, optnames(i)) == 0) {
10293 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10296 for (i = 0; i < NOPTS; i++) {
10298 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10300 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10306 setoption(int flag, int val)
10310 for (i = 0; i < NOPTS; i++) {
10311 if (optletters(i) == flag) {
10316 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10320 options(int cmdline)
10328 while ((p = *argptr) != NULL) {
10330 if (c != '-' && c != '+')
10333 val = 0; /* val = 0 if c == '+' */
10336 if (p[0] == '\0' || LONE_DASH(p)) {
10338 /* "-" means turn off -x and -v */
10341 /* "--" means reset params */
10342 else if (*argptr == NULL)
10345 break; /* "-" or "--" terminates options */
10348 /* first char was + or - */
10349 while ((c = *p++) != '\0') {
10350 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10351 if (c == 'c' && cmdline) {
10352 minusc = p; /* command is after shell args */
10353 } else if (c == 'o') {
10354 if (plus_minus_o(*argptr, val)) {
10355 /* it already printed err message */
10356 return 1; /* error */
10360 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10362 /* bash does not accept +-login, we also won't */
10363 } else if (cmdline && val && (c == '-')) { /* long options */
10364 if (strcmp(p, "login") == 0)
10376 * The shift builtin command.
10378 static int FAST_FUNC
10379 shiftcmd(int argc UNUSED_PARAM, char **argv)
10386 n = number(argv[1]);
10387 if (n > shellparam.nparam)
10388 n = 0; /* bash compat, was = shellparam.nparam; */
10390 shellparam.nparam -= n;
10391 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10392 if (shellparam.malloced)
10395 ap2 = shellparam.p;
10396 while ((*ap2++ = *ap1++) != NULL)
10398 #if ENABLE_ASH_GETOPTS
10399 shellparam.optind = 1;
10400 shellparam.optoff = -1;
10407 * POSIX requires that 'set' (but not export or readonly) output the
10408 * variables in lexicographic order - by the locale's collating order (sigh).
10409 * Maybe we could keep them in an ordered balanced binary tree
10410 * instead of hashed lists.
10411 * For now just roll 'em through qsort for printing...
10414 showvars(const char *sep_prefix, int on, int off)
10417 char **ep, **epend;
10419 ep = listvars(on, off, &epend);
10420 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10422 sep = *sep_prefix ? " " : sep_prefix;
10424 for (; ep < epend; ep++) {
10428 p = strchrnul(*ep, '=');
10431 q = single_quote(++p);
10432 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10438 * The set command builtin.
10440 static int FAST_FUNC
10441 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10446 return showvars(nullstr, 0, VUNSET);
10449 retval = options(/*cmdline:*/ 0);
10450 if (retval == 0) { /* if no parse error... */
10452 if (*argptr != NULL) {
10460 #if ENABLE_ASH_RANDOM_SUPPORT
10461 static void FAST_FUNC
10462 change_random(const char *value)
10466 if (value == NULL) {
10467 /* "get", generate */
10468 t = next_random(&random_gen);
10469 /* set without recursion */
10470 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10471 vrandom.flags &= ~VNOFUNC;
10474 t = strtoul(value, NULL, 10);
10475 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10480 #if ENABLE_ASH_GETOPTS
10482 getopts(char *optstr, char *optvar, char **optfirst)
10489 int ind = shellparam.optind;
10490 int off = shellparam.optoff;
10494 shellparam.optind = -1;
10495 optnext = optfirst + ind - 1;
10497 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10500 p = optnext[-1] + off;
10501 if (p == NULL || *p == '\0') {
10502 /* Current word is done, advance */
10504 if (p == NULL || *p != '-' || *++p == '\0') {
10511 if (LONE_DASH(p)) /* check for "--" */
10516 for (q = optstr; *q != c;) {
10518 if (optstr[0] == ':') {
10520 /*sbuf[1] = '\0'; - already is */
10521 setvar0("OPTARG", sbuf);
10523 fprintf(stderr, "Illegal option -%c\n", c);
10524 unsetvar("OPTARG");
10534 if (*p == '\0' && (p = *optnext) == NULL) {
10535 if (optstr[0] == ':') {
10537 /*sbuf[1] = '\0'; - already is */
10538 setvar0("OPTARG", sbuf);
10541 fprintf(stderr, "No arg for -%c option\n", c);
10542 unsetvar("OPTARG");
10550 setvar0("OPTARG", p);
10553 setvar0("OPTARG", nullstr);
10555 ind = optnext - optfirst + 1;
10556 setvar("OPTIND", itoa(ind), VNOFUNC);
10558 /*sbuf[1] = '\0'; - already is */
10559 setvar0(optvar, sbuf);
10561 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10562 shellparam.optind = ind;
10568 * The getopts builtin. Shellparam.optnext points to the next argument
10569 * to be processed. Shellparam.optptr points to the next character to
10570 * be processed in the current argument. If shellparam.optnext is NULL,
10571 * then it's the first time getopts has been called.
10573 static int FAST_FUNC
10574 getoptscmd(int argc, char **argv)
10579 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10581 optbase = shellparam.p;
10582 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10583 shellparam.optind = 1;
10584 shellparam.optoff = -1;
10587 optbase = &argv[3];
10588 if ((unsigned)shellparam.optind > argc - 2) {
10589 shellparam.optind = 1;
10590 shellparam.optoff = -1;
10594 return getopts(argv[1], argv[2], optbase);
10596 #endif /* ASH_GETOPTS */
10599 /* ============ Shell parser */
10602 struct heredoc *next; /* next here document in list */
10603 union node *here; /* redirection node */
10604 char *eofmark; /* string indicating end of input */
10605 smallint striptabs; /* if set, strip leading tabs */
10608 static smallint tokpushback; /* last token pushed back */
10609 static smallint quoteflag; /* set if (part of) last token was quoted */
10610 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10611 static struct heredoc *heredoclist; /* list of here documents to read */
10612 static char *wordtext; /* text of last word returned by readtoken */
10613 static struct nodelist *backquotelist;
10614 static union node *redirnode;
10615 static struct heredoc *heredoc;
10617 static const char *
10618 tokname(char *buf, int tok)
10621 return tokname_array[tok];
10622 sprintf(buf, "\"%s\"", tokname_array[tok]);
10626 /* raise_error_unexpected_syntax:
10627 * Called when an unexpected token is read during the parse. The argument
10628 * is the token that is expected, or -1 if more than one type of token can
10629 * occur at this point.
10631 static void raise_error_unexpected_syntax(int) NORETURN;
10633 raise_error_unexpected_syntax(int token)
10639 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10641 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10642 raise_error_syntax(msg);
10646 #define EOFMARKLEN 79
10648 /* parsing is heavily cross-recursive, need these forward decls */
10649 static union node *andor(void);
10650 static union node *pipeline(void);
10651 static union node *parse_command(void);
10652 static void parseheredoc(void);
10653 static int peektoken(void);
10654 static int readtoken(void);
10656 static union node *
10659 union node *n1, *n2, *n3;
10664 switch (peektoken()) {
10672 if (!n1 && (nlflag & 1))
10678 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10679 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10685 if (tok == TBACKGND) {
10686 if (n2->type == NPIPE) {
10687 n2->npipe.pipe_backgnd = 1;
10689 if (n2->type != NREDIR) {
10690 n3 = stzalloc(sizeof(struct nredir));
10692 /*n3->nredir.redirect = NULL; - stzalloc did it */
10695 n2->type = NBACKGND;
10701 n3 = stzalloc(sizeof(struct nbinary));
10703 n3->nbinary.ch1 = n1;
10704 n3->nbinary.ch2 = n2;
10717 raise_error_unexpected_syntax(-1);
10724 static union node *
10727 union node *n1, *n2, *n3;
10735 } else if (t == TOR) {
10741 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10743 n3 = stzalloc(sizeof(struct nbinary));
10745 n3->nbinary.ch1 = n1;
10746 n3->nbinary.ch2 = n2;
10751 static union node *
10754 union node *n1, *n2, *pipenode;
10755 struct nodelist *lp, *prev;
10759 TRACE(("pipeline: entered\n"));
10760 if (readtoken() == TNOT) {
10762 checkkwd = CHKKWD | CHKALIAS;
10765 n1 = parse_command();
10766 if (readtoken() == TPIPE) {
10767 pipenode = stzalloc(sizeof(struct npipe));
10768 pipenode->type = NPIPE;
10769 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10770 lp = stzalloc(sizeof(struct nodelist));
10771 pipenode->npipe.cmdlist = lp;
10775 lp = stzalloc(sizeof(struct nodelist));
10776 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10777 lp->n = parse_command();
10779 } while (readtoken() == TPIPE);
10785 n2 = stzalloc(sizeof(struct nnot));
10793 static union node *
10798 n = stzalloc(sizeof(struct narg));
10800 /*n->narg.next = NULL; - stzalloc did it */
10801 n->narg.text = wordtext;
10802 n->narg.backquote = backquotelist;
10807 fixredir(union node *n, const char *text, int err)
10811 TRACE(("Fix redir %s %d\n", text, err));
10813 n->ndup.vname = NULL;
10815 fd = bb_strtou(text, NULL, 10);
10816 if (!errno && fd >= 0)
10817 n->ndup.dupfd = fd;
10818 else if (LONE_DASH(text))
10819 n->ndup.dupfd = -1;
10822 raise_error_syntax("bad fd number");
10823 n->ndup.vname = makename();
10828 * Returns true if the text contains nothing to expand (no dollar signs
10832 noexpand(const char *text)
10836 while ((c = *text++) != '\0') {
10837 if (c == CTLQUOTEMARK)
10841 else if (SIT(c, BASESYNTAX) == CCTL)
10850 union node *n = redirnode;
10852 if (readtoken() != TWORD)
10853 raise_error_unexpected_syntax(-1);
10854 if (n->type == NHERE) {
10855 struct heredoc *here = heredoc;
10859 if (quoteflag == 0)
10861 TRACE(("Here document %d\n", n->type));
10862 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10863 raise_error_syntax("illegal eof marker for << redirection");
10864 rmescapes(wordtext, 0);
10865 here->eofmark = wordtext;
10867 if (heredoclist == NULL)
10868 heredoclist = here;
10870 for (p = heredoclist; p->next; p = p->next)
10874 } else if (n->type == NTOFD || n->type == NFROMFD) {
10875 fixredir(n, wordtext, 0);
10877 n->nfile.fname = makename();
10881 static union node *
10884 union node *args, **app;
10885 union node *n = NULL;
10886 union node *vars, **vpp;
10887 union node **rpp, *redir;
10889 #if ENABLE_ASH_BASH_COMPAT
10890 smallint double_brackets_flag = 0;
10891 smallint function_flag = 0;
10901 savecheckkwd = CHKALIAS;
10904 checkkwd = savecheckkwd;
10907 #if ENABLE_ASH_BASH_COMPAT
10909 if (peektoken() != TWORD)
10910 raise_error_unexpected_syntax(TWORD);
10913 case TAND: /* "&&" */
10914 case TOR: /* "||" */
10915 if (!double_brackets_flag) {
10919 wordtext = (char *) (t == TAND ? "-a" : "-o");
10922 n = stzalloc(sizeof(struct narg));
10924 /*n->narg.next = NULL; - stzalloc did it */
10925 n->narg.text = wordtext;
10926 #if ENABLE_ASH_BASH_COMPAT
10927 if (strcmp("[[", wordtext) == 0)
10928 double_brackets_flag = 1;
10929 else if (strcmp("]]", wordtext) == 0)
10930 double_brackets_flag = 0;
10932 n->narg.backquote = backquotelist;
10933 if (savecheckkwd && isassignment(wordtext)) {
10935 vpp = &n->narg.next;
10938 app = &n->narg.next;
10941 #if ENABLE_ASH_BASH_COMPAT
10942 if (function_flag) {
10943 checkkwd = CHKNL | CHKKWD;
10944 switch (peektoken()) {
10956 if (strcmp("[[", wordtext) == 0)
10960 raise_error_unexpected_syntax(-1);
10966 *rpp = n = redirnode;
10967 rpp = &n->nfile.next;
10968 parsefname(); /* read name of redirection file */
10971 IF_ASH_BASH_COMPAT(do_func:)
10972 if (args && app == &args->narg.next
10975 struct builtincmd *bcmd;
10978 /* We have a function */
10979 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
10980 raise_error_unexpected_syntax(TRP);
10981 name = n->narg.text;
10982 if (!goodname(name)
10983 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10985 raise_error_syntax("bad function name");
10988 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10989 n->narg.next = parse_command();
10992 IF_ASH_BASH_COMPAT(function_flag = 0;)
11003 n = stzalloc(sizeof(struct ncmd));
11005 n->ncmd.args = args;
11006 n->ncmd.assign = vars;
11007 n->ncmd.redirect = redir;
11011 static union node *
11012 parse_command(void)
11014 union node *n1, *n2;
11015 union node *ap, **app;
11016 union node *cp, **cpp;
11017 union node *redir, **rpp;
11024 switch (readtoken()) {
11026 raise_error_unexpected_syntax(-1);
11029 n1 = stzalloc(sizeof(struct nif));
11031 n1->nif.test = list(0);
11032 if (readtoken() != TTHEN)
11033 raise_error_unexpected_syntax(TTHEN);
11034 n1->nif.ifpart = list(0);
11036 while (readtoken() == TELIF) {
11037 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11038 n2 = n2->nif.elsepart;
11040 n2->nif.test = list(0);
11041 if (readtoken() != TTHEN)
11042 raise_error_unexpected_syntax(TTHEN);
11043 n2->nif.ifpart = list(0);
11045 if (lasttoken == TELSE)
11046 n2->nif.elsepart = list(0);
11048 n2->nif.elsepart = NULL;
11056 n1 = stzalloc(sizeof(struct nbinary));
11057 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11058 n1->nbinary.ch1 = list(0);
11061 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11062 got == TWORD ? wordtext : ""));
11063 raise_error_unexpected_syntax(TDO);
11065 n1->nbinary.ch2 = list(0);
11070 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11071 raise_error_syntax("bad for loop variable");
11072 n1 = stzalloc(sizeof(struct nfor));
11074 n1->nfor.var = wordtext;
11075 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11076 if (readtoken() == TIN) {
11078 while (readtoken() == TWORD) {
11079 n2 = stzalloc(sizeof(struct narg));
11081 /*n2->narg.next = NULL; - stzalloc did it */
11082 n2->narg.text = wordtext;
11083 n2->narg.backquote = backquotelist;
11085 app = &n2->narg.next;
11088 n1->nfor.args = ap;
11089 if (lasttoken != TNL && lasttoken != TSEMI)
11090 raise_error_unexpected_syntax(-1);
11092 n2 = stzalloc(sizeof(struct narg));
11094 /*n2->narg.next = NULL; - stzalloc did it */
11095 n2->narg.text = (char *)dolatstr;
11096 /*n2->narg.backquote = NULL;*/
11097 n1->nfor.args = n2;
11099 * Newline or semicolon here is optional (but note
11100 * that the original Bourne shell only allowed NL).
11102 if (lasttoken != TSEMI)
11105 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11106 if (readtoken() != TDO)
11107 raise_error_unexpected_syntax(TDO);
11108 n1->nfor.body = list(0);
11112 n1 = stzalloc(sizeof(struct ncase));
11114 if (readtoken() != TWORD)
11115 raise_error_unexpected_syntax(TWORD);
11116 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11118 /*n2->narg.next = NULL; - stzalloc did it */
11119 n2->narg.text = wordtext;
11120 n2->narg.backquote = backquotelist;
11121 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11122 if (readtoken() != TIN)
11123 raise_error_unexpected_syntax(TIN);
11124 cpp = &n1->ncase.cases;
11126 checkkwd = CHKNL | CHKKWD;
11128 while (t != TESAC) {
11129 if (lasttoken == TLP)
11131 *cpp = cp = stzalloc(sizeof(struct nclist));
11133 app = &cp->nclist.pattern;
11135 *app = ap = stzalloc(sizeof(struct narg));
11137 /*ap->narg.next = NULL; - stzalloc did it */
11138 ap->narg.text = wordtext;
11139 ap->narg.backquote = backquotelist;
11140 if (readtoken() != TPIPE)
11142 app = &ap->narg.next;
11145 //ap->narg.next = NULL;
11146 if (lasttoken != TRP)
11147 raise_error_unexpected_syntax(TRP);
11148 cp->nclist.body = list(2);
11150 cpp = &cp->nclist.next;
11152 checkkwd = CHKNL | CHKKWD;
11156 raise_error_unexpected_syntax(TENDCASE);
11163 n1 = stzalloc(sizeof(struct nredir));
11164 n1->type = NSUBSHELL;
11165 n1->nredir.n = list(0);
11166 /*n1->nredir.redirect = NULL; - stzalloc did it */
11173 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11177 return simplecmd();
11180 if (readtoken() != t)
11181 raise_error_unexpected_syntax(t);
11184 /* Now check for redirection which may follow command */
11185 checkkwd = CHKKWD | CHKALIAS;
11187 while (readtoken() == TREDIR) {
11188 *rpp = n2 = redirnode;
11189 rpp = &n2->nfile.next;
11195 if (n1->type != NSUBSHELL) {
11196 n2 = stzalloc(sizeof(struct nredir));
11201 n1->nredir.redirect = redir;
11206 #if ENABLE_ASH_BASH_COMPAT
11208 decode_dollar_squote(void)
11210 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11216 p = strchr(C_escapes, c);
11221 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11225 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11227 } else if (c == 'x') { /* \xHH */
11231 } while (isxdigit(c) && --cnt);
11233 if (cnt == 3) { /* \x but next char is "bad" */
11237 } else { /* simple seq like \\ or \t */
11242 c = bb_process_escape_sequence((void*)&p);
11243 } else { /* unrecognized "\z": print both chars unless ' or " */
11244 if (c != '\'' && c != '"') {
11246 c |= 0x100; /* "please encode \, then me" */
11254 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11255 * is not NULL, read a here document. In the latter case, eofmark is the
11256 * word which marks the end of the document and striptabs is true if
11257 * leading tabs should be stripped from the document. The argument c
11258 * is the first character of the input token or document.
11260 * Because C does not have internal subroutines, I have simulated them
11261 * using goto's to implement the subroutine linkage. The following macros
11262 * will run code that appears at the end of readtoken1.
11264 #define CHECKEND() {goto checkend; checkend_return:;}
11265 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11266 #define PARSESUB() {goto parsesub; parsesub_return:;}
11267 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11268 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11269 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11271 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11273 /* NB: syntax parameter fits into smallint */
11274 /* c parameter is an unsigned char or PEOF or PEOA */
11277 char line[EOFMARKLEN + 1];
11278 struct nodelist *bqlist;
11282 smallint prevsyntax; /* syntax before arithmetic */
11283 #if ENABLE_ASH_EXPAND_PRMT
11284 smallint pssyntax; /* we are expanding a prompt string */
11286 int varnest; /* levels of variables expansion */
11287 int arinest; /* levels of arithmetic expansion */
11288 int parenlevel; /* levels of parens in arithmetic */
11289 int dqvarnest; /* levels of variables expansion within double quotes */
11291 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11293 startlinno = g_parsefile->linno;
11297 #if ENABLE_ASH_EXPAND_PRMT
11298 pssyntax = (syntax == PSSYNTAX);
11302 dblquote = (syntax == DQSYNTAX);
11308 STARTSTACKSTR(out);
11310 /* For each line, until end of word */
11311 CHECKEND(); /* set c to PEOF if at end of here document */
11312 for (;;) { /* until end of line or end of word */
11313 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11314 switch (SIT(c, syntax)) {
11315 case CNL: /* '\n' */
11316 if (syntax == BASESYNTAX)
11317 goto endword; /* exit outer loop */
11321 goto loop; /* continue outer loop */
11326 #if ENABLE_ASH_BASH_COMPAT
11327 if (c == '\\' && bash_dollar_squote) {
11328 c = decode_dollar_squote();
11330 /* skip $'\000', $'\x00' (like bash) */
11334 /* Unknown escape. Encode as '\z' */
11335 c = (unsigned char)c;
11336 if (eofmark == NULL || dblquote)
11337 USTPUTC(CTLESC, out);
11338 USTPUTC('\\', out);
11342 if (eofmark == NULL || dblquote)
11343 USTPUTC(CTLESC, out);
11346 case CBACK: /* backslash */
11347 c = pgetc_without_PEOA();
11349 USTPUTC(CTLESC, out);
11350 USTPUTC('\\', out);
11352 } else if (c == '\n') {
11355 #if ENABLE_ASH_EXPAND_PRMT
11356 if (c == '$' && pssyntax) {
11357 USTPUTC(CTLESC, out);
11358 USTPUTC('\\', out);
11361 /* Backslash is retained if we are in "str" and next char isn't special */
11366 && (c != '"' || eofmark != NULL)
11368 USTPUTC('\\', out);
11370 USTPUTC(CTLESC, out);
11378 if (eofmark == NULL) {
11379 USTPUTC(CTLQUOTEMARK, out);
11387 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11388 if (eofmark != NULL && varnest == 0) {
11391 if (dqvarnest == 0) {
11392 syntax = BASESYNTAX;
11399 case CVAR: /* '$' */
11400 PARSESUB(); /* parse substitution */
11402 case CENDVAR: /* '}' */
11405 if (dqvarnest > 0) {
11412 #if ENABLE_SH_MATH_SUPPORT
11413 case CLP: /* '(' in arithmetic */
11417 case CRP: /* ')' in arithmetic */
11418 if (parenlevel > 0) {
11421 if (pgetc_eatbnl() == ')') {
11423 if (--arinest == 0) {
11424 syntax = prevsyntax;
11428 * unbalanced parens
11429 * (don't 2nd guess - no error)
11437 case CBQUOTE: /* '`' */
11441 goto endword; /* exit outer loop */
11445 if (varnest == 0) {
11446 #if ENABLE_ASH_BASH_COMPAT
11448 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11449 if (pgetc() == '>')
11450 c = 0x100 + '>'; /* flag &> */
11454 goto endword; /* exit outer loop */
11456 IF_ASH_ALIAS(if (c != PEOA))
11463 #if ENABLE_SH_MATH_SUPPORT
11464 if (syntax == ARISYNTAX)
11465 raise_error_syntax("missing '))'");
11467 if (syntax != BASESYNTAX && eofmark == NULL)
11468 raise_error_syntax("unterminated quoted string");
11469 if (varnest != 0) {
11470 startlinno = g_parsefile->linno;
11472 raise_error_syntax("missing '}'");
11474 USTPUTC('\0', out);
11475 len = out - (char *)stackblock();
11476 out = stackblock();
11477 if (eofmark == NULL) {
11478 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11481 if (isdigit_str9(out)) {
11482 PARSEREDIR(); /* passed as params: out, c */
11483 lasttoken = TREDIR;
11486 /* else: non-number X seen, interpret it
11487 * as "NNNX>file" = "NNNX >file" */
11491 quoteflag = quotef;
11492 backquotelist = bqlist;
11493 grabstackblock(len);
11497 /* end of readtoken routine */
11500 * Check to see whether we are at the end of the here document. When this
11501 * is called, c is set to the first character of the next input line. If
11502 * we are at the end of the here document, this routine sets the c to PEOF.
11506 #if ENABLE_ASH_ALIAS
11508 c = pgetc_without_PEOA();
11511 while (c == '\t') {
11512 c = pgetc_without_PEOA();
11515 if (c == *eofmark) {
11516 if (pfgets(line, sizeof(line)) != NULL) {
11521 for (q = eofmark + 1;; p++, q++) {
11525 if (!*q || cc != *q)
11532 pushstring(line, NULL);
11537 goto checkend_return;
11541 * Parse a redirection operator. The variable "out" points to a string
11542 * specifying the fd to be redirected. The variable "c" contains the
11543 * first character of the redirection operator.
11546 /* out is already checked to be a valid number or "" */
11547 int fd = (*out == '\0' ? -1 : atoi(out));
11550 np = stzalloc(sizeof(struct nfile));
11555 np->type = NAPPEND;
11557 np->type = NCLOBBER;
11560 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11566 #if ENABLE_ASH_BASH_COMPAT
11567 else if (c == 0x100 + '>') { /* this flags &> redirection */
11569 pgetc(); /* this is '>', no need to check */
11573 else { /* c == '<' */
11574 /*np->nfile.fd = 0; - stzalloc did it */
11578 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11579 np = stzalloc(sizeof(struct nhere));
11580 /*np->nfile.fd = 0; - stzalloc did it */
11583 heredoc = stzalloc(sizeof(struct heredoc));
11584 heredoc->here = np;
11587 heredoc->striptabs = 1;
11589 /*heredoc->striptabs = 0; - stzalloc did it */
11595 np->type = NFROMFD;
11599 np->type = NFROMTO;
11611 goto parseredir_return;
11615 * Parse a substitution. At this point, we have read the dollar sign
11616 * and nothing else.
11619 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11620 * (assuming ascii char codes, as the original implementation did) */
11621 #define is_special(c) \
11622 (((unsigned)(c) - 33 < 32) \
11623 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11625 unsigned char subtype;
11628 c = pgetc_eatbnl();
11629 if (c > 255 /* PEOA or PEOF */
11630 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11632 #if ENABLE_ASH_BASH_COMPAT
11633 if (syntax != DQSYNTAX && c == '\'')
11634 bash_dollar_squote = 1;
11639 } else if (c == '(') {
11640 /* $(command) or $((arith)) */
11641 if (pgetc_eatbnl() == '(') {
11642 #if ENABLE_SH_MATH_SUPPORT
11645 raise_error_syntax("you disabled math support for $((arith)) syntax");
11652 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11653 USTPUTC(CTLVAR, out);
11654 typeloc = out - (char *)stackblock();
11656 subtype = VSNORMAL;
11658 c = pgetc_eatbnl();
11663 /* $[{[#]]NAME[}] */
11666 c = pgetc_eatbnl();
11667 } while (is_in_name(c));
11668 } else if (isdigit(c)) {
11669 /* $[{[#]]NUM[}] */
11672 c = pgetc_eatbnl();
11673 } while (isdigit(c));
11674 } else if (is_special(c)) {
11675 /* $[{[#]]<specialchar>[}] */
11678 c = pgetc_eatbnl();
11679 if (!subtype && cc == '#') {
11680 subtype = VSLENGTH;
11681 if (c == '_' || isalnum(c))
11684 c = pgetc_eatbnl();
11685 if (cc == '}' || c != '}') {
11696 if (c != '}' && subtype == VSLENGTH) {
11697 /* ${#VAR didn't end with } */
11701 if (subtype == 0) {
11702 static const char types[] ALIGN1 = "}-+?=";
11703 /* ${VAR...} but not $VAR or ${#VAR} */
11704 /* c == first char after VAR */
11707 c = pgetc_eatbnl();
11708 #if ENABLE_ASH_BASH_COMPAT
11709 /* This check is only needed to not misinterpret
11710 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11713 if (!strchr(types, c)) {
11714 subtype = VSSUBSTR;
11716 break; /* "goto badsub" is bigger (!) */
11722 const char *p = strchr(types, c);
11725 subtype |= p - types + VSNORMAL;
11731 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11732 c = pgetc_eatbnl();
11738 #if ENABLE_ASH_BASH_COMPAT
11740 /* ${v/[/]pattern/repl} */
11741 //TODO: encode pattern and repl separately.
11742 // Currently ${v/$var_with_slash/repl} is horribly broken
11743 subtype = VSREPLACE;
11744 c = pgetc_eatbnl();
11747 subtype++; /* VSREPLACEALL */
11755 ((unsigned char *)stackblock())[typeloc] = subtype;
11756 if (subtype != VSNORMAL) {
11763 goto parsesub_return;
11767 * Called to parse command substitutions. Newstyle is set if the command
11768 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11769 * list of commands (passed by reference), and savelen is the number of
11770 * characters on the top of the stack which must be preserved.
11773 struct nodelist **nlpp;
11777 smallint saveprompt = 0;
11780 savelen = out - (char *)stackblock();
11783 * FIXME: this can allocate very large block on stack and SEGV.
11785 * echo "..<100kbytes>..`true` $(true) `true` ..."
11786 * allocates 100kb for every command subst. With about
11787 * a hundred command substitutions stack overflows.
11788 * With larger prepended string, SEGV happens sooner.
11790 str = alloca(savelen);
11791 memcpy(str, stackblock(), savelen);
11795 /* We must read until the closing backquote, giving special
11796 * treatment to some slashes, and then push the string and
11797 * reread it as input, interpreting it normally.
11803 STARTSTACKSTR(pout);
11807 setprompt_if(needprompt, 2);
11818 * If eating a newline, avoid putting
11819 * the newline into the new character
11820 * stream (via the STPUTC after the
11825 if (pc != '\\' && pc != '`' && pc != '$'
11826 && (!dblquote || pc != '"')
11828 STPUTC('\\', pout);
11830 if (pc <= 255 /* not PEOA or PEOF */) {
11836 IF_ASH_ALIAS(case PEOA:)
11837 startlinno = g_parsefile->linno;
11838 raise_error_syntax("EOF in backquote substitution");
11850 STPUTC('\0', pout);
11851 psavelen = pout - (char *)stackblock();
11852 if (psavelen > 0) {
11853 pstr = grabstackstr(pout);
11854 setinputstring(pstr);
11859 nlpp = &(*nlpp)->next;
11860 *nlpp = stzalloc(sizeof(**nlpp));
11861 /* (*nlpp)->next = NULL; - stzalloc did it */
11864 saveprompt = doprompt;
11871 doprompt = saveprompt;
11872 else if (readtoken() != TRP)
11873 raise_error_unexpected_syntax(TRP);
11878 * Start reading from old file again, ignoring any pushed back
11879 * tokens left from the backquote parsing
11884 while (stackblocksize() <= savelen)
11886 STARTSTACKSTR(out);
11888 memcpy(out, str, savelen);
11889 STADJUST(savelen, out);
11891 USTPUTC(CTLBACKQ, out);
11893 goto parsebackq_oldreturn;
11894 goto parsebackq_newreturn;
11897 #if ENABLE_SH_MATH_SUPPORT
11899 * Parse an arithmetic expansion (indicate start of one and set state)
11902 if (++arinest == 1) {
11903 prevsyntax = syntax;
11904 syntax = ARISYNTAX;
11906 USTPUTC(CTLARI, out);
11907 goto parsearith_return;
11910 } /* end of readtoken */
11913 * Read the next input token.
11914 * If the token is a word, we set backquotelist to the list of cmds in
11915 * backquotes. We set quoteflag to true if any part of the word was
11917 * If the token is TREDIR, then we set redirnode to a structure containing
11919 * In all cases, the variable startlinno is set to the number of the line
11920 * on which the token starts.
11922 * [Change comment: here documents and internal procedures]
11923 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11924 * word parsing code into a separate routine. In this case, readtoken
11925 * doesn't need to have any internal procedures, but parseword does.
11926 * We could also make parseoperator in essence the main routine, and
11927 * have parseword (readtoken1?) handle both words and redirection.]
11929 #define NEW_xxreadtoken
11930 #ifdef NEW_xxreadtoken
11931 /* singles must be first! */
11932 static const char xxreadtoken_chars[7] ALIGN1 = {
11933 '\n', '(', ')', /* singles */
11934 '&', '|', ';', /* doubles */
11938 #define xxreadtoken_singles 3
11939 #define xxreadtoken_doubles 3
11941 static const char xxreadtoken_tokens[] ALIGN1 = {
11942 TNL, TLP, TRP, /* only single occurrence allowed */
11943 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11944 TEOF, /* corresponds to trailing nul */
11945 TAND, TOR, TENDCASE /* if double occurrence */
11957 setprompt_if(needprompt, 2);
11958 startlinno = g_parsefile->linno;
11959 for (;;) { /* until token or start of word found */
11961 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11965 while ((c = pgetc()) != '\n' && c != PEOF)
11968 } else if (c == '\\') {
11969 if (pgetc() != '\n') {
11971 break; /* return readtoken1(...) */
11977 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11983 p = strchr(xxreadtoken_chars, c);
11985 break; /* return readtoken1(...) */
11987 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11989 if (cc == c) { /* double occurrence? */
11990 p += xxreadtoken_doubles + 1;
11993 #if ENABLE_ASH_BASH_COMPAT
11994 if (c == '&' && cc == '>') /* &> */
11995 break; /* return readtoken1(...) */
12000 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12005 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12007 #else /* old xxreadtoken */
12008 #define RETURN(token) return lasttoken = token
12018 setprompt_if(needprompt, 2);
12019 startlinno = g_parsefile->linno;
12020 for (;;) { /* until token or start of word found */
12023 case ' ': case '\t':
12024 IF_ASH_ALIAS(case PEOA:)
12027 while ((c = pgetc()) != '\n' && c != PEOF)
12032 if (pgetc() == '\n') {
12044 if (pgetc() == '&')
12049 if (pgetc() == '|')
12054 if (pgetc() == ';')
12067 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12070 #endif /* old xxreadtoken */
12076 int kwd = checkkwd;
12078 smallint alreadyseen = tokpushback;
12081 #if ENABLE_ASH_ALIAS
12097 if (t != TWORD || quoteflag) {
12102 * check for keywords
12104 if (kwd & CHKKWD) {
12105 const char *const *pp;
12107 pp = findkwd(wordtext);
12109 lasttoken = t = pp - tokname_array;
12110 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12115 if (checkkwd & CHKALIAS) {
12116 #if ENABLE_ASH_ALIAS
12118 ap = lookupalias(wordtext, 1);
12121 pushstring(ap->val, ap);
12131 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12133 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12149 * Read and parse a command. Returns NODE_EOF on end of file.
12150 * (NULL is a valid parse tree indicating a blank line.)
12152 static union node *
12153 parsecmd(int interact)
12158 doprompt = interact;
12159 setprompt_if(doprompt, doprompt);
12165 * Input any here documents.
12170 struct heredoc *here;
12173 here = heredoclist;
12174 heredoclist = NULL;
12177 setprompt_if(needprompt, 2);
12178 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12179 here->eofmark, here->striptabs);
12180 n = stzalloc(sizeof(struct narg));
12181 n->narg.type = NARG;
12182 /*n->narg.next = NULL; - stzalloc did it */
12183 n->narg.text = wordtext;
12184 n->narg.backquote = backquotelist;
12185 here->here->nhere.doc = n;
12192 * called by editline -- any expansions to the prompt should be added here.
12194 #if ENABLE_ASH_EXPAND_PRMT
12195 static const char *
12196 expandstr(const char *ps)
12201 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12202 * and token processing _can_ alter it (delete NULs etc). */
12203 setinputstring((char *)ps);
12205 saveprompt = doprompt;
12207 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12208 doprompt = saveprompt;
12212 n.narg.type = NARG;
12213 n.narg.next = NULL;
12214 n.narg.text = wordtext;
12215 n.narg.backquote = backquotelist;
12217 expandarg(&n, NULL, EXP_QUOTED);
12218 return stackblock();
12223 * Execute a command or commands contained in a string.
12226 evalstring(char *s, int flags)
12229 struct stackmark smark;
12234 setstackmark(&smark);
12237 while ((n = parsecmd(0)) != NODE_EOF) {
12240 i = evaltree(n, flags);
12243 popstackmark(&smark);
12247 popstackmark(&smark);
12255 * The eval command.
12257 static int FAST_FUNC
12258 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12267 STARTSTACKSTR(concat);
12269 concat = stack_putstr(p, concat);
12273 STPUTC(' ', concat);
12275 STPUTC('\0', concat);
12276 p = grabstackstr(concat);
12278 return evalstring(p, flags & EV_TESTED);
12284 * Read and execute commands.
12285 * "Top" is nonzero for the top level command loop;
12286 * it turns on prompting if the shell is interactive.
12292 struct stackmark smark;
12297 TRACE(("cmdloop(%d) called\n", top));
12301 setstackmark(&smark);
12304 showjobs(SHOW_CHANGED|SHOW_STDERR);
12307 if (iflag && top) {
12311 n = parsecmd(inter);
12313 if (DEBUG > 2 && debug && (n != NODE_EOF))
12316 if (n == NODE_EOF) {
12317 if (!top || numeof >= 50)
12319 if (!stoppedjobs()) {
12322 out2str("\nUse \"exit\" to leave shell.\n");
12325 } else if (nflag == 0) {
12328 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12331 i = evaltree(n, 0);
12335 popstackmark(&smark);
12339 evalskip &= ~SKIPFUNC;
12347 * Take commands from a file. To be compatible we should do a path
12348 * search for the file, which is necessary to find sub-commands.
12351 find_dot_file(char *name)
12354 const char *path = pathval();
12357 /* don't try this for absolute or relative paths */
12358 if (strchr(name, '/'))
12361 /* IIRC standards do not say whether . is to be searched.
12362 * And it is even smaller this way, making it unconditional for now:
12364 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12369 while ((fullname = path_advance(&path, name)) != NULL) {
12371 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12373 * Don't bother freeing here, since it will
12374 * be freed by the caller.
12378 if (fullname != name)
12379 stunalloc(fullname);
12382 /* not found in the PATH */
12383 ash_msg_and_raise_error("%s: not found", name);
12387 static int FAST_FUNC
12388 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12390 /* "false; . empty_file; echo $?" should print 0, not 1: */
12394 struct strlist *sp;
12395 volatile struct shparam saveparam;
12397 for (sp = cmdenviron; sp; sp = sp->next)
12398 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12400 nextopt(nullstr); /* handle possible "--" */
12404 /* bash says: "bash: .: filename argument required" */
12405 return 2; /* bash compat */
12408 /* This aborts if file isn't found, which is POSIXly correct.
12409 * bash returns exitcode 1 instead.
12411 fullname = find_dot_file(argv[0]);
12413 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12415 saveparam = shellparam;
12416 shellparam.malloced = 0;
12420 shellparam.nparam = argc;
12421 shellparam.p = argv;
12424 /* This aborts if file can't be opened, which is POSIXly correct.
12425 * bash returns exitcode 1 instead.
12427 setinputfile(fullname, INPUT_PUSH_FILE);
12428 commandname = fullname;
12429 status = cmdloop(0);
12433 freeparam(&shellparam);
12434 shellparam = saveparam;
12440 static int FAST_FUNC
12441 exitcmd(int argc UNUSED_PARAM, char **argv)
12446 exitstatus = number(argv[1]);
12447 raise_exception(EXEXIT);
12452 * Read a file containing shell functions.
12455 readcmdfile(char *name)
12457 setinputfile(name, INPUT_PUSH_FILE);
12463 /* ============ find_command inplementation */
12466 * Resolve a command name. If you change this routine, you may have to
12467 * change the shellexec routine as well.
12470 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12472 struct tblentry *cmdp;
12479 struct builtincmd *bcmd;
12481 /* If name contains a slash, don't use PATH or hash table */
12482 if (strchr(name, '/') != NULL) {
12483 entry->u.index = -1;
12484 if (act & DO_ABS) {
12485 while (stat(name, &statb) < 0) {
12487 if (errno == EINTR)
12490 entry->cmdtype = CMDUNKNOWN;
12494 entry->cmdtype = CMDNORMAL;
12498 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12500 updatetbl = (path == pathval());
12503 if (strstr(path, "%builtin") != NULL)
12504 act |= DO_ALTBLTIN;
12507 /* If name is in the table, check answer will be ok */
12508 cmdp = cmdlookup(name, 0);
12509 if (cmdp != NULL) {
12512 switch (cmdp->cmdtype) {
12530 } else if (cmdp->rehash == 0)
12531 /* if not invalidated by cd, we're done */
12535 /* If %builtin not in path, check for builtin next */
12536 bcmd = find_builtin(name);
12538 if (IS_BUILTIN_REGULAR(bcmd))
12539 goto builtin_success;
12540 if (act & DO_ALTPATH) {
12541 if (!(act & DO_ALTBLTIN))
12542 goto builtin_success;
12543 } else if (builtinloc <= 0) {
12544 goto builtin_success;
12548 #if ENABLE_FEATURE_SH_STANDALONE
12550 int applet_no = find_applet_by_name(name);
12551 if (applet_no >= 0) {
12552 entry->cmdtype = CMDNORMAL;
12553 entry->u.index = -2 - applet_no;
12559 /* We have to search path. */
12560 prev = -1; /* where to start */
12561 if (cmdp && cmdp->rehash) { /* doing a rehash */
12562 if (cmdp->cmdtype == CMDBUILTIN)
12565 prev = cmdp->param.index;
12571 while ((fullname = path_advance(&path, name)) != NULL) {
12572 stunalloc(fullname);
12573 /* NB: code below will still use fullname
12574 * despite it being "unallocated" */
12577 if (prefix(pathopt, "builtin")) {
12579 goto builtin_success;
12582 if ((act & DO_NOFUNC)
12583 || !prefix(pathopt, "func")
12584 ) { /* ignore unimplemented options */
12588 /* if rehash, don't redo absolute path names */
12589 if (fullname[0] == '/' && idx <= prev) {
12592 TRACE(("searchexec \"%s\": no change\n", name));
12595 while (stat(fullname, &statb) < 0) {
12597 if (errno == EINTR)
12600 if (errno != ENOENT && errno != ENOTDIR)
12604 e = EACCES; /* if we fail, this will be the error */
12605 if (!S_ISREG(statb.st_mode))
12607 if (pathopt) { /* this is a %func directory */
12608 stalloc(strlen(fullname) + 1);
12609 /* NB: stalloc will return space pointed by fullname
12610 * (because we don't have any intervening allocations
12611 * between stunalloc above and this stalloc) */
12612 readcmdfile(fullname);
12613 cmdp = cmdlookup(name, 0);
12614 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12615 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12616 stunalloc(fullname);
12619 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12621 entry->cmdtype = CMDNORMAL;
12622 entry->u.index = idx;
12626 cmdp = cmdlookup(name, 1);
12627 cmdp->cmdtype = CMDNORMAL;
12628 cmdp->param.index = idx;
12633 /* We failed. If there was an entry for this command, delete it */
12634 if (cmdp && updatetbl)
12635 delete_cmd_entry();
12637 ash_msg("%s: %s", name, errmsg(e, "not found"));
12638 entry->cmdtype = CMDUNKNOWN;
12643 entry->cmdtype = CMDBUILTIN;
12644 entry->u.cmd = bcmd;
12648 cmdp = cmdlookup(name, 1);
12649 cmdp->cmdtype = CMDBUILTIN;
12650 cmdp->param.cmd = bcmd;
12654 entry->cmdtype = cmdp->cmdtype;
12655 entry->u = cmdp->param;
12660 * The trap builtin.
12662 static int FAST_FUNC
12663 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12667 int signo, exitcode;
12672 for (signo = 0; signo < NSIG; signo++) {
12673 char *tr = trap_ptr[signo];
12675 /* note: bash adds "SIG", but only if invoked
12676 * as "bash". If called as "sh", or if set -o posix,
12677 * then it prints short signal names.
12678 * We are printing short names: */
12679 out1fmt("trap -- %s %s\n",
12681 get_signame(signo));
12682 /* trap_ptr != trap only if we are in special-cased `trap` code.
12683 * In this case, we will exit very soon, no need to free(). */
12684 /* if (trap_ptr != trap && tp[0]) */
12689 if (trap_ptr != trap) {
12702 signo = get_signum(*ap);
12704 /* Mimic bash message exactly */
12705 ash_msg("%s: invalid signal specification", *ap);
12711 if (LONE_DASH(action))
12714 if (action[0]) /* not NULL and not "" and not "-" */
12715 may_have_traps = 1;
12716 action = ckstrdup(action);
12720 trap[signo] = action;
12731 /* ============ Builtins */
12733 #if ENABLE_ASH_HELP
12734 static int FAST_FUNC
12735 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12741 "Built-in commands:\n"
12742 "------------------\n");
12743 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12744 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12745 builtintab[i].name + 1);
12751 # if ENABLE_FEATURE_SH_STANDALONE
12753 const char *a = applet_names;
12755 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12760 while (*a++ != '\0')
12765 newline_and_flush(stdout);
12766 return EXIT_SUCCESS;
12771 static int FAST_FUNC
12772 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12774 show_history(line_input_state);
12775 return EXIT_SUCCESS;
12780 * The export and readonly commands.
12782 static int FAST_FUNC
12783 exportcmd(int argc UNUSED_PARAM, char **argv)
12793 /* "readonly" in bash accepts, but ignores -n.
12794 * We do the same: it saves a conditional in nextopt's param.
12797 while ((opt = nextopt("np")) != '\0') {
12799 flag_off = VEXPORT;
12802 if (argv[0][0] == 'r') {
12804 flag_off = 0; /* readonly ignores -n */
12806 flag_off = ~flag_off;
12808 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12814 p = strchr(name, '=');
12818 vp = *findvar(hashvar(name), name);
12820 vp->flags = ((vp->flags | flag) & flag_off);
12824 setvar(name, p, (flag & flag_off));
12825 } while ((name = *++aptr) != NULL);
12830 /* No arguments. Show the list of exported or readonly vars.
12833 showvars(argv[0], flag, 0);
12838 * Delete a function if it exists.
12841 unsetfunc(const char *name)
12843 struct tblentry *cmdp;
12845 cmdp = cmdlookup(name, 0);
12846 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12847 delete_cmd_entry();
12851 * The unset builtin command. We unset the function before we unset the
12852 * variable to allow a function to be unset when there is a readonly variable
12853 * with the same name.
12855 static int FAST_FUNC
12856 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12863 while ((i = nextopt("vf")) != 0) {
12867 for (ap = argptr; *ap; ap++) {
12880 static const unsigned char timescmd_str[] ALIGN1 = {
12881 ' ', offsetof(struct tms, tms_utime),
12882 '\n', offsetof(struct tms, tms_stime),
12883 ' ', offsetof(struct tms, tms_cutime),
12884 '\n', offsetof(struct tms, tms_cstime),
12887 static int FAST_FUNC
12888 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12890 unsigned long clk_tck, s, t;
12891 const unsigned char *p;
12894 clk_tck = bb_clk_tck();
12899 t = *(clock_t *)(((char *) &buf) + p[1]);
12902 out1fmt("%lum%lu.%03lus%c",
12904 (t * 1000) / clk_tck,
12912 #if ENABLE_SH_MATH_SUPPORT
12914 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12915 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12917 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12919 static int FAST_FUNC
12920 letcmd(int argc UNUSED_PARAM, char **argv)
12926 ash_msg_and_raise_error("expression expected");
12928 i = ash_arith(*argv);
12936 * The read builtin. Options:
12937 * -r Do not interpret '\' specially
12938 * -s Turn off echo (tty only)
12939 * -n NCHARS Read NCHARS max
12940 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12941 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12942 * -u FD Read from given FD instead of fd 0
12943 * This uses unbuffered input, which may be avoidable in some cases.
12944 * TODO: bash also has:
12945 * -a ARRAY Read into array[0],[1],etc
12946 * -d DELIM End on DELIM char, not newline
12947 * -e Use line editing (tty only)
12949 static int FAST_FUNC
12950 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12952 char *opt_n = NULL;
12953 char *opt_p = NULL;
12954 char *opt_t = NULL;
12955 char *opt_u = NULL;
12956 int read_flags = 0;
12960 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12969 read_flags |= BUILTIN_READ_SILENT;
12975 read_flags |= BUILTIN_READ_RAW;
12985 /* "read -s" needs to save/restore termios, can't allow ^C
12986 * to jump out of it.
12989 r = shell_builtin_read(setvar0,
12991 bltinlookup("IFS"), /* can be NULL */
13000 if ((uintptr_t)r > 1)
13001 ash_msg_and_raise_error(r);
13003 return (uintptr_t)r;
13006 static int FAST_FUNC
13007 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13009 static const char permuser[3] ALIGN1 = "ogu";
13012 int symbolic_mode = 0;
13014 while (nextopt("S") != '\0') {
13023 if (*argptr == NULL) {
13024 if (symbolic_mode) {
13025 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13032 *p++ = permuser[i];
13034 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13035 if (!(mask & 0400)) *p++ = 'r';
13036 if (!(mask & 0200)) *p++ = 'w';
13037 if (!(mask & 0100)) *p++ = 'x';
13045 out1fmt("%04o\n", mask);
13048 char *modestr = *argptr;
13049 /* numeric umasks are taken as-is */
13050 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13051 if (!isdigit(modestr[0]))
13053 mask = bb_parse_mode(modestr, mask);
13054 if ((unsigned)mask > 0777) {
13055 ash_msg_and_raise_error("illegal mode: %s", modestr);
13057 if (!isdigit(modestr[0]))
13064 static int FAST_FUNC
13065 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13067 return shell_builtin_ulimit(argv);
13070 /* ============ main() and helpers */
13073 * Called to exit the shell.
13082 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13083 save_history(line_input_state);
13085 status = exitstatus;
13086 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13087 if (setjmp(loc.loc)) {
13088 if (exception_type == EXEXIT)
13089 status = exitstatus;
13092 exception_handler = &loc;
13098 /*free(p); - we'll exit soon */
13101 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13102 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13105 flush_stdout_stderr();
13113 /* we will never free this */
13114 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13116 signal(SIGCHLD, SIG_DFL);
13117 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13118 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13120 signal(SIGHUP, SIG_DFL);
13125 struct stat st1, st2;
13128 for (envp = environ; envp && *envp; envp++) {
13129 p = endofname(*envp);
13130 if (p != *envp && *p == '=') {
13131 setvareq(*envp, VEXPORT|VTEXTFIXED);
13135 setvareq((char*)defoptindvar, VTEXTFIXED);
13137 setvar0("PPID", utoa(getppid()));
13138 #if ENABLE_ASH_BASH_COMPAT
13139 p = lookupvar("SHLVL");
13140 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13141 if (!lookupvar("HOSTNAME")) {
13142 struct utsname uts;
13144 setvar0("HOSTNAME", uts.nodename);
13147 p = lookupvar("PWD");
13149 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13150 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13160 //usage:#define ash_trivial_usage
13161 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13162 //usage:#define ash_full_usage "\n\n"
13163 //usage: "Unix shell interpreter"
13165 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13166 //usage:# define sh_trivial_usage ash_trivial_usage
13167 //usage:# define sh_full_usage ash_full_usage
13169 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13170 //usage:# define bash_trivial_usage ash_trivial_usage
13171 //usage:# define bash_full_usage ash_full_usage
13175 * Process the shell command line arguments.
13178 procargs(char **argv)
13181 const char *xminusc;
13186 /* if (xargv[0]) - mmm, this is always true! */
13188 for (i = 0; i < NOPTS; i++)
13191 if (options(/*cmdline:*/ 1)) {
13192 /* it already printed err message */
13193 raise_exception(EXERROR);
13197 if (*xargv == NULL) {
13199 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13202 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13206 for (i = 0; i < NOPTS; i++)
13207 if (optlist[i] == 2)
13212 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13217 } else if (!sflag) {
13218 setinputfile(*xargv, 0);
13221 commandname = arg0;
13224 shellparam.p = xargv;
13225 #if ENABLE_ASH_GETOPTS
13226 shellparam.optind = 1;
13227 shellparam.optoff = -1;
13229 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13231 shellparam.nparam++;
13238 * Read /etc/profile, ~/.profile, $ENV.
13241 read_profile(const char *name)
13243 name = expandstr(name);
13244 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13251 * This routine is called when an error or an interrupt occurs in an
13252 * interactive shell and control is returned to the main command loop.
13253 * (In dash, this function is auto-generated by build machinery).
13262 /* from expand.c: */
13265 /* from input.c: */
13266 g_parsefile->left_in_buffer = 0;
13267 g_parsefile->left_in_line = 0; /* clear input buffer */
13270 /* from redir.c: */
13272 popredir(/*drop:*/ 0, /*restore:*/ 0);
13276 static short profile_buf[16384];
13277 extern int etext();
13281 * Main routine. We initialize things, parse the arguments, execute
13282 * profiles if we're a login shell, and then call cmdloop to execute
13283 * commands. The setjmp call sets up the location to jump to when an
13284 * exception occurs. When an exception occurs the variable "state"
13285 * is used to figure out how far we had gotten.
13287 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13288 int ash_main(int argc UNUSED_PARAM, char **argv)
13290 volatile smallint state;
13291 struct jmploc jmploc;
13292 struct stackmark smark;
13294 /* Initialize global data */
13298 #if ENABLE_ASH_ALIAS
13304 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13307 #if ENABLE_FEATURE_EDITING
13308 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13311 if (setjmp(jmploc.loc)) {
13317 e = exception_type;
13319 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13323 newline_and_flush(stderr);
13326 popstackmark(&smark);
13327 FORCE_INT_ON; /* enable interrupts */
13336 exception_handler = &jmploc;
13339 TRACE(("Shell args: "));
13340 trace_puts_args(argv);
13342 rootpid = getpid();
13345 setstackmark(&smark);
13348 if (argv[0] && argv[0][0] == '-')
13354 read_profile("/etc/profile");
13357 hp = lookupvar("HOME");
13359 read_profile("$HOME/.profile");
13365 getuid() == geteuid() && getgid() == getegid() &&
13369 const char *shinit = lookupvar("ENV");
13370 if (shinit != NULL && *shinit != '\0')
13371 read_profile(shinit);
13373 popstackmark(&smark);
13377 /* evalstring pushes parsefile stack.
13378 * Ensure we don't falsely claim that 0 (stdin)
13379 * is one of stacked source fds.
13380 * Testcase: ash -c 'exec 1>&0' must not complain. */
13381 // if (!sflag) g_parsefile->pf_fd = -1;
13382 // ^^ not necessary since now we special-case fd 0
13383 // in is_hidden_fd() to not be considered "hidden fd"
13384 evalstring(minusc, 0);
13387 if (sflag || minusc == NULL) {
13388 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13390 const char *hp = lookupvar("HISTFILE");
13392 hp = lookupvar("HOME");
13394 hp = concat_path_file(hp, ".ash_history");
13395 setvar0("HISTFILE", hp);
13397 hp = lookupvar("HISTFILE");
13401 line_input_state->hist_file = hp;
13402 # if ENABLE_FEATURE_SH_HISTFILESIZE
13403 hp = lookupvar("HISTFILESIZE");
13404 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13408 state4: /* XXX ??? - why isn't this before the "if" statement */
13416 extern void _mcleanup(void);
13420 TRACE(("End of main reached\n"));
13427 * Copyright (c) 1989, 1991, 1993, 1994
13428 * The Regents of the University of California. All rights reserved.
13430 * This code is derived from software contributed to Berkeley by
13431 * Kenneth Almquist.
13433 * Redistribution and use in source and binary forms, with or without
13434 * modification, are permitted provided that the following conditions
13436 * 1. Redistributions of source code must retain the above copyright
13437 * notice, this list of conditions and the following disclaimer.
13438 * 2. Redistributions in binary form must reproduce the above copyright
13439 * notice, this list of conditions and the following disclaimer in the
13440 * documentation and/or other materials provided with the distribution.
13441 * 3. Neither the name of the University nor the names of its contributors
13442 * may be used to endorse or promote products derived from this software
13443 * without specific prior written permission.
13445 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13446 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13447 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13448 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13449 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13450 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13451 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13452 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13453 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13454 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF