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 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
299 /* last pending signal */
300 volatile /*sig_atomic_t*/ smallint pending_sig;
301 smallint exception_type; /* kind of exception (0..5) */
303 #define EXINT 0 /* SIGINT received */
304 #define EXERROR 1 /* a generic error */
305 #define EXEXIT 4 /* exit the shell */
308 char nullstr[1]; /* zero length string */
311 #define eflag optlist[0]
312 #define fflag optlist[1]
313 #define Iflag optlist[2]
314 #define iflag optlist[3]
315 #define mflag optlist[4]
316 #define nflag optlist[5]
317 #define sflag optlist[6]
318 #define xflag optlist[7]
319 #define vflag optlist[8]
320 #define Cflag optlist[9]
321 #define aflag optlist[10]
322 #define bflag optlist[11]
323 #define uflag optlist[12]
324 #define viflag optlist[13]
325 #if ENABLE_ASH_BASH_COMPAT
326 # define pipefail optlist[14]
331 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
332 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
335 /* trap handler commands */
337 * Sigmode records the current value of the signal handlers for the various
338 * modes. A value of zero means that the current handler is not known.
339 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
341 char sigmode[NSIG - 1];
342 #define S_DFL 1 /* default signal handling (SIG_DFL) */
343 #define S_CATCH 2 /* signal is caught */
344 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
345 #define S_HARD_IGN 4 /* signal is ignored permanently */
347 /* indicates specified signal received */
348 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
349 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
351 char **trap_ptr; /* used only by "trap hack" */
353 /* Rarely referenced stuff */
354 #if ENABLE_ASH_RANDOM_SUPPORT
357 pid_t backgndpid; /* pid of last background process */
359 extern struct globals_misc *const ash_ptr_to_globals_misc;
360 #define G_misc (*ash_ptr_to_globals_misc)
361 #define exitstatus (G_misc.exitstatus )
362 #define back_exitstatus (G_misc.back_exitstatus )
363 #define job_warning (G_misc.job_warning)
364 #define rootpid (G_misc.rootpid )
365 #define shlvl (G_misc.shlvl )
366 #define minusc (G_misc.minusc )
367 #define curdir (G_misc.curdir )
368 #define physdir (G_misc.physdir )
369 #define arg0 (G_misc.arg0 )
370 #define exception_handler (G_misc.exception_handler)
371 #define exception_type (G_misc.exception_type )
372 #define suppress_int (G_misc.suppress_int )
373 #define pending_int (G_misc.pending_int )
374 #define got_sigchld (G_misc.got_sigchld )
375 #define pending_sig (G_misc.pending_sig )
376 #define isloginsh (G_misc.isloginsh )
377 #define nullstr (G_misc.nullstr )
378 #define optlist (G_misc.optlist )
379 #define sigmode (G_misc.sigmode )
380 #define gotsig (G_misc.gotsig )
381 #define may_have_traps (G_misc.may_have_traps )
382 #define trap (G_misc.trap )
383 #define trap_ptr (G_misc.trap_ptr )
384 #define random_gen (G_misc.random_gen )
385 #define backgndpid (G_misc.backgndpid )
386 #define INIT_G_misc() do { \
387 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
395 /* ============ DEBUG */
397 static void trace_printf(const char *fmt, ...);
398 static void trace_vprintf(const char *fmt, va_list va);
399 # define TRACE(param) trace_printf param
400 # define TRACEV(param) trace_vprintf param
401 # define close(fd) do { \
403 if (close(dfd) < 0) \
404 bb_error_msg("bug on %d: closing %d(0x%x)", \
405 __LINE__, dfd, dfd); \
408 # define TRACE(param)
409 # define TRACEV(param)
413 /* ============ Utility functions */
414 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
415 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
418 isdigit_str9(const char *str)
420 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
421 while (--maxlen && isdigit(*str))
423 return (*str == '\0');
427 var_end(const char *var)
436 /* ============ Interrupts / exceptions */
438 static void exitshell(void) NORETURN;
441 * These macros allow the user to suspend the handling of interrupt signals
442 * over a period of time. This is similar to SIGHOLD or to sigblock, but
443 * much more efficient and portable. (But hacking the kernel is so much
444 * more fun than worrying about efficiency and portability. :-))
446 #define INT_OFF do { \
452 * Called to raise an exception. Since C doesn't include exceptions, we
453 * just do a longjmp to the exception handler. The type of exception is
454 * stored in the global variable "exception_type".
456 static void raise_exception(int) NORETURN;
458 raise_exception(int e)
461 if (exception_handler == NULL)
466 longjmp(exception_handler->loc, 1);
469 #define raise_exception(e) do { \
470 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
471 raise_exception(e); \
476 * Called when a SIGINT is received. (If the user specifies
477 * that SIGINT is to be trapped or ignored using the trap builtin, then
478 * this routine is not called.) Suppressint is nonzero when interrupts
479 * are held using the INT_OFF macro. (The test for iflag is just
480 * defensive programming.)
482 static void raise_interrupt(void) NORETURN;
484 raise_interrupt(void)
487 /* Signal is not automatically unmasked after it is raised,
488 * do it ourself - unmask all signals */
489 sigprocmask_allsigs(SIG_UNBLOCK);
490 /* pending_sig = 0; - now done in signal_handler() */
492 if (!(rootshell && iflag)) {
493 /* Kill ourself with SIGINT */
494 signal(SIGINT, SIG_DFL);
497 /* bash: ^C even on empty command line sets $? */
498 exitstatus = SIGINT + 128;
499 raise_exception(EXINT);
503 #define raise_interrupt() do { \
504 TRACE(("raising interrupt on line %d\n", __LINE__)); \
509 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
513 if (--suppress_int == 0 && pending_int) {
517 #define INT_ON int_on()
518 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
526 #define FORCE_INT_ON force_int_on()
528 #define SAVE_INT(v) ((v) = suppress_int)
530 #define RESTORE_INT(v) do { \
532 suppress_int = (v); \
533 if (suppress_int == 0 && pending_int) \
538 /* ============ Stdout/stderr output */
541 outstr(const char *p, FILE *file)
549 flush_stdout_stderr(void)
556 /* Was called outcslow(c,FILE*), but c was always '\n' */
558 newline_and_flush(FILE *dest)
566 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
568 out1fmt(const char *fmt, ...)
575 r = vprintf(fmt, ap);
581 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
583 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
590 ret = vsnprintf(outbuf, length, fmt, ap);
597 out1str(const char *p)
603 out2str(const char *p)
606 flush_stdout_stderr();
610 /* ============ Parser structures */
612 /* control characters in argument strings */
613 #define CTL_FIRST CTLESC
614 #define CTLESC ((unsigned char)'\201') /* escape next character */
615 #define CTLVAR ((unsigned char)'\202') /* variable defn */
616 #define CTLENDVAR ((unsigned char)'\203')
617 #define CTLBACKQ ((unsigned char)'\204')
618 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
619 #define CTLENDARI ((unsigned char)'\207')
620 #define CTLQUOTEMARK ((unsigned char)'\210')
621 #define CTL_LAST CTLQUOTEMARK
623 /* variable substitution byte (follows CTLVAR) */
624 #define VSTYPE 0x0f /* type of variable substitution */
625 #define VSNUL 0x10 /* colon--treat the empty string as unset */
627 /* values of VSTYPE field */
628 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
629 #define VSMINUS 0x2 /* ${var-text} */
630 #define VSPLUS 0x3 /* ${var+text} */
631 #define VSQUESTION 0x4 /* ${var?message} */
632 #define VSASSIGN 0x5 /* ${var=text} */
633 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
634 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
635 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
636 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
637 #define VSLENGTH 0xa /* ${#var} */
638 #if ENABLE_ASH_BASH_COMPAT
639 #define VSSUBSTR 0xc /* ${var:position:length} */
640 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
641 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
644 static const char dolatstr[] ALIGN1 = {
645 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
647 #define DOLATSTRLEN 6
666 #if ENABLE_ASH_BASH_COMPAT
683 smallint type; /* Nxxxx */
686 union node *redirect;
691 smallint pipe_backgnd;
692 struct nodelist *cmdlist;
698 union node *redirect;
711 union node *elsepart;
738 struct nodelist *backquote;
741 /* nfile and ndup layout must match!
742 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
743 * that it is actually NTO2 (>&file), and change its type.
760 char *_unused_expfname;
779 struct nredir nredir;
780 struct nbinary nbinary;
784 struct nclist nclist;
793 * NODE_EOF is returned by parsecmd when it encounters an end of file.
794 * It must be distinct from NULL.
796 #define NODE_EOF ((union node *) -1L)
799 struct nodelist *next;
812 freefunc(struct funcnode *f)
814 if (f && --f->count < 0)
819 /* ============ Debugging output */
823 static FILE *tracefile;
826 trace_printf(const char *fmt, ...)
833 fprintf(tracefile, "%u ", (int) time(NULL));
835 fprintf(tracefile, "[%u] ", (int) getpid());
837 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
839 vfprintf(tracefile, fmt, va);
844 trace_vprintf(const char *fmt, va_list va)
849 fprintf(tracefile, "%u ", (int) time(NULL));
851 fprintf(tracefile, "[%u] ", (int) getpid());
853 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
854 vfprintf(tracefile, fmt, va);
858 trace_puts(const char *s)
866 trace_puts_quoted(char *s)
873 putc('"', tracefile);
874 for (p = s; *p; p++) {
875 switch ((unsigned char)*p) {
876 case '\n': c = 'n'; goto backslash;
877 case '\t': c = 't'; goto backslash;
878 case '\r': c = 'r'; goto backslash;
879 case '\"': c = '\"'; goto backslash;
880 case '\\': c = '\\'; goto backslash;
881 case CTLESC: c = 'e'; goto backslash;
882 case CTLVAR: c = 'v'; goto backslash;
883 case CTLBACKQ: c = 'q'; goto backslash;
885 putc('\\', tracefile);
889 if (*p >= ' ' && *p <= '~')
892 putc('\\', tracefile);
893 putc((*p >> 6) & 03, tracefile);
894 putc((*p >> 3) & 07, tracefile);
895 putc(*p & 07, tracefile);
900 putc('"', tracefile);
904 trace_puts_args(char **ap)
911 trace_puts_quoted(*ap);
913 putc('\n', tracefile);
916 putc(' ', tracefile);
931 /* leave open because libedit might be using it */
934 strcpy(s, "./trace");
936 if (!freopen(s, "a", tracefile)) {
937 fprintf(stderr, "Can't re-open %s\n", s);
942 tracefile = fopen(s, "a");
943 if (tracefile == NULL) {
944 fprintf(stderr, "Can't open %s\n", s);
950 flags = fcntl(fileno(tracefile), F_GETFL);
952 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
954 setlinebuf(tracefile);
955 fputs("\nTracing started.\n", tracefile);
959 indent(int amount, char *pfx, FILE *fp)
963 for (i = 0; i < amount; i++) {
964 if (pfx && i == amount - 1)
970 /* little circular references here... */
971 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
974 sharg(union node *arg, FILE *fp)
977 struct nodelist *bqlist;
978 unsigned char subtype;
980 if (arg->type != NARG) {
981 out1fmt("<node type %d>\n", arg->type);
984 bqlist = arg->narg.backquote;
985 for (p = arg->narg.text; *p; p++) {
986 switch ((unsigned char)*p) {
995 if (subtype == VSLENGTH)
1003 if (subtype & VSNUL)
1006 switch (subtype & VSTYPE) {
1032 case VSTRIMRIGHTMAX:
1039 out1fmt("<subtype %d>", subtype);
1048 shtree(bqlist->n, -1, NULL, fp);
1059 shcmd(union node *cmd, FILE *fp)
1067 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1073 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1077 switch (np->nfile.type) {
1078 case NTO: s = ">>"+1; dftfd = 1; break;
1079 case NCLOBBER: s = ">|"; dftfd = 1; break;
1080 case NAPPEND: s = ">>"; dftfd = 1; break;
1081 #if ENABLE_ASH_BASH_COMPAT
1084 case NTOFD: s = ">&"; dftfd = 1; break;
1085 case NFROM: s = "<"; break;
1086 case NFROMFD: s = "<&"; break;
1087 case NFROMTO: s = "<>"; break;
1088 default: s = "*error*"; break;
1090 if (np->nfile.fd != dftfd)
1091 fprintf(fp, "%d", np->nfile.fd);
1093 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1094 fprintf(fp, "%d", np->ndup.dupfd);
1096 sharg(np->nfile.fname, fp);
1103 shtree(union node *n, int ind, char *pfx, FILE *fp)
1105 struct nodelist *lp;
1111 indent(ind, pfx, fp);
1113 if (n == NODE_EOF) {
1128 shtree(n->nbinary.ch1, ind, NULL, fp);
1131 shtree(n->nbinary.ch2, ind, NULL, fp);
1139 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1140 shtree(lp->n, 0, NULL, fp);
1144 if (n->npipe.pipe_backgnd)
1150 fprintf(fp, "<node type %d>", n->type);
1158 showtree(union node *n)
1160 trace_puts("showtree called\n");
1161 shtree(n, 1, NULL, stderr);
1167 /* ============ Parser data */
1170 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1173 struct strlist *next;
1180 struct strpush *prev; /* preceding string on stack */
1182 int prev_left_in_line;
1183 #if ENABLE_ASH_ALIAS
1184 struct alias *ap; /* if push was associated with an alias */
1186 char *string; /* remember the string since it may change */
1188 /* Remember last two characters for pungetc. */
1191 /* Number of outstanding calls to pungetc. */
1196 struct parsefile *prev; /* preceding file on stack */
1197 int linno; /* current line */
1198 int pf_fd; /* file descriptor (or -1 if string) */
1199 int left_in_line; /* number of chars left in this line */
1200 int left_in_buffer; /* number of chars left in this buffer past the line */
1201 char *next_to_pgetc; /* next char in buffer */
1202 char *buf; /* input buffer */
1203 struct strpush *strpush; /* for pushing strings at this level */
1204 struct strpush basestrpush; /* so pushing one is fast */
1206 /* Remember last two characters for pungetc. */
1209 /* Number of outstanding calls to pungetc. */
1213 static struct parsefile basepf; /* top level input file */
1214 static struct parsefile *g_parsefile = &basepf; /* current input file */
1215 static int startlinno; /* line # where last token started */
1216 static char *commandname; /* currently executing command */
1217 static struct strlist *cmdenviron; /* environment for builtin command */
1220 /* ============ Message printing */
1223 ash_vmsg(const char *msg, va_list ap)
1225 fprintf(stderr, "%s: ", arg0);
1227 if (strcmp(arg0, commandname))
1228 fprintf(stderr, "%s: ", commandname);
1229 if (!iflag || g_parsefile->pf_fd > 0)
1230 fprintf(stderr, "line %d: ", startlinno);
1232 vfprintf(stderr, msg, ap);
1233 newline_and_flush(stderr);
1237 * Exverror is called to raise the error exception. If the second argument
1238 * is not NULL then error prints an error message using printf style
1239 * formatting. It then raises the error exception.
1241 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1243 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1247 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1249 TRACE(("\") pid=%d\n", getpid()));
1251 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1256 flush_stdout_stderr();
1257 raise_exception(cond);
1261 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1263 ash_msg_and_raise_error(const char *msg, ...)
1268 ash_vmsg_and_raise(EXERROR, msg, ap);
1273 static void raise_error_syntax(const char *) NORETURN;
1275 raise_error_syntax(const char *msg)
1277 ash_msg_and_raise_error("syntax error: %s", msg);
1281 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1283 ash_msg_and_raise(int cond, const char *msg, ...)
1288 ash_vmsg_and_raise(cond, msg, ap);
1294 * error/warning routines for external builtins
1297 ash_msg(const char *fmt, ...)
1307 * Return a string describing an error. The returned string may be a
1308 * pointer to a static buffer that will be overwritten on the next call.
1309 * Action describes the operation that got the error.
1312 errmsg(int e, const char *em)
1314 if (e == ENOENT || e == ENOTDIR) {
1321 /* ============ Memory allocation */
1324 /* I consider these wrappers nearly useless:
1325 * ok, they return you to nearest exception handler, but
1326 * how much memory do you leak in the process, making
1327 * memory starvation worse?
1330 ckrealloc(void * p, size_t nbytes)
1332 p = realloc(p, nbytes);
1334 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1339 ckmalloc(size_t nbytes)
1341 return ckrealloc(NULL, nbytes);
1345 ckzalloc(size_t nbytes)
1347 return memset(ckmalloc(nbytes), 0, nbytes);
1351 ckstrdup(const char *s)
1353 char *p = strdup(s);
1355 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1359 /* Using bbox equivalents. They exit if out of memory */
1360 # define ckrealloc xrealloc
1361 # define ckmalloc xmalloc
1362 # define ckzalloc xzalloc
1363 # define ckstrdup xstrdup
1367 * It appears that grabstackstr() will barf with such alignments
1368 * because stalloc() will return a string allocated in a new stackblock.
1370 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1372 /* Most machines require the value returned from malloc to be aligned
1373 * in some way. The following macro will get this right
1374 * on many machines. */
1375 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1376 /* Minimum size of a block */
1377 MINSIZE = SHELL_ALIGN(504),
1380 struct stack_block {
1381 struct stack_block *prev;
1382 char space[MINSIZE];
1386 struct stack_block *stackp;
1392 struct globals_memstack {
1393 struct stack_block *g_stackp; // = &stackbase;
1394 char *g_stacknxt; // = stackbase.space;
1395 char *sstrend; // = stackbase.space + MINSIZE;
1396 size_t g_stacknleft; // = MINSIZE;
1397 struct stack_block stackbase;
1399 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1400 #define G_memstack (*ash_ptr_to_globals_memstack)
1401 #define g_stackp (G_memstack.g_stackp )
1402 #define g_stacknxt (G_memstack.g_stacknxt )
1403 #define sstrend (G_memstack.sstrend )
1404 #define g_stacknleft (G_memstack.g_stacknleft)
1405 #define stackbase (G_memstack.stackbase )
1406 #define INIT_G_memstack() do { \
1407 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1409 g_stackp = &stackbase; \
1410 g_stacknxt = stackbase.space; \
1411 g_stacknleft = MINSIZE; \
1412 sstrend = stackbase.space + MINSIZE; \
1416 #define stackblock() ((void *)g_stacknxt)
1417 #define stackblocksize() g_stacknleft
1420 * Parse trees for commands are allocated in lifo order, so we use a stack
1421 * to make this more efficient, and also to avoid all sorts of exception
1422 * handling code to handle interrupts in the middle of a parse.
1424 * The size 504 was chosen because the Ultrix malloc handles that size
1428 stalloc(size_t nbytes)
1433 aligned = SHELL_ALIGN(nbytes);
1434 if (aligned > g_stacknleft) {
1437 struct stack_block *sp;
1439 blocksize = aligned;
1440 if (blocksize < MINSIZE)
1441 blocksize = MINSIZE;
1442 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1443 if (len < blocksize)
1444 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1447 sp->prev = g_stackp;
1448 g_stacknxt = sp->space;
1449 g_stacknleft = blocksize;
1450 sstrend = g_stacknxt + blocksize;
1455 g_stacknxt += aligned;
1456 g_stacknleft -= aligned;
1461 stzalloc(size_t nbytes)
1463 return memset(stalloc(nbytes), 0, nbytes);
1470 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1471 write(STDERR_FILENO, "stunalloc\n", 10);
1475 g_stacknleft += g_stacknxt - (char *)p;
1480 * Like strdup but works with the ash stack.
1483 sstrdup(const char *p)
1485 size_t len = strlen(p) + 1;
1486 return memcpy(stalloc(len), p, len);
1490 grabstackblock(size_t len)
1496 pushstackmark(struct stackmark *mark, size_t len)
1498 mark->stackp = g_stackp;
1499 mark->stacknxt = g_stacknxt;
1500 mark->stacknleft = g_stacknleft;
1501 grabstackblock(len);
1505 setstackmark(struct stackmark *mark)
1507 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1511 popstackmark(struct stackmark *mark)
1513 struct stack_block *sp;
1519 while (g_stackp != mark->stackp) {
1521 g_stackp = sp->prev;
1524 g_stacknxt = mark->stacknxt;
1525 g_stacknleft = mark->stacknleft;
1526 sstrend = mark->stacknxt + mark->stacknleft;
1531 * When the parser reads in a string, it wants to stick the string on the
1532 * stack and only adjust the stack pointer when it knows how big the
1533 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1534 * of space on top of the stack and stackblocklen returns the length of
1535 * this block. Growstackblock will grow this space by at least one byte,
1536 * possibly moving it (like realloc). Grabstackblock actually allocates the
1537 * part of the block that has been used.
1540 growstackblock(void)
1544 newlen = g_stacknleft * 2;
1545 if (newlen < g_stacknleft)
1546 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1550 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1551 struct stack_block *sp;
1552 struct stack_block *prevstackp;
1557 prevstackp = sp->prev;
1558 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1559 sp = ckrealloc(sp, grosslen);
1560 sp->prev = prevstackp;
1562 g_stacknxt = sp->space;
1563 g_stacknleft = newlen;
1564 sstrend = sp->space + newlen;
1567 char *oldspace = g_stacknxt;
1568 size_t oldlen = g_stacknleft;
1569 char *p = stalloc(newlen);
1571 /* free the space we just allocated */
1572 g_stacknxt = memcpy(p, oldspace, oldlen);
1573 g_stacknleft += newlen;
1578 * The following routines are somewhat easier to use than the above.
1579 * The user declares a variable of type STACKSTR, which may be declared
1580 * to be a register. The macro STARTSTACKSTR initializes things. Then
1581 * the user uses the macro STPUTC to add characters to the string. In
1582 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1583 * grown as necessary. When the user is done, she can just leave the
1584 * string there and refer to it using stackblock(). Or she can allocate
1585 * the space for it using grabstackstr(). If it is necessary to allow
1586 * someone else to use the stack temporarily and then continue to grow
1587 * the string, the user should use grabstack to allocate the space, and
1588 * then call ungrabstr(p) to return to the previous mode of operation.
1590 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1591 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1592 * is space for at least one character.
1597 size_t len = stackblocksize();
1599 return (char *)stackblock() + len;
1603 * Called from CHECKSTRSPACE.
1606 makestrspace(size_t newlen, char *p)
1608 size_t len = p - g_stacknxt;
1614 size = stackblocksize();
1616 if (nleft >= newlen)
1620 return (char *)stackblock() + len;
1624 stack_nputstr(const char *s, size_t n, char *p)
1626 p = makestrspace(n, p);
1627 p = (char *)memcpy(p, s, n) + n;
1632 stack_putstr(const char *s, char *p)
1634 return stack_nputstr(s, strlen(s), p);
1638 _STPUTC(int c, char *p)
1646 #define STARTSTACKSTR(p) ((p) = stackblock())
1647 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1648 #define CHECKSTRSPACE(n, p) do { \
1651 size_t m = sstrend - q; \
1653 (p) = makestrspace(l, q); \
1655 #define USTPUTC(c, p) (*(p)++ = (c))
1656 #define STACKSTRNUL(p) do { \
1657 if ((p) == sstrend) \
1658 (p) = growstackstr(); \
1661 #define STUNPUTC(p) (--(p))
1662 #define STTOPC(p) ((p)[-1])
1663 #define STADJUST(amount, p) ((p) += (amount))
1665 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1666 #define ungrabstackstr(s, p) stunalloc(s)
1667 #define stackstrend() ((void *)sstrend)
1670 /* ============ String helpers */
1673 * prefix -- see if pfx is a prefix of string.
1676 prefix(const char *string, const char *pfx)
1679 if (*pfx++ != *string++)
1682 return (char *) string;
1686 * Check for a valid number. This should be elsewhere.
1689 is_number(const char *p)
1694 } while (*++p != '\0');
1699 * Convert a string of digits to an integer, printing an error message on
1703 number(const char *s)
1706 ash_msg_and_raise_error(msg_illnum, s);
1711 * Produce a possibly single quoted string suitable as input to the shell.
1712 * The return string is allocated on the stack.
1715 single_quote(const char *s)
1725 len = strchrnul(s, '\'') - s;
1727 q = p = makestrspace(len + 3, p);
1730 q = (char *)memcpy(q, s, len) + len;
1739 do len++; while (*++s == '\'');
1741 q = p = makestrspace(len + 3, p);
1744 q = (char *)memcpy(q, s - len, len) + len;
1752 return stackblock();
1756 /* ============ nextopt */
1758 static char **argptr; /* argument list for builtin commands */
1759 static char *optionarg; /* set by nextopt (like getopt) */
1760 static char *optptr; /* used by nextopt */
1763 * XXX - should get rid of. Have all builtins use getopt(3).
1764 * The library getopt must have the BSD extension static variable
1765 * "optreset", otherwise it can't be used within the shell safely.
1767 * Standard option processing (a la getopt) for builtin routines.
1768 * The only argument that is passed to nextopt is the option string;
1769 * the other arguments are unnecessary. It returns the character,
1770 * or '\0' on end of input.
1773 nextopt(const char *optstring)
1780 if (p == NULL || *p == '\0') {
1781 /* We ate entire "-param", take next one */
1787 if (*++p == '\0') /* just "-" ? */
1790 if (LONE_DASH(p)) /* "--" ? */
1792 /* p => next "-param" */
1794 /* p => some option char in the middle of a "-param" */
1796 for (q = optstring; *q != c;) {
1798 ash_msg_and_raise_error("illegal option -%c", c);
1806 ash_msg_and_raise_error("no arg for -%c option", c);
1816 /* ============ Shell variables */
1819 * The parsefile structure pointed to by the global variable parsefile
1820 * contains information about the current file being read.
1823 int nparam; /* # of positional parameters (without $0) */
1824 #if ENABLE_ASH_GETOPTS
1825 int optind; /* next parameter to be processed by getopts */
1826 int optoff; /* used by getopts */
1828 unsigned char malloced; /* if parameter list dynamically allocated */
1829 char **p; /* parameter list */
1833 * Free the list of positional parameters.
1836 freeparam(volatile struct shparam *param)
1838 if (param->malloced) {
1840 ap = ap1 = param->p;
1847 #if ENABLE_ASH_GETOPTS
1848 static void FAST_FUNC getoptsreset(const char *value);
1852 struct var *next; /* next entry in hash list */
1853 int flags; /* flags are defined above */
1854 const char *var_text; /* name=value */
1855 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1856 /* the variable gets set/unset */
1860 struct localvar *next; /* next local variable in list */
1861 struct var *vp; /* the variable that was made local */
1862 int flags; /* saved flags */
1863 const char *text; /* saved text */
1867 #define VEXPORT 0x01 /* variable is exported */
1868 #define VREADONLY 0x02 /* variable cannot be modified */
1869 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1870 #define VTEXTFIXED 0x08 /* text is statically allocated */
1871 #define VSTACK 0x10 /* text is allocated on the stack */
1872 #define VUNSET 0x20 /* the variable is not set */
1873 #define VNOFUNC 0x40 /* don't call the callback function */
1874 #define VNOSET 0x80 /* do not set variable - just readonly test */
1875 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1876 #if ENABLE_ASH_RANDOM_SUPPORT
1877 # define VDYNAMIC 0x200 /* dynamic variable */
1883 /* Need to be before varinit_data[] */
1884 #if ENABLE_LOCALE_SUPPORT
1885 static void FAST_FUNC
1886 change_lc_all(const char *value)
1888 if (value && *value != '\0')
1889 setlocale(LC_ALL, value);
1891 static void FAST_FUNC
1892 change_lc_ctype(const char *value)
1894 if (value && *value != '\0')
1895 setlocale(LC_CTYPE, value);
1899 static void chkmail(void);
1900 static void changemail(const char *var_value) FAST_FUNC;
1902 # define chkmail() ((void)0)
1904 static void changepath(const char *) FAST_FUNC;
1905 #if ENABLE_ASH_RANDOM_SUPPORT
1906 static void change_random(const char *) FAST_FUNC;
1909 static const struct {
1911 const char *var_text;
1912 void (*var_func)(const char *) FAST_FUNC;
1913 } varinit_data[] = {
1915 * Note: VEXPORT would not work correctly here for NOFORK applets:
1916 * some environment strings may be constant.
1918 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1920 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1921 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1923 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1924 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1925 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1926 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1927 #if ENABLE_ASH_GETOPTS
1928 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1930 #if ENABLE_ASH_RANDOM_SUPPORT
1931 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1933 #if ENABLE_LOCALE_SUPPORT
1934 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1935 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1937 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1938 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1944 struct globals_var {
1945 struct shparam shellparam; /* $@ current positional parameters */
1946 struct redirtab *redirlist;
1947 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1948 struct var *vartab[VTABSIZE];
1949 struct var varinit[ARRAY_SIZE(varinit_data)];
1951 extern struct globals_var *const ash_ptr_to_globals_var;
1952 #define G_var (*ash_ptr_to_globals_var)
1953 #define shellparam (G_var.shellparam )
1954 //#define redirlist (G_var.redirlist )
1955 #define preverrout_fd (G_var.preverrout_fd)
1956 #define vartab (G_var.vartab )
1957 #define varinit (G_var.varinit )
1958 #define INIT_G_var() do { \
1960 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1962 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1963 varinit[i].flags = varinit_data[i].flags; \
1964 varinit[i].var_text = varinit_data[i].var_text; \
1965 varinit[i].var_func = varinit_data[i].var_func; \
1969 #define vifs varinit[0]
1971 # define vmail (&vifs)[1]
1972 # define vmpath (&vmail)[1]
1973 # define vpath (&vmpath)[1]
1975 # define vpath (&vifs)[1]
1977 #define vps1 (&vpath)[1]
1978 #define vps2 (&vps1)[1]
1979 #define vps4 (&vps2)[1]
1980 #if ENABLE_ASH_GETOPTS
1981 # define voptind (&vps4)[1]
1982 # if ENABLE_ASH_RANDOM_SUPPORT
1983 # define vrandom (&voptind)[1]
1986 # if ENABLE_ASH_RANDOM_SUPPORT
1987 # define vrandom (&vps4)[1]
1992 * The following macros access the values of the above variables.
1993 * They have to skip over the name. They return the null string
1994 * for unset variables.
1996 #define ifsval() (vifs.var_text + 4)
1997 #define ifsset() ((vifs.flags & VUNSET) == 0)
1999 # define mailval() (vmail.var_text + 5)
2000 # define mpathval() (vmpath.var_text + 9)
2001 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2003 #define pathval() (vpath.var_text + 5)
2004 #define ps1val() (vps1.var_text + 4)
2005 #define ps2val() (vps2.var_text + 4)
2006 #define ps4val() (vps4.var_text + 4)
2007 #if ENABLE_ASH_GETOPTS
2008 # define optindval() (voptind.var_text + 7)
2011 #if ENABLE_ASH_GETOPTS
2012 static void FAST_FUNC
2013 getoptsreset(const char *value)
2015 shellparam.optind = number(value) ?: 1;
2016 shellparam.optoff = -1;
2021 * Compares two strings up to the first = or '\0'. The first
2022 * string must be terminated by '='; the second may be terminated by
2023 * either '=' or '\0'.
2026 varcmp(const char *p, const char *q)
2030 while ((c = *p) == (d = *q)) {
2031 if (c == '\0' || c == '=')
2045 * Find the appropriate entry in the hash table from the name.
2047 static struct var **
2048 hashvar(const char *p)
2052 hashval = ((unsigned char) *p) << 4;
2053 while (*p && *p != '=')
2054 hashval += (unsigned char) *p++;
2055 return &vartab[hashval % VTABSIZE];
2059 vpcmp(const void *a, const void *b)
2061 return varcmp(*(const char **)a, *(const char **)b);
2065 * This routine initializes the builtin variables.
2075 * PS1 depends on uid
2077 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2078 vps1.var_text = "PS1=\\w \\$ ";
2081 vps1.var_text = "PS1=# ";
2084 end = vp + ARRAY_SIZE(varinit);
2086 vpp = hashvar(vp->var_text);
2089 } while (++vp < end);
2092 static struct var **
2093 findvar(struct var **vpp, const char *name)
2095 for (; *vpp; vpp = &(*vpp)->next) {
2096 if (varcmp((*vpp)->var_text, name) == 0) {
2104 * Find the value of a variable. Returns NULL if not set.
2106 static const char* FAST_FUNC
2107 lookupvar(const char *name)
2111 v = *findvar(hashvar(name), name);
2113 #if ENABLE_ASH_RANDOM_SUPPORT
2115 * Dynamic variables are implemented roughly the same way they are
2116 * in bash. Namely, they're "special" so long as they aren't unset.
2117 * As soon as they're unset, they're no longer dynamic, and dynamic
2118 * lookup will no longer happen at that point. -- PFM.
2120 if (v->flags & VDYNAMIC)
2123 if (!(v->flags & VUNSET))
2124 return var_end(v->var_text);
2130 reinit_unicode_for_ash(void)
2132 /* Unicode support should be activated even if LANG is set
2133 * _during_ shell execution, not only if it was set when
2134 * shell was started. Therefore, re-check LANG every time:
2136 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2137 || ENABLE_UNICODE_USING_LOCALE
2139 const char *s = lookupvar("LC_ALL");
2140 if (!s) s = lookupvar("LC_CTYPE");
2141 if (!s) s = lookupvar("LANG");
2147 * Search the environment of a builtin command.
2150 bltinlookup(const char *name)
2154 for (sp = cmdenviron; sp; sp = sp->next) {
2155 if (varcmp(sp->text, name) == 0)
2156 return var_end(sp->text);
2158 return lookupvar(name);
2162 * Same as setvar except that the variable and value are passed in
2163 * the first argument as name=value. Since the first argument will
2164 * be actually stored in the table, it should not be a string that
2166 * Called with interrupts off.
2169 setvareq(char *s, int flags)
2171 struct var *vp, **vpp;
2174 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2175 vp = *findvar(vpp, s);
2177 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2180 if (flags & VNOSAVE)
2184 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2190 if (vp->var_func && !(flags & VNOFUNC))
2191 vp->var_func(var_end(s));
2193 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2194 free((char*)vp->var_text);
2196 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2198 /* variable s is not found */
2201 vp = ckzalloc(sizeof(*vp));
2203 /*vp->func = NULL; - ckzalloc did it */
2206 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2213 * Set the value of a variable. The flags argument is ored with the
2214 * flags of the variable. If val is NULL, the variable is unset.
2217 setvar(const char *name, const char *val, int flags)
2225 q = endofname(name);
2226 p = strchrnul(q, '=');
2228 if (!namelen || p != q)
2229 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2234 vallen = strlen(val);
2238 nameeq = ckmalloc(namelen + vallen + 2);
2239 p = memcpy(nameeq, name, namelen) + namelen;
2242 p = memcpy(p, val, vallen) + vallen;
2245 setvareq(nameeq, flags | VNOSAVE);
2249 static void FAST_FUNC
2250 setvar0(const char *name, const char *val)
2252 setvar(name, val, 0);
2256 * Unset the specified variable.
2259 unsetvar(const char *s)
2265 vpp = findvar(hashvar(s), s);
2269 int flags = vp->flags;
2272 if (flags & VREADONLY)
2274 #if ENABLE_ASH_RANDOM_SUPPORT
2275 vp->flags &= ~VDYNAMIC;
2279 if ((flags & VSTRFIXED) == 0) {
2281 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2282 free((char*)vp->var_text);
2288 vp->flags &= ~VEXPORT;
2298 * Process a linked list of variable assignments.
2301 listsetvar(struct strlist *list_set_var, int flags)
2303 struct strlist *lp = list_set_var;
2309 setvareq(lp->text, flags);
2316 * Generate a list of variables satisfying the given conditions.
2319 listvars(int on, int off, char ***end)
2330 for (vp = *vpp; vp; vp = vp->next) {
2331 if ((vp->flags & mask) == on) {
2332 if (ep == stackstrend())
2333 ep = growstackstr();
2334 *ep++ = (char*)vp->var_text;
2337 } while (++vpp < vartab + VTABSIZE);
2338 if (ep == stackstrend())
2339 ep = growstackstr();
2343 return grabstackstr(ep);
2347 /* ============ Path search helper
2349 * The variable path (passed by reference) should be set to the start
2350 * of the path before the first call; path_advance will update
2351 * this value as it proceeds. Successive calls to path_advance will return
2352 * the possible path expansions in sequence. If an option (indicated by
2353 * a percent sign) appears in the path entry then the global variable
2354 * pathopt will be set to point to it; otherwise pathopt will be set to
2357 static const char *pathopt; /* set by path_advance */
2360 path_advance(const char **path, const char *name)
2370 for (p = start; *p && *p != ':' && *p != '%'; p++)
2372 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2373 while (stackblocksize() < len)
2377 memcpy(q, start, p - start);
2385 while (*p && *p != ':')
2392 return stalloc(len);
2396 /* ============ Prompt */
2398 static smallint doprompt; /* if set, prompt the user */
2399 static smallint needprompt; /* true if interactive and at start of line */
2401 #if ENABLE_FEATURE_EDITING
2402 static line_input_t *line_input_state;
2403 static const char *cmdedit_prompt;
2405 putprompt(const char *s)
2407 if (ENABLE_ASH_EXPAND_PRMT) {
2408 free((char*)cmdedit_prompt);
2409 cmdedit_prompt = ckstrdup(s);
2416 putprompt(const char *s)
2422 #if ENABLE_ASH_EXPAND_PRMT
2423 /* expandstr() needs parsing machinery, so it is far away ahead... */
2424 static const char *expandstr(const char *ps);
2426 #define expandstr(s) s
2430 setprompt_if(smallint do_set, int whichprompt)
2433 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2440 switch (whichprompt) {
2450 #if ENABLE_ASH_EXPAND_PRMT
2451 pushstackmark(&smark, stackblocksize());
2453 putprompt(expandstr(prompt));
2454 #if ENABLE_ASH_EXPAND_PRMT
2455 popstackmark(&smark);
2460 /* ============ The cd and pwd commands */
2462 #define CD_PHYSICAL 1
2472 while ((i = nextopt("LP")) != '\0') {
2474 flags ^= CD_PHYSICAL;
2483 * Update curdir (the name of the current directory) in response to a
2487 updatepwd(const char *dir)
2494 cdcomppath = sstrdup(dir);
2497 if (curdir == nullstr)
2499 new = stack_putstr(curdir, new);
2501 new = makestrspace(strlen(dir) + 2, new);
2502 lim = (char *)stackblock() + 1;
2506 if (new > lim && *lim == '/')
2511 if (dir[1] == '/' && dir[2] != '/') {
2517 p = strtok(cdcomppath, "/");
2521 if (p[1] == '.' && p[2] == '\0') {
2533 new = stack_putstr(p, new);
2536 p = strtok(NULL, "/");
2541 return stackblock();
2545 * Find out what the current directory is. If we already know the current
2546 * directory, this routine returns immediately.
2551 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2552 return dir ? dir : nullstr;
2556 setpwd(const char *val, int setold)
2560 oldcur = dir = curdir;
2563 setvar("OLDPWD", oldcur, VEXPORT);
2566 if (physdir != nullstr) {
2567 if (physdir != oldcur)
2571 if (oldcur == val || !val) {
2577 dir = ckstrdup(val);
2578 if (oldcur != dir && oldcur != nullstr) {
2583 setvar("PWD", dir, VEXPORT);
2586 static void hashcd(void);
2589 * Actually do the chdir. We also call hashcd to let other routines
2590 * know that the current directory has changed.
2593 docd(const char *dest, int flags)
2595 const char *dir = NULL;
2598 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2601 if (!(flags & CD_PHYSICAL)) {
2602 dir = updatepwd(dest);
2616 static int FAST_FUNC
2617 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2629 dest = bltinlookup("HOME");
2630 else if (LONE_DASH(dest)) {
2631 dest = bltinlookup("OLDPWD");
2653 path = bltinlookup("CDPATH");
2656 p = path_advance(&path, dest);
2657 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2661 if (!docd(p, flags))
2672 ash_msg_and_raise_error("can't cd to %s", dest);
2675 if (flags & CD_PRINT)
2676 out1fmt("%s\n", curdir);
2680 static int FAST_FUNC
2681 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2684 const char *dir = curdir;
2688 if (physdir == nullstr)
2692 out1fmt("%s\n", dir);
2697 /* ============ ... */
2700 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2702 /* Syntax classes */
2703 #define CWORD 0 /* character is nothing special */
2704 #define CNL 1 /* newline character */
2705 #define CBACK 2 /* a backslash character */
2706 #define CSQUOTE 3 /* single quote */
2707 #define CDQUOTE 4 /* double quote */
2708 #define CENDQUOTE 5 /* a terminating quote */
2709 #define CBQUOTE 6 /* backwards single quote */
2710 #define CVAR 7 /* a dollar sign */
2711 #define CENDVAR 8 /* a '}' character */
2712 #define CLP 9 /* a left paren in arithmetic */
2713 #define CRP 10 /* a right paren in arithmetic */
2714 #define CENDFILE 11 /* end of file */
2715 #define CCTL 12 /* like CWORD, except it must be escaped */
2716 #define CSPCL 13 /* these terminate a word */
2717 #define CIGN 14 /* character should be ignored */
2720 #if ENABLE_ASH_ALIAS
2724 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2726 #if ENABLE_SH_MATH_SUPPORT
2727 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2729 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2731 static const uint16_t S_I_T[] ALIGN2 = {
2732 #if ENABLE_ASH_ALIAS
2733 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2735 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2736 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2737 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2738 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2739 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2740 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2741 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2742 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2743 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2744 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2745 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2746 #if !USE_SIT_FUNCTION
2747 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2748 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2749 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2753 /* Constants below must match table above */
2755 #if ENABLE_ASH_ALIAS
2756 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2758 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2759 CNL_CNL_CNL_CNL , /* 2 */
2760 CWORD_CCTL_CCTL_CWORD , /* 3 */
2761 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2762 CVAR_CVAR_CWORD_CVAR , /* 5 */
2763 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2764 CSPCL_CWORD_CWORD_CLP , /* 7 */
2765 CSPCL_CWORD_CWORD_CRP , /* 8 */
2766 CBACK_CBACK_CCTL_CBACK , /* 9 */
2767 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2768 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2769 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2770 CWORD_CWORD_CWORD_CWORD , /* 13 */
2771 CCTL_CCTL_CCTL_CCTL , /* 14 */
2774 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2775 * caller must ensure proper cast on it if c is *char_ptr!
2777 /* Values for syntax param */
2778 #define BASESYNTAX 0 /* not in quotes */
2779 #define DQSYNTAX 1 /* in double quotes */
2780 #define SQSYNTAX 2 /* in single quotes */
2781 #define ARISYNTAX 3 /* in arithmetic */
2782 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2784 #if USE_SIT_FUNCTION
2787 SIT(int c, int syntax)
2789 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2790 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2792 * This causes '/' to be prepended with CTLESC in dquoted string,
2793 * making "./file"* treated incorrectly because we feed
2794 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2795 * The "homegrown" glob implementation is okay with that,
2796 * but glibc one isn't. With '/' always treated as CWORD,
2799 # if ENABLE_ASH_ALIAS
2800 static const uint8_t syntax_index_table[] ALIGN1 = {
2801 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2802 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2803 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2807 static const uint8_t syntax_index_table[] ALIGN1 = {
2808 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2809 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2810 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2819 # if ENABLE_ASH_ALIAS
2825 /* Cast is purely for paranoia here,
2826 * just in case someone passed signed char to us */
2827 if ((unsigned char)c >= CTL_FIRST
2828 && (unsigned char)c <= CTL_LAST
2832 s = strchrnul(spec_symbls, c);
2835 indx = syntax_index_table[s - spec_symbls];
2837 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2840 #else /* !USE_SIT_FUNCTION */
2842 static const uint8_t syntax_index_table[] ALIGN1 = {
2843 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2844 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2855 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2878 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2879 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2880 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2881 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2883 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2884 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2885 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2886 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2887 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2889 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2890 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2891 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2892 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2907 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2908 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2909 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2937 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2938 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2942 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2970 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2971 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2972 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2973 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2975 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2976 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2977 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2978 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2979 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2980 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2981 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2982 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3101 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3102 # if ENABLE_ASH_ALIAS
3103 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3107 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3109 #endif /* !USE_SIT_FUNCTION */
3112 /* ============ Alias handling */
3114 #if ENABLE_ASH_ALIAS
3116 #define ALIASINUSE 1
3127 static struct alias **atab; // [ATABSIZE];
3128 #define INIT_G_alias() do { \
3129 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3133 static struct alias **
3134 __lookupalias(const char *name)
3136 unsigned int hashval;
3143 ch = (unsigned char)*p;
3147 ch = (unsigned char)*++p;
3149 app = &atab[hashval % ATABSIZE];
3151 for (; *app; app = &(*app)->next) {
3152 if (strcmp(name, (*app)->name) == 0) {
3160 static struct alias *
3161 lookupalias(const char *name, int check)
3163 struct alias *ap = *__lookupalias(name);
3165 if (check && ap && (ap->flag & ALIASINUSE))
3170 static struct alias *
3171 freealias(struct alias *ap)
3175 if (ap->flag & ALIASINUSE) {
3176 ap->flag |= ALIASDEAD;
3188 setalias(const char *name, const char *val)
3190 struct alias *ap, **app;
3192 app = __lookupalias(name);
3196 if (!(ap->flag & ALIASINUSE)) {
3199 ap->val = ckstrdup(val);
3200 ap->flag &= ~ALIASDEAD;
3203 ap = ckzalloc(sizeof(struct alias));
3204 ap->name = ckstrdup(name);
3205 ap->val = ckstrdup(val);
3206 /*ap->flag = 0; - ckzalloc did it */
3207 /*ap->next = NULL;*/
3214 unalias(const char *name)
3218 app = __lookupalias(name);
3222 *app = freealias(*app);
3233 struct alias *ap, **app;
3237 for (i = 0; i < ATABSIZE; i++) {
3239 for (ap = *app; ap; ap = *app) {
3240 *app = freealias(*app);
3250 printalias(const struct alias *ap)
3252 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3256 * TODO - sort output
3258 static int FAST_FUNC
3259 aliascmd(int argc UNUSED_PARAM, char **argv)
3268 for (i = 0; i < ATABSIZE; i++) {
3269 for (ap = atab[i]; ap; ap = ap->next) {
3275 while ((n = *++argv) != NULL) {
3276 v = strchr(n+1, '=');
3277 if (v == NULL) { /* n+1: funny ksh stuff */
3278 ap = *__lookupalias(n);
3280 fprintf(stderr, "%s: %s not found\n", "alias", n);
3293 static int FAST_FUNC
3294 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3298 while ((i = nextopt("a")) != '\0') {
3304 for (i = 0; *argptr; argptr++) {
3305 if (unalias(*argptr)) {
3306 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3314 #endif /* ASH_ALIAS */
3317 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3320 #define FORK_NOJOB 2
3322 /* mode flags for showjob(s) */
3323 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3324 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3325 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3326 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3329 * A job structure contains information about a job. A job is either a
3330 * single process or a set of processes contained in a pipeline. In the
3331 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3335 pid_t ps_pid; /* process id */
3336 int ps_status; /* last process status from wait() */
3337 char *ps_cmd; /* text of command being run */
3341 struct procstat ps0; /* status of process */
3342 struct procstat *ps; /* status or processes when more than one */
3344 int stopstatus; /* status of a stopped job */
3347 nprocs: 16, /* number of processes */
3349 #define JOBRUNNING 0 /* at least one proc running */
3350 #define JOBSTOPPED 1 /* all procs are stopped */
3351 #define JOBDONE 2 /* all procs are completed */
3353 sigint: 1, /* job was killed by SIGINT */
3354 jobctl: 1, /* job running under job control */
3356 waited: 1, /* true if this entry has been waited for */
3357 used: 1, /* true if this entry is in used */
3358 changed: 1; /* true if status has changed */
3359 struct job *prev_job; /* previous job */
3362 static struct job *makejob(/*union node *,*/ int);
3363 static int forkshell(struct job *, union node *, int);
3364 static int waitforjob(struct job *);
3367 enum { doing_jobctl = 0 };
3368 #define setjobctl(on) do {} while (0)
3370 static smallint doing_jobctl; //references:8
3371 static void setjobctl(int);
3378 ignoresig(int signo)
3380 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3381 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3382 /* No, need to do it */
3383 signal(signo, SIG_IGN);
3385 sigmode[signo - 1] = S_HARD_IGN;
3389 * Only one usage site - in setsignal()
3392 signal_handler(int signo)
3394 if (signo == SIGCHLD) {
3400 gotsig[signo - 1] = 1;
3401 pending_sig = signo;
3403 if (signo == SIGINT && !trap[SIGINT]) {
3404 if (!suppress_int) {
3406 raise_interrupt(); /* does not return */
3413 * Set the signal handler for the specified signal. The routine figures
3414 * out what it should be set to.
3417 setsignal(int signo)
3420 char cur_act, new_act;
3421 struct sigaction act;
3425 if (t != NULL) { /* trap for this sig is set */
3427 if (t[0] == '\0') /* trap is "": ignore this sig */
3431 if (rootshell && new_act == S_DFL) {
3434 if (iflag || minusc || sflag == 0)
3443 * "In all cases, bash ignores SIGQUIT. Non-builtin
3444 * commands run by bash have signal handlers
3445 * set to the values inherited by the shell
3446 * from its parent". */
3462 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3463 //whereas we have to restore it to what shell got on entry
3464 //from the parent. See comment above
3466 if (signo == SIGCHLD)
3469 t = &sigmode[signo - 1];
3472 /* current setting is not yet known */
3473 if (sigaction(signo, NULL, &act)) {
3474 /* pretend it worked; maybe we should give a warning,
3475 * but other shells don't. We don't alter sigmode,
3476 * so we retry every time.
3477 * btw, in Linux it never fails. --vda */
3480 if (act.sa_handler == SIG_IGN) {
3481 cur_act = S_HARD_IGN;
3483 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3485 cur_act = S_IGN; /* don't hard ignore these */
3489 if (cur_act == S_HARD_IGN || cur_act == new_act)
3492 act.sa_handler = SIG_DFL;
3495 act.sa_handler = signal_handler;
3498 act.sa_handler = SIG_IGN;
3502 /* flags and mask matter only if !DFL and !IGN, but we do it
3503 * for all cases for more deterministic behavior:
3506 sigfillset(&act.sa_mask);
3508 sigaction_set(signo, &act);
3513 /* mode flags for set_curjob */
3514 #define CUR_DELETE 2
3515 #define CUR_RUNNING 1
3516 #define CUR_STOPPED 0
3518 /* mode flags for dowait */
3519 #define DOWAIT_NONBLOCK 0
3520 #define DOWAIT_BLOCK 1
3521 #define DOWAIT_BLOCK_OR_SIG 2
3524 /* pgrp of shell on invocation */
3525 static int initialpgrp; //references:2
3526 static int ttyfd = -1; //5
3529 static struct job *jobtab; //5
3531 static unsigned njobs; //4
3533 static struct job *curjob; //lots
3534 /* number of presumed living untracked jobs */
3535 static int jobless; //4
3538 set_curjob(struct job *jp, unsigned mode)
3541 struct job **jpp, **curp;
3543 /* first remove from list */
3544 jpp = curp = &curjob;
3549 jpp = &jp1->prev_job;
3551 *jpp = jp1->prev_job;
3553 /* Then re-insert in correct position */
3561 /* job being deleted */
3564 /* newly created job or backgrounded job,
3565 * put after all stopped jobs.
3570 if (!jp1 || jp1->state != JOBSTOPPED)
3573 jpp = &jp1->prev_job;
3579 /* newly stopped job - becomes curjob */
3580 jp->prev_job = *jpp;
3588 jobno(const struct job *jp)
3590 return jp - jobtab + 1;
3595 * Convert a job name to a job structure.
3598 #define getjob(name, getctl) getjob(name)
3601 getjob(const char *name, int getctl)
3605 const char *err_msg = "%s: no such job";
3609 char *(*match)(const char *, const char *);
3624 if (c == '+' || c == '%') {
3626 err_msg = "No current job";
3632 err_msg = "No previous job";
3642 if (num > 0 && num <= njobs) {
3643 jp = jobtab + num - 1;
3658 if (match(jp->ps[0].ps_cmd, p)) {
3662 err_msg = "%s: ambiguous";
3672 err_msg = "job %s not created under job control";
3673 if (getctl && jp->jobctl == 0)
3678 ash_msg_and_raise_error(err_msg, name);
3682 * Mark a job structure as unused.
3685 freejob(struct job *jp)
3687 struct procstat *ps;
3691 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3692 if (ps->ps_cmd != nullstr)
3695 if (jp->ps != &jp->ps0)
3698 set_curjob(jp, CUR_DELETE);
3704 xtcsetpgrp(int fd, pid_t pgrp)
3706 if (tcsetpgrp(fd, pgrp))
3707 ash_msg_and_raise_error("can't set tty process group (%m)");
3711 * Turn job control on and off.
3713 * Note: This code assumes that the third arg to ioctl is a character
3714 * pointer, which is true on Berkeley systems but not System V. Since
3715 * System V doesn't have job control yet, this isn't a problem now.
3717 * Called with interrupts off.
3725 if (on == doing_jobctl || rootshell == 0)
3729 ofd = fd = open(_PATH_TTY, O_RDWR);
3731 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3732 * That sometimes helps to acquire controlling tty.
3733 * Obviously, a workaround for bugs when someone
3734 * failed to provide a controlling tty to bash! :) */
3740 /* fd is a tty at this point */
3741 fd = fcntl(fd, F_DUPFD, 10);
3742 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3745 goto out; /* F_DUPFD failed */
3746 close_on_exec_on(fd);
3747 while (1) { /* while we are in the background */
3748 pgrp = tcgetpgrp(fd);
3751 ash_msg("can't access tty; job control turned off");
3755 if (pgrp == getpgrp())
3766 xtcsetpgrp(fd, pgrp);
3768 /* turning job control off */
3771 /* was xtcsetpgrp, but this can make exiting ash
3772 * loop forever if pty is already deleted */
3773 tcsetpgrp(fd, pgrp);
3787 static int FAST_FUNC
3788 killcmd(int argc, char **argv)
3790 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3793 if (argv[i][0] == '%') {
3795 * "kill %N" - job kill
3796 * Converting to pgrp / pid kill
3802 jp = getjob(argv[i], 0);
3804 * In jobs started under job control, we signal
3805 * entire process group by kill -PGRP_ID.
3806 * This happens, f.e., in interactive shell.
3808 * Otherwise, we signal each child via
3809 * kill PID1 PID2 PID3.
3811 * sh -c 'sleep 1|sleep 1 & kill %1'
3812 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3813 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3815 n = jp->nprocs; /* can't be 0 (I hope) */
3818 dst = alloca(n * sizeof(int)*4);
3820 for (j = 0; j < n; j++) {
3821 struct procstat *ps = &jp->ps[j];
3822 /* Skip non-running and not-stopped members
3823 * (i.e. dead members) of the job
3825 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3828 * kill_main has matching code to expect
3829 * leading space. Needed to not confuse
3830 * negative pids with "kill -SIGNAL_NO" syntax
3832 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3836 } while (argv[++i]);
3838 return kill_main(argc, argv);
3842 showpipe(struct job *jp /*, FILE *out*/)
3844 struct procstat *ps;
3845 struct procstat *psend;
3847 psend = jp->ps + jp->nprocs;
3848 for (ps = jp->ps + 1; ps < psend; ps++)
3849 printf(" | %s", ps->ps_cmd);
3850 newline_and_flush(stdout);
3851 flush_stdout_stderr();
3856 restartjob(struct job *jp, int mode)
3858 struct procstat *ps;
3864 if (jp->state == JOBDONE)
3866 jp->state = JOBRUNNING;
3867 pgid = jp->ps[0].ps_pid;
3868 if (mode == FORK_FG)
3869 xtcsetpgrp(ttyfd, pgid);
3870 killpg(pgid, SIGCONT);
3874 if (WIFSTOPPED(ps->ps_status)) {
3880 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3885 static int FAST_FUNC
3886 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3892 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3896 jp = getjob(*argv, 1);
3897 if (mode == FORK_BG) {
3898 set_curjob(jp, CUR_RUNNING);
3899 printf("[%d] ", jobno(jp));
3901 out1str(jp->ps[0].ps_cmd);
3902 showpipe(jp /*, stdout*/);
3903 retval = restartjob(jp, mode);
3904 } while (*argv && *++argv);
3910 sprint_status48(char *s, int status, int sigonly)
3916 if (!WIFEXITED(status)) {
3917 if (JOBS && WIFSTOPPED(status))
3918 st = WSTOPSIG(status);
3920 st = WTERMSIG(status);
3922 if (st == SIGINT || st == SIGPIPE)
3924 if (JOBS && WIFSTOPPED(status))
3928 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3929 col = fmtstr(s, 32, strsignal(st));
3930 if (WCOREDUMP(status)) {
3931 strcpy(s + col, " (core dumped)");
3932 col += sizeof(" (core dumped)")-1;
3934 } else if (!sigonly) {
3935 st = WEXITSTATUS(status);
3936 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3943 wait_block_or_sig(int *status, int wait_flags)
3949 /* Poll all children for changes in their state */
3951 pid = waitpid(-1, status, wait_flags | WNOHANG);
3953 break; /* Error (e.g. EINTR) or pid */
3955 /* No child is ready. Sleep until interesting signal is received */
3957 sigprocmask(SIG_SETMASK, &mask, &mask);
3958 while (!got_sigchld && !pending_sig)
3960 sigprocmask(SIG_SETMASK, &mask, NULL);
3962 /* If it was SIGCHLD, poll children again */
3963 } while (got_sigchld);
3970 dowait(int block, struct job *job)
3976 struct job *thisjob = NULL;
3978 TRACE(("dowait(0x%x) called\n", block));
3981 if (block == DOWAIT_NONBLOCK)
3982 wait_flags = WNOHANG;
3983 /* If job control is compiled in, we accept stopped processes too. */
3985 wait_flags |= WUNTRACED;
3987 /* It's wrong to call waitpid() outside of INT_OFF region:
3988 * signal can arrive just after syscall return and handler can
3989 * longjmp away, losing stop/exit notification processing.
3990 * Thus, for "jobs" builtin, and for waiting for a fg job,
3991 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
3993 * However, for "wait" builtin it is wrong to simply call waitpid()
3994 * in INT_OFF region: "wait" needs to wait for any running job
3995 * to change state, but should exit on any trap too.
3996 * In INT_OFF region, a signal just before syscall entry can set
3997 * pending_sig valiables, but we can't check them, and we would
3998 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
3999 * Because of this, we run inside INT_OFF, but use a special routine
4000 * which combines waitpid() and sigsuspend().
4003 if (block == DOWAIT_BLOCK_OR_SIG)
4004 pid = wait_block_or_sig(&status, wait_flags);
4006 /* NB: _not_ safe_waitpid, we need to detect EINTR. */
4007 pid = waitpid(-1, &status, wait_flags);
4008 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4009 pid, status, errno, strerror(errno)));
4014 for (jp = curjob; jp; jp = jp->prev_job) {
4016 struct procstat *ps;
4017 struct procstat *psend;
4018 if (jp->state == JOBDONE)
4022 psend = ps + jp->nprocs;
4024 if (ps->ps_pid == pid) {
4025 TRACE(("Job %d: changing status of proc %d "
4026 "from 0x%x to 0x%x\n",
4027 jobno(jp), pid, ps->ps_status, status));
4028 ps->ps_status = status;
4031 if (ps->ps_status == -1)
4032 jobstate = JOBRUNNING;
4034 if (jobstate == JOBRUNNING)
4036 if (WIFSTOPPED(ps->ps_status)) {
4037 jp->stopstatus = ps->ps_status;
4038 jobstate = JOBSTOPPED;
4041 } while (++ps < psend);
4045 /* Found the job where one of its processes changed its state.
4046 * Is there at least one live and running process in this job? */
4047 if (jobstate != JOBRUNNING) {
4048 /* No. All live processes in the job are stopped
4049 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4051 thisjob->changed = 1;
4052 if (thisjob->state != jobstate) {
4053 TRACE(("Job %d: changing state from %d to %d\n",
4054 jobno(thisjob), thisjob->state, jobstate));
4055 thisjob->state = jobstate;
4057 if (jobstate == JOBSTOPPED)
4058 set_curjob(thisjob, CUR_STOPPED);
4064 /* The process wasn't found in job list */
4065 if (JOBS && !WIFSTOPPED(status))
4070 if (thisjob && thisjob == job) {
4074 len = sprint_status48(s, status, 1);
4086 showjob(struct job *jp, int mode)
4088 struct procstat *ps;
4089 struct procstat *psend;
4092 char s[16 + 16 + 48];
4093 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4097 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4098 /* just output process (group) id of pipeline */
4099 fprintf(out, "%d\n", ps->ps_pid);
4103 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4108 else if (curjob && jp == curjob->prev_job)
4111 if (mode & SHOW_PIDS)
4112 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4114 psend = ps + jp->nprocs;
4116 if (jp->state == JOBRUNNING) {
4117 strcpy(s + col, "Running");
4118 col += sizeof("Running") - 1;
4120 int status = psend[-1].ps_status;
4121 if (jp->state == JOBSTOPPED)
4122 status = jp->stopstatus;
4123 col += sprint_status48(s + col, status, 0);
4125 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4127 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4128 * or prints several "PID | <cmdN>" lines,
4129 * depending on SHOW_PIDS bit.
4130 * We do not print status of individual processes
4131 * between PID and <cmdN>. bash does it, but not very well:
4132 * first line shows overall job status, not process status,
4133 * making it impossible to know 1st process status.
4137 /* for each process */
4140 if (mode & SHOW_PIDS)
4141 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4143 fprintf(out, "%s%*c%s%s",
4145 33 - col >= 0 ? 33 - col : 0, ' ',
4146 ps == jp->ps ? "" : "| ",
4149 } while (++ps != psend);
4150 newline_and_flush(out);
4154 if (jp->state == JOBDONE) {
4155 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4161 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4162 * statuses have changed since the last call to showjobs.
4169 TRACE(("showjobs(0x%x) called\n", mode));
4171 /* Handle all finished jobs */
4172 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4175 for (jp = curjob; jp; jp = jp->prev_job) {
4176 if (!(mode & SHOW_CHANGED) || jp->changed) {
4182 static int FAST_FUNC
4183 jobscmd(int argc UNUSED_PARAM, char **argv)
4188 while ((m = nextopt("lp")) != '\0') {
4192 mode |= SHOW_ONLY_PGID;
4198 showjob(getjob(*argv, 0), mode);
4208 /* Called only on finished or stopped jobs (no members are running) */
4210 getstatus(struct job *job)
4214 struct procstat *ps;
4216 /* Fetch last member's status */
4217 ps = job->ps + job->nprocs - 1;
4218 status = ps->ps_status;
4220 /* "set -o pipefail" mode: use last _nonzero_ status */
4221 while (status == 0 && --ps >= job->ps)
4222 status = ps->ps_status;
4225 retval = WEXITSTATUS(status);
4226 if (!WIFEXITED(status)) {
4228 retval = WSTOPSIG(status);
4229 if (!WIFSTOPPED(status))
4232 /* XXX: limits number of signals */
4233 retval = WTERMSIG(status);
4235 if (retval == SIGINT)
4241 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4242 jobno(job), job->nprocs, status, retval));
4246 static int FAST_FUNC
4247 waitcmd(int argc UNUSED_PARAM, char **argv)
4258 /* wait for all jobs */
4262 if (!jp) /* no running procs */
4264 if (jp->state == JOBRUNNING)
4270 * "When bash is waiting for an asynchronous command via
4271 * the wait builtin, the reception of a signal for which a trap
4272 * has been set will cause the wait builtin to return immediately
4273 * with an exit status greater than 128, immediately after which
4274 * the trap is executed."
4276 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4277 /* if child sends us a signal *and immediately exits*,
4278 * dowait() returns pid > 0. Check this case,
4279 * not "if (dowait() < 0)"!
4288 if (**argv != '%') {
4289 pid_t pid = number(*argv);
4294 if (job->ps[job->nprocs - 1].ps_pid == pid)
4296 job = job->prev_job;
4299 job = getjob(*argv, 0);
4301 /* loop until process terminated or stopped */
4302 while (job->state == JOBRUNNING) {
4303 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4308 retval = getstatus(job);
4315 retval = 128 + pending_sig;
4324 struct job *jp, *jq;
4326 len = njobs * sizeof(*jp);
4328 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4330 offset = (char *)jp - (char *)jq;
4332 /* Relocate pointers */
4335 jq = (struct job *)((char *)jq + l);
4339 #define joff(p) ((struct job *)((char *)(p) + l))
4340 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4341 if (joff(jp)->ps == &jq->ps0)
4342 jmove(joff(jp)->ps);
4343 if (joff(jp)->prev_job)
4344 jmove(joff(jp)->prev_job);
4354 jp = (struct job *)((char *)jp + len);
4358 } while (--jq >= jp);
4363 * Return a new job structure.
4364 * Called with interrupts off.
4367 makejob(/*union node *node,*/ int nprocs)
4372 for (i = njobs, jp = jobtab; ; jp++) {
4379 if (jp->state != JOBDONE || !jp->waited)
4388 memset(jp, 0, sizeof(*jp));
4390 /* jp->jobctl is a bitfield.
4391 * "jp->jobctl |= jobctl" likely to give awful code */
4395 jp->prev_job = curjob;
4400 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4402 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4409 * Return a string identifying a command (to be printed by the
4412 static char *cmdnextc;
4415 cmdputs(const char *s)
4417 static const char vstype[VSTYPE + 1][3] = {
4418 "", "}", "-", "+", "?", "=",
4419 "%", "%%", "#", "##"
4420 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4423 const char *p, *str;
4427 unsigned char subtype = 0;
4431 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4433 while ((c = *p++) != '\0') {
4441 if ((subtype & VSTYPE) == VSLENGTH)
4447 str = "\"}" + !(quoted & 1);
4454 #if ENABLE_SH_MATH_SUPPORT
4469 if ((subtype & VSTYPE) != VSNORMAL)
4471 str = vstype[subtype & VSTYPE];
4472 if (subtype & VSNUL)
4481 /* These can only happen inside quotes */
4494 while ((c = *str++) != '\0') {
4497 } /* while *p++ not NUL */
4500 USTPUTC('"', nextc);
4506 /* cmdtxt() and cmdlist() call each other */
4507 static void cmdtxt(union node *n);
4510 cmdlist(union node *np, int sep)
4512 for (; np; np = np->narg.next) {
4516 if (sep && np->narg.next)
4522 cmdtxt(union node *n)
4525 struct nodelist *lp;
4536 lp = n->npipe.cmdlist;
4554 cmdtxt(n->nbinary.ch1);
4570 cmdtxt(n->nif.test);
4572 if (n->nif.elsepart) {
4573 cmdtxt(n->nif.ifpart);
4575 n = n->nif.elsepart;
4593 cmdtxt(n->nbinary.ch1);
4603 cmdputs(n->nfor.var);
4605 cmdlist(n->nfor.args, 1);
4610 cmdputs(n->narg.text);
4614 cmdlist(n->ncmd.args, 1);
4615 cmdlist(n->ncmd.redirect, 0);
4628 cmdputs(n->ncase.expr->narg.text);
4630 for (np = n->ncase.cases; np; np = np->nclist.next) {
4631 cmdtxt(np->nclist.pattern);
4633 cmdtxt(np->nclist.body);
4647 #if ENABLE_ASH_BASH_COMPAT
4662 cmdputs(utoa(n->nfile.fd));
4664 if (n->type == NTOFD || n->type == NFROMFD) {
4665 cmdputs(utoa(n->ndup.dupfd));
4674 commandtext(union node *n)
4678 STARTSTACKSTR(cmdnextc);
4680 name = stackblock();
4681 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4682 return ckstrdup(name);
4687 * Fork off a subshell. If we are doing job control, give the subshell its
4688 * own process group. Jp is a job structure that the job is to be added to.
4689 * N is the command that will be evaluated by the child. Both jp and n may
4690 * be NULL. The mode parameter can be one of the following:
4691 * FORK_FG - Fork off a foreground process.
4692 * FORK_BG - Fork off a background process.
4693 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4694 * process group even if job control is on.
4696 * When job control is turned off, background processes have their standard
4697 * input redirected to /dev/null (except for the second and later processes
4700 * Called with interrupts off.
4703 * Clear traps on a fork.
4711 for (tp = trap; tp < &trap[NSIG]; tp++) {
4712 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4713 if (trap_ptr == trap)
4715 /* else: it "belongs" to trap_ptr vector, don't free */
4717 if ((tp - trap) != 0)
4718 setsignal(tp - trap);
4725 /* Lives far away from here, needed for forkchild */
4726 static void closescript(void);
4728 /* Called after fork(), in child */
4729 /* jp and n are NULL when called by openhere() for heredoc support */
4730 static NOINLINE void
4731 forkchild(struct job *jp, union node *n, int mode)
4735 TRACE(("Child shell %d\n", getpid()));
4739 /* man bash: "Non-builtin commands run by bash have signal handlers
4740 * set to the values inherited by the shell from its parent".
4741 * Do we do it correctly? */
4745 if (mode == FORK_NOJOB /* is it `xxx` ? */
4746 && n && n->type == NCMD /* is it single cmd? */
4747 /* && n->ncmd.args->type == NARG - always true? */
4748 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4749 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4750 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4752 TRACE(("Trap hack\n"));
4753 /* Awful hack for `trap` or $(trap).
4755 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4756 * contains an example where "trap" is executed in a subshell:
4758 * save_traps=$(trap)
4760 * eval "$save_traps"
4762 * Standard does not say that "trap" in subshell shall print
4763 * parent shell's traps. It only says that its output
4764 * must have suitable form, but then, in the above example
4765 * (which is not supposed to be normative), it implies that.
4767 * bash (and probably other shell) does implement it
4768 * (traps are reset to defaults, but "trap" still shows them),
4769 * but as a result, "trap" logic is hopelessly messed up:
4772 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4773 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4774 * # true | trap <--- trap is in subshell - no output (ditto)
4775 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4776 * trap -- 'echo Ho' SIGWINCH
4777 * # echo `(trap)` <--- in subshell in subshell - output
4778 * trap -- 'echo Ho' SIGWINCH
4779 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4780 * trap -- 'echo Ho' SIGWINCH
4782 * The rules when to forget and when to not forget traps
4783 * get really complex and nonsensical.
4785 * Our solution: ONLY bare $(trap) or `trap` is special.
4787 /* Save trap handler strings for trap builtin to print */
4788 trap_ptr = xmemdup(trap, sizeof(trap));
4789 /* Fall through into clearing traps */
4793 /* do job control only in root shell */
4795 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4798 if (jp->nprocs == 0)
4801 pgrp = jp->ps[0].ps_pid;
4802 /* this can fail because we are doing it in the parent also */
4804 if (mode == FORK_FG)
4805 xtcsetpgrp(ttyfd, pgrp);
4810 if (mode == FORK_BG) {
4811 /* man bash: "When job control is not in effect,
4812 * asynchronous commands ignore SIGINT and SIGQUIT" */
4815 if (jp->nprocs == 0) {
4817 if (open(bb_dev_null, O_RDONLY) != 0)
4818 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4822 if (iflag) { /* why if iflag only? */
4827 * "In all cases, bash ignores SIGQUIT. Non-builtin
4828 * commands run by bash have signal handlers
4829 * set to the values inherited by the shell
4831 * Take care of the second rule: */
4835 if (n && n->type == NCMD
4836 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4838 TRACE(("Job hack\n"));
4839 /* "jobs": we do not want to clear job list for it,
4840 * instead we remove only _its_ own_ job from job list.
4841 * This makes "jobs .... | cat" more useful.
4847 for (jp = curjob; jp; jp = jp->prev_job)
4852 /* Called after fork(), in parent */
4854 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4857 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4859 TRACE(("In parent shell: child = %d\n", pid));
4861 /* jp is NULL when called by openhere() for heredoc support */
4862 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4868 if (mode != FORK_NOJOB && jp->jobctl) {
4871 if (jp->nprocs == 0)
4874 pgrp = jp->ps[0].ps_pid;
4875 /* This can fail because we are doing it in the child also */
4879 if (mode == FORK_BG) {
4880 backgndpid = pid; /* set $! */
4881 set_curjob(jp, CUR_RUNNING);
4884 struct procstat *ps = &jp->ps[jp->nprocs++];
4887 ps->ps_cmd = nullstr;
4889 if (doing_jobctl && n)
4890 ps->ps_cmd = commandtext(n);
4895 /* jp and n are NULL when called by openhere() for heredoc support */
4897 forkshell(struct job *jp, union node *n, int mode)
4901 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4904 TRACE(("Fork failed, errno=%d", errno));
4907 ash_msg_and_raise_error("can't fork");
4910 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4911 forkchild(jp, n, mode);
4913 forkparent(jp, n, mode, pid);
4919 * Wait for job to finish.
4921 * Under job control we have the problem that while a child process
4922 * is running interrupts generated by the user are sent to the child
4923 * but not to the shell. This means that an infinite loop started by
4924 * an interactive user may be hard to kill. With job control turned off,
4925 * an interactive user may place an interactive program inside a loop.
4926 * If the interactive program catches interrupts, the user doesn't want
4927 * these interrupts to also abort the loop. The approach we take here
4928 * is to have the shell ignore interrupt signals while waiting for a
4929 * foreground process to terminate, and then send itself an interrupt
4930 * signal if the child process was terminated by an interrupt signal.
4931 * Unfortunately, some programs want to do a bit of cleanup and then
4932 * exit on interrupt; unless these processes terminate themselves by
4933 * sending a signal to themselves (instead of calling exit) they will
4934 * confuse this approach.
4936 * Called with interrupts off.
4939 waitforjob(struct job *jp)
4943 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4946 while (jp->state == JOBRUNNING) {
4947 /* In non-interactive shells, we _can_ get
4948 * a keyboard signal here and be EINTRed,
4949 * but we just loop back, waiting for command to complete.
4952 * "If bash is waiting for a command to complete and receives
4953 * a signal for which a trap has been set, the trap
4954 * will not be executed until the command completes."
4956 * Reality is that even if trap is not set, bash
4957 * will not act on the signal until command completes.
4958 * Try this. sleep5intoff.c:
4959 * #include <signal.h>
4960 * #include <unistd.h>
4963 * sigemptyset(&set);
4964 * sigaddset(&set, SIGINT);
4965 * sigaddset(&set, SIGQUIT);
4966 * sigprocmask(SIG_BLOCK, &set, NULL);
4970 * $ bash -c './sleep5intoff; echo hi'
4971 * ^C^C^C^C <--- pressing ^C once a second
4973 * $ bash -c './sleep5intoff; echo hi'
4974 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4977 dowait(DOWAIT_BLOCK, jp);
4984 xtcsetpgrp(ttyfd, rootpid);
4986 * This is truly gross.
4987 * If we're doing job control, then we did a TIOCSPGRP which
4988 * caused us (the shell) to no longer be in the controlling
4989 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4990 * intuit from the subprocess exit status whether a SIGINT
4991 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4993 if (jp->sigint) /* TODO: do the same with all signals */
4994 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4996 if (jp->state == JOBDONE)
5003 * return 1 if there are stopped jobs, otherwise 0
5015 if (jp && jp->state == JOBSTOPPED) {
5016 out2str("You have stopped jobs.\n");
5026 * Code for dealing with input/output redirection.
5031 #define EMPTY -2 /* marks an unused slot in redirtab */
5032 #define CLOSED -3 /* marks a slot of previously-closed fd */
5035 * Open a file in noclobber mode.
5036 * The code was copied from bash.
5039 noclobberopen(const char *fname)
5042 struct stat finfo, finfo2;
5045 * If the file exists and is a regular file, return an error
5048 r = stat(fname, &finfo);
5049 if (r == 0 && S_ISREG(finfo.st_mode)) {
5055 * If the file was not present (r != 0), make sure we open it
5056 * exclusively so that if it is created before we open it, our open
5057 * will fail. Make sure that we do not truncate an existing file.
5058 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5059 * file was not a regular file, we leave O_EXCL off.
5062 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5063 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5065 /* If the open failed, return the file descriptor right away. */
5070 * OK, the open succeeded, but the file may have been changed from a
5071 * non-regular file to a regular file between the stat and the open.
5072 * We are assuming that the O_EXCL open handles the case where FILENAME
5073 * did not exist and is symlinked to an existing file between the stat
5078 * If we can open it and fstat the file descriptor, and neither check
5079 * revealed that it was a regular file, and the file has not been
5080 * replaced, return the file descriptor.
5082 if (fstat(fd, &finfo2) == 0
5083 && !S_ISREG(finfo2.st_mode)
5084 && finfo.st_dev == finfo2.st_dev
5085 && finfo.st_ino == finfo2.st_ino
5090 /* The file has been replaced. badness. */
5097 * Handle here documents. Normally we fork off a process to write the
5098 * data to a pipe. If the document is short, we can stuff the data in
5099 * the pipe without forking.
5101 /* openhere needs this forward reference */
5102 static void expandhere(union node *arg, int fd);
5104 openhere(union node *redir)
5110 ash_msg_and_raise_error("pipe call failed");
5111 if (redir->type == NHERE) {
5112 len = strlen(redir->nhere.doc->narg.text);
5113 if (len <= PIPE_BUF) {
5114 full_write(pip[1], redir->nhere.doc->narg.text, len);
5118 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5121 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5122 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5123 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5124 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5125 signal(SIGPIPE, SIG_DFL);
5126 if (redir->type == NHERE)
5127 full_write(pip[1], redir->nhere.doc->narg.text, len);
5129 expandhere(redir->nhere.doc, pip[1]);
5130 _exit(EXIT_SUCCESS);
5138 openredirect(union node *redir)
5143 switch (redir->nfile.type) {
5144 /* Can't happen, our single caller does this itself */
5150 return openhere(redir);
5153 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5154 * allocated space. Do it only when we know it is safe.
5156 fname = redir->nfile.expfname;
5158 switch (redir->nfile.type) {
5164 f = open(fname, O_RDONLY);
5169 f = open(fname, O_RDWR|O_CREAT, 0666);
5174 #if ENABLE_ASH_BASH_COMPAT
5177 /* Take care of noclobber mode. */
5179 f = noclobberopen(fname);
5186 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5191 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5199 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5201 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5205 * Copy a file descriptor to be >= 10. Throws exception on error.
5213 newfd = fcntl(from, F_DUPFD, 10);
5214 err = newfd < 0 ? errno : 0;
5217 ash_msg_and_raise_error("%d: %m", from);
5219 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5225 dup2_or_raise(int from, int to)
5229 newfd = (from != to) ? dup2(from, to) : to;
5231 /* Happens when source fd is not open: try "echo >&99" */
5232 ash_msg_and_raise_error("%d: %m", from);
5237 /* Struct def and variable are moved down to the first usage site */
5242 struct redirtab *next;
5244 struct two_fd_t two_fd[];
5246 #define redirlist (G_var.redirlist)
5248 COPYFD_RESTORE = (int)~(INT_MAX),
5252 need_to_remember(struct redirtab *rp, int fd)
5256 if (!rp) /* remembering was not requested */
5259 for (i = 0; i < rp->pair_count; i++) {
5260 if (rp->two_fd[i].orig == fd) {
5261 /* already remembered */
5268 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5270 is_hidden_fd(struct redirtab *rp, int fd)
5273 struct parsefile *pf;
5277 /* Check open scripts' fds */
5280 /* We skip pf_fd == 0 case because of the following case:
5281 * $ ash # running ash interactively
5283 * and in script.sh: "exec 9>&0".
5284 * Even though top-level pf_fd _is_ 0,
5285 * it's still ok to use it: "read" builtin uses it,
5286 * why should we cripple "exec" builtin?
5288 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5296 /* Check saved fds of redirects */
5297 fd |= COPYFD_RESTORE;
5298 for (i = 0; i < rp->pair_count; i++) {
5299 if (rp->two_fd[i].copy == fd) {
5307 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5308 * old file descriptors are stashed away so that the redirection can be
5309 * undone by calling popredir.
5311 /* flags passed to redirect */
5312 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5313 #define REDIR_SAVEFD2 03 /* set preverrout */
5315 redirect(union node *redir, int flags)
5317 struct redirtab *sv;
5322 int copied_fd2 = -1;
5331 if (flags & REDIR_PUSH) {
5332 union node *tmp = redir;
5335 #if ENABLE_ASH_BASH_COMPAT
5336 if (tmp->nfile.type == NTO2)
5339 tmp = tmp->nfile.next;
5341 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5342 sv->next = redirlist;
5343 sv->pair_count = sv_pos;
5345 while (sv_pos > 0) {
5347 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5353 fd = redir->nfile.fd;
5354 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5355 right_fd = redir->ndup.dupfd;
5356 //bb_error_msg("doing %d > %d", fd, right_fd);
5357 /* redirect from/to same file descriptor? */
5360 /* "echo >&10" and 10 is a fd opened to a sh script? */
5361 if (is_hidden_fd(sv, right_fd)) {
5362 errno = EBADF; /* as if it is closed */
5363 ash_msg_and_raise_error("%d: %m", right_fd);
5367 newfd = openredirect(redir); /* always >= 0 */
5369 /* Descriptor wasn't open before redirect.
5370 * Mark it for close in the future */
5371 if (need_to_remember(sv, fd)) {
5372 goto remember_to_close;
5377 #if ENABLE_ASH_BASH_COMPAT
5380 if (need_to_remember(sv, fd)) {
5381 /* Copy old descriptor */
5382 /* Careful to not accidentally "save"
5383 * to the same fd as right side fd in N>&M */
5384 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5385 i = fcntl(fd, F_DUPFD, minfd);
5386 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5387 * are closed in popredir() in the child, preventing them from leaking
5388 * into child. (popredir() also cleans up the mess in case of failures)
5393 /* Strange error (e.g. "too many files" EMFILE?) */
5397 ash_msg_and_raise_error("%d: %m", fd);
5400 /* EBADF: it is not open - good, remember to close it */
5403 } else { /* fd is open, save its copy */
5404 /* "exec fd>&-" should not close fds
5405 * which point to script file(s).
5406 * Force them to be restored afterwards */
5407 if (is_hidden_fd(sv, fd))
5408 i |= COPYFD_RESTORE;
5412 sv->two_fd[sv_pos].orig = fd;
5413 sv->two_fd[sv_pos].copy = i;
5417 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5418 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5419 /* Don't want to trigger debugging */
5423 dup2_or_raise(redir->ndup.dupfd, fd);
5425 } else if (fd != newfd) { /* move newfd to fd */
5426 dup2_or_raise(newfd, fd);
5427 #if ENABLE_ASH_BASH_COMPAT
5428 if (!(redir->nfile.type == NTO2 && fd == 2))
5432 #if ENABLE_ASH_BASH_COMPAT
5433 if (redir->nfile.type == NTO2 && fd == 1) {
5434 /* We already redirected it to fd 1, now copy it to 2 */
5440 } while ((redir = redir->nfile.next) != NULL);
5443 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5444 preverrout_fd = copied_fd2;
5448 * Undo the effects of the last redirection.
5451 popredir(int drop, int restore)
5453 struct redirtab *rp;
5456 if (redirlist == NULL)
5460 for (i = 0; i < rp->pair_count; i++) {
5461 int fd = rp->two_fd[i].orig;
5462 int copy = rp->two_fd[i].copy;
5463 if (copy == CLOSED) {
5468 if (copy != EMPTY) {
5469 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5470 copy &= ~COPYFD_RESTORE;
5472 dup2_or_raise(copy, fd);
5474 close(copy & ~COPYFD_RESTORE);
5477 redirlist = rp->next;
5483 * Undo all redirections. Called on error or interrupt.
5487 redirectsafe(union node *redir, int flags)
5490 volatile int saveint;
5491 struct jmploc *volatile savehandler = exception_handler;
5492 struct jmploc jmploc;
5495 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5496 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5498 exception_handler = &jmploc;
5499 redirect(redir, flags);
5501 exception_handler = savehandler;
5502 if (err && exception_type != EXERROR)
5503 longjmp(exception_handler->loc, 1);
5504 RESTORE_INT(saveint);
5509 /* ============ Routines to expand arguments to commands
5511 * We have to deal with backquotes, shell variables, and file metacharacters.
5514 #if ENABLE_SH_MATH_SUPPORT
5516 ash_arith(const char *s)
5518 arith_state_t math_state;
5521 math_state.lookupvar = lookupvar;
5522 math_state.setvar = setvar0;
5523 //math_state.endofname = endofname;
5526 result = arith(&math_state, s);
5527 if (math_state.errmsg)
5528 ash_msg_and_raise_error(math_state.errmsg);
5538 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5539 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5540 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5541 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5542 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5543 * POSIX says for this case:
5544 * Pathname expansion shall not be performed on the word by a
5545 * non-interactive shell; an interactive shell may perform it, but shall
5546 * do so only when the expansion would result in one word.
5547 * Currently, our code complies to the above rule by never globbing
5548 * redirection filenames.
5549 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5550 * (this means that on a typical Linux distro, bash almost always
5551 * performs globbing, and thus diverges from what we do).
5553 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5554 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5555 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5556 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5557 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5561 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5562 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5563 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5564 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5565 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5567 /* Add CTLESC when necessary. */
5568 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5569 /* Do not skip NUL characters. */
5570 #define QUOTES_KEEPNUL EXP_TILDE
5573 * Structure specifying which parts of the string should be searched
5574 * for IFS characters.
5577 struct ifsregion *next; /* next region in list */
5578 int begoff; /* offset of start of region */
5579 int endoff; /* offset of end of region */
5580 int nulonly; /* search for nul bytes only */
5584 struct strlist *list;
5585 struct strlist **lastp;
5588 /* output of current string */
5589 static char *expdest;
5590 /* list of back quote expressions */
5591 static struct nodelist *argbackq;
5592 /* first struct in list of ifs regions */
5593 static struct ifsregion ifsfirst;
5594 /* last struct in list */
5595 static struct ifsregion *ifslastp;
5596 /* holds expanded arg list */
5597 static struct arglist exparg;
5602 #if !ENABLE_SH_MATH_SUPPORT
5603 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5604 typedef long arith_t;
5605 # define ARITH_FMT "%ld"
5612 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5613 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5614 STADJUST(len, expdest);
5619 * Break the argument string into pieces based upon IFS and add the
5620 * strings to the argument list. The regions of the string to be
5621 * searched for IFS characters have been stored by recordregion.
5624 ifsbreakup(char *string, struct arglist *arglist)
5626 struct ifsregion *ifsp;
5631 const char *ifs, *realifs;
5636 if (ifslastp != NULL) {
5639 realifs = ifsset() ? ifsval() : defifs;
5642 p = string + ifsp->begoff;
5643 nulonly = ifsp->nulonly;
5644 ifs = nulonly ? nullstr : realifs;
5646 while (p < string + ifsp->endoff) {
5648 if ((unsigned char)*p == CTLESC)
5650 if (!strchr(ifs, *p)) {
5655 ifsspc = (strchr(defifs, *p) != NULL);
5656 /* Ignore IFS whitespace at start */
5657 if (q == start && ifsspc) {
5663 sp = stzalloc(sizeof(*sp));
5665 *arglist->lastp = sp;
5666 arglist->lastp = &sp->next;
5670 if (p >= string + ifsp->endoff) {
5674 if ((unsigned char)*p == CTLESC)
5676 if (strchr(ifs, *p) == NULL) {
5680 if (strchr(defifs, *p) == NULL) {
5695 } while (ifsp != NULL);
5704 sp = stzalloc(sizeof(*sp));
5706 *arglist->lastp = sp;
5707 arglist->lastp = &sp->next;
5713 struct ifsregion *p = ifsfirst.next;
5720 struct ifsregion *ifsp;
5725 ifsfirst.next = NULL;
5732 esclen(const char *start, const char *p)
5736 while (p > start && (unsigned char)*--p == CTLESC) {
5743 * Remove any CTLESC characters from a string.
5746 rmescapes(char *str, int flag)
5748 static const char qchars[] ALIGN1 = {
5749 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5753 unsigned protect_against_glob;
5755 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5757 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5763 if (flag & RMESCAPE_ALLOC) {
5764 size_t len = p - str;
5765 size_t fulllen = len + strlen(p) + 1;
5767 if (flag & RMESCAPE_GROW) {
5768 int strloc = str - (char *)stackblock();
5769 r = makestrspace(fulllen, expdest);
5770 /* p and str may be invalidated by makestrspace */
5771 str = (char *)stackblock() + strloc;
5773 } else if (flag & RMESCAPE_HEAP) {
5774 r = ckmalloc(fulllen);
5776 r = stalloc(fulllen);
5780 q = (char *)memcpy(q, str, len) + len;
5785 globbing = flag & RMESCAPE_GLOB;
5786 protect_against_glob = globbing;
5788 if ((unsigned char)*p == CTLQUOTEMARK) {
5789 // Note: both inquotes and protect_against_glob only affect whether
5790 inquotes = ~inquotes;
5792 protect_against_glob = globbing;
5795 if ((unsigned char)*p == CTLESC) {
5799 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5801 if (protect_against_glob) {
5804 } else if (*p == '\\' && !inquotes) {
5805 /* naked back slash */
5806 protect_against_glob = 0;
5809 #if ENABLE_ASH_BASH_COMPAT
5810 else if (*p == '/' && slash) {
5811 /* stop handling globbing and mark location of slash */
5812 globbing = slash = 0;
5816 protect_against_glob = globbing;
5821 if (flag & RMESCAPE_GROW) {
5823 STADJUST(q - r + 1, expdest);
5827 #define pmatch(a, b) !fnmatch((a), (b), 0)
5830 * Prepare a pattern for a expmeta (internal glob(3)) call.
5832 * Returns an stalloced string.
5835 preglob(const char *pattern, int flag)
5837 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5841 * Put a string on the stack.
5844 memtodest(const char *p, size_t len, int syntax, int quotes)
5851 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5854 unsigned char c = *p++;
5856 int n = SIT(c, syntax);
5857 if ((quotes & QUOTES_ESC)
5859 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5865 } else if (!(quotes & QUOTES_KEEPNUL))
5874 strtodest(const char *p, int syntax, int quotes)
5876 size_t len = strlen(p);
5877 memtodest(p, len, syntax, quotes);
5882 * Record the fact that we have to scan this region of the
5883 * string for IFS characters.
5886 recordregion(int start, int end, int nulonly)
5888 struct ifsregion *ifsp;
5890 if (ifslastp == NULL) {
5894 ifsp = ckzalloc(sizeof(*ifsp));
5895 /*ifsp->next = NULL; - ckzalloc did it */
5896 ifslastp->next = ifsp;
5900 ifslastp->begoff = start;
5901 ifslastp->endoff = end;
5902 ifslastp->nulonly = nulonly;
5906 removerecordregions(int endoff)
5908 if (ifslastp == NULL)
5911 if (ifsfirst.endoff > endoff) {
5912 while (ifsfirst.next) {
5913 struct ifsregion *ifsp;
5915 ifsp = ifsfirst.next->next;
5916 free(ifsfirst.next);
5917 ifsfirst.next = ifsp;
5920 if (ifsfirst.begoff > endoff) {
5923 ifslastp = &ifsfirst;
5924 ifsfirst.endoff = endoff;
5929 ifslastp = &ifsfirst;
5930 while (ifslastp->next && ifslastp->next->begoff < endoff)
5931 ifslastp = ifslastp->next;
5932 while (ifslastp->next) {
5933 struct ifsregion *ifsp;
5935 ifsp = ifslastp->next->next;
5936 free(ifslastp->next);
5937 ifslastp->next = ifsp;
5940 if (ifslastp->endoff > endoff)
5941 ifslastp->endoff = endoff;
5945 exptilde(char *startp, char *p, int flags)
5951 int quotes = flags & QUOTES_ESC;
5955 while ((c = *++p) != '\0') {
5962 if (flags & EXP_VARTILDE)
5972 if (*name == '\0') {
5973 home = lookupvar("HOME");
5975 pw = getpwnam(name);
5980 if (!home || !*home)
5983 strtodest(home, SQSYNTAX, quotes);
5991 * Execute a command inside back quotes. If it's a builtin command, we
5992 * want to save its output in a block obtained from malloc. Otherwise
5993 * we fork off a subprocess and get the output of the command via a pipe.
5994 * Should be called with interrupts off.
5996 struct backcmd { /* result of evalbackcmd */
5997 int fd; /* file descriptor to read from */
5998 int nleft; /* number of chars in buffer */
5999 char *buf; /* buffer */
6000 struct job *jp; /* job structure for command */
6003 /* These forward decls are needed to use "eval" code for backticks handling: */
6004 #define EV_EXIT 01 /* exit after evaluating tree */
6005 static int evaltree(union node *, int);
6007 static void FAST_FUNC
6008 evalbackcmd(union node *n, struct backcmd *result)
6022 ash_msg_and_raise_error("pipe call failed");
6023 jp = makejob(/*n,*/ 1);
6024 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6030 dup2_or_raise(pip[1], 1);
6033 /* TODO: eflag clearing makes the following not abort:
6034 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6035 * which is what bash does (unless it is in POSIX mode).
6036 * dash deleted "eflag = 0" line in the commit
6037 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6038 * [EVAL] Don't clear eflag in evalbackcmd
6039 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6043 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6048 result->fd = pip[0];
6052 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6053 result->fd, result->buf, result->nleft, result->jp));
6057 * Expand stuff in backwards quotes.
6060 expbackq(union node *cmd, int flag)
6068 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6069 struct stackmark smark;
6072 startloc = expdest - (char *)stackblock();
6073 pushstackmark(&smark, startloc);
6074 evalbackcmd(cmd, &in);
6075 popstackmark(&smark);
6082 memtodest(p, i, syntax, flag & QUOTES_ESC);
6086 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6087 TRACE(("expbackq: read returns %d\n", i));
6096 back_exitstatus = waitforjob(in.jp);
6100 /* Eat all trailing newlines */
6102 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6106 if (!(flag & EXP_QUOTED))
6107 recordregion(startloc, dest - (char *)stackblock(), 0);
6108 TRACE(("evalbackq: size:%d:'%.*s'\n",
6109 (int)((dest - (char *)stackblock()) - startloc),
6110 (int)((dest - (char *)stackblock()) - startloc),
6111 stackblock() + startloc));
6114 #if ENABLE_SH_MATH_SUPPORT
6116 * Expand arithmetic expression. Backup to start of expression,
6117 * evaluate, place result in (backed up) result, adjust string position.
6129 * This routine is slightly over-complicated for
6130 * efficiency. Next we scan backwards looking for the
6131 * start of arithmetic.
6133 start = stackblock();
6140 while ((unsigned char)*p != CTLARI) {
6144 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6149 esc = esclen(start, p);
6159 removerecordregions(begoff);
6163 if (flag & QUOTES_ESC)
6164 rmescapes(p + 1, 0);
6166 len = cvtnum(ash_arith(p + 1));
6168 if (!(flag & EXP_QUOTED))
6169 recordregion(begoff, begoff + len, 0);
6173 /* argstr needs it */
6174 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6177 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6178 * characters to allow for further processing. Otherwise treat
6179 * $@ like $* since no splitting will be performed.
6181 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6182 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6183 * for correct expansion of "B=$A" word.
6186 argstr(char *p, int flags, struct strlist *var_str_list)
6188 static const char spclchars[] ALIGN1 = {
6196 #if ENABLE_SH_MATH_SUPPORT
6201 const char *reject = spclchars;
6202 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6207 if (!(flags & EXP_VARTILDE)) {
6209 } else if (flags & EXP_VARTILDE2) {
6214 if (flags & EXP_TILDE) {
6217 flags &= ~EXP_TILDE;
6221 p = exptilde(p, q, flags);
6224 startloc = expdest - (char *)stackblock();
6228 length += strcspn(p + length, reject);
6232 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6234 /* c == '=' || c == ':' || c == CTLENDARI */
6240 expdest = stack_nputstr(p, length, expdest);
6241 newloc = expdest - (char *)stackblock();
6242 if (breakall && !inquotes && newloc > startloc) {
6243 recordregion(startloc, newloc, 0);
6254 if (flags & EXP_VARTILDE2) {
6258 flags |= EXP_VARTILDE2;
6263 * sort of a hack - expand tildes in variable
6264 * assignments (after the first '=' and after ':'s).
6273 case CTLENDVAR: /* ??? */
6276 inquotes ^= EXP_QUOTED;
6277 /* "$@" syntax adherence hack */
6278 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6279 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6283 if (flags & QUOTES_ESC) {
6294 * Quoted parameter expansion pattern: remove quote
6295 * unless inside inner quotes or we have a literal
6298 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6299 EXP_QPAT && *p != '\\')
6304 TRACE(("argstr: evalvar('%s')\n", p));
6305 p = evalvar(p, flags | inquotes, var_str_list);
6306 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6309 expbackq(argbackq->n, flags | inquotes);
6310 argbackq = argbackq->next;
6312 #if ENABLE_SH_MATH_SUPPORT
6315 expari(flags | inquotes);
6324 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6325 char *pattern, int quotes, int zero)
6334 const char *s = loc2;
6341 match = pmatch(pattern, s);
6346 if (quotes && (unsigned char)*loc == CTLESC)
6355 scanright(char *startp, char *rmesc, char *rmescend,
6356 char *pattern, int quotes, int match_at_start)
6358 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6359 int try2optimize = match_at_start;
6365 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6366 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6367 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6369 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6370 * and on each iteration they go back two/one char until they reach the beginning.
6371 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6373 /* TODO: document in what other circumstances we are called. */
6375 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6378 const char *s = loc2;
6379 if (match_at_start) {
6383 match = pmatch(pattern, s);
6384 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6388 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6390 /* Maybe we can optimize this:
6391 * if pattern ends with unescaped *, we can avoid checking
6392 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6393 * it wont match truncated "raw_value_of_" strings too.
6395 unsigned plen = strlen(pattern);
6396 /* Does it end with "*"? */
6397 if (plen != 0 && pattern[--plen] == '*') {
6398 /* "xxxx*" is not escaped */
6399 /* "xxx\*" is escaped */
6400 /* "xx\\*" is not escaped */
6401 /* "x\\\*" is escaped */
6403 while (plen != 0 && pattern[--plen] == '\\')
6406 break; /* ends with unescaped "*" */
6414 esc = esclen(startp, loc);
6425 static void varunset(const char *, const char *, const char *, int) NORETURN;
6427 varunset(const char *end, const char *var, const char *umsg, int varflags)
6433 msg = "parameter not set";
6435 if ((unsigned char)*end == CTLENDVAR) {
6436 if (varflags & VSNUL)
6442 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6446 subevalvar(char *p, char *varname, int strloc, int subtype,
6447 int startloc, int varflags, int flag, struct strlist *var_str_list)
6449 struct nodelist *saveargbackq = argbackq;
6450 int quotes = flag & QUOTES_ESC;
6453 char *rmesc, *rmescend;
6455 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6456 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6457 int amount, resetloc;
6458 IF_ASH_BASH_COMPAT(int workloc;)
6460 char *(*scan)(char*, char*, char*, char*, int, int);
6462 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6463 // p, varname, strloc, subtype, startloc, varflags, quotes);
6465 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6466 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6468 STPUTC('\0', expdest);
6469 argbackq = saveargbackq;
6470 startp = (char *)stackblock() + startloc;
6474 setvar0(varname, startp);
6475 amount = startp - expdest;
6476 STADJUST(amount, expdest);
6480 varunset(p, varname, startp, varflags);
6483 #if ENABLE_ASH_BASH_COMPAT
6485 //TODO: support more general format ${v:EXPR:EXPR},
6486 // where EXPR follows $(()) rules
6487 loc = str = stackblock() + strloc;
6488 /* Read POS in ${var:POS:LEN} */
6489 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6490 len = str - startp - 1;
6492 /* *loc != '\0', guaranteed by parser */
6496 /* Adjust the length by the number of escapes */
6497 for (ptr = startp; ptr < (str - 1); ptr++) {
6498 if ((unsigned char)*ptr == CTLESC) {
6506 if (*loc++ == ':') {
6510 /* Skip POS in ${var:POS:LEN} */
6512 while (*loc && *loc != ':') {
6514 * bash complains on: var=qwe; echo ${var:1a:123}
6516 ash_msg_and_raise_error(msg_illnum, str);
6520 if (*loc++ == ':') {
6525 /* ${VAR:$((-n)):l} starts n chars from the end */
6526 pos = orig_len + pos;
6528 if ((unsigned)pos >= orig_len) {
6529 /* apart from obvious ${VAR:999999:l},
6530 * covers ${VAR:$((-9999999)):l} - result is ""
6536 if (len > (orig_len - pos))
6537 len = orig_len - pos;
6539 for (str = startp; pos; str++, pos--) {
6540 if (quotes && (unsigned char)*str == CTLESC)
6543 for (loc = startp; len; len--) {
6544 if (quotes && (unsigned char)*str == CTLESC)
6549 amount = loc - expdest;
6550 STADJUST(amount, expdest);
6555 resetloc = expdest - (char *)stackblock();
6557 /* We'll comeback here if we grow the stack while handling
6558 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6559 * stack will need rebasing, and we'll need to remove our work
6562 IF_ASH_BASH_COMPAT(restart:)
6564 amount = expdest - ((char *)stackblock() + resetloc);
6565 STADJUST(-amount, expdest);
6566 startp = (char *)stackblock() + startloc;
6569 rmescend = (char *)stackblock() + strloc;
6571 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6572 if (rmesc != startp) {
6574 startp = (char *)stackblock() + startloc;
6578 str = (char *)stackblock() + strloc;
6580 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6581 * The result is a_\_z_c (not a\_\_z_c)!
6583 * The search pattern and replace string treat backslashes differently!
6584 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6585 * and string. It's only used on the first call.
6587 preglob(str, IF_ASH_BASH_COMPAT(
6588 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6589 RMESCAPE_SLASH :) 0);
6591 #if ENABLE_ASH_BASH_COMPAT
6592 workloc = expdest - (char *)stackblock();
6593 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6597 repl = strchr(str, CTLESC);
6603 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6605 /* If there's no pattern to match, return the expansion unmolested */
6614 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6615 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6617 /* No match, advance */
6618 char *restart_detect = stackblock();
6620 STPUTC(*idx, expdest);
6621 if (quotes && (unsigned char)*idx == CTLESC) {
6624 STPUTC(*idx, expdest);
6626 if (stackblock() != restart_detect)
6631 /* continue; - prone to quadratic behavior, smarter code: */
6634 if (str[0] == '*') {
6635 /* Pattern is "*foo". If "*foo" does not match "long_string",
6636 * it would never match "ong_string" etc, no point in trying.
6643 if (subtype == VSREPLACEALL) {
6645 if (quotes && (unsigned char)*idx == CTLESC)
6654 //bb_error_msg("repl:'%s'", repl);
6655 for (loc = (char*)repl; *loc; loc++) {
6656 char *restart_detect = stackblock();
6657 if (quotes && *loc == '\\') {
6658 STPUTC(CTLESC, expdest);
6661 STPUTC(*loc, expdest);
6662 if (stackblock() != restart_detect)
6667 if (subtype == VSREPLACE) {
6668 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6670 char *restart_detect = stackblock();
6671 STPUTC(*idx, expdest);
6672 if (stackblock() != restart_detect)
6681 /* We've put the replaced text into a buffer at workloc, now
6682 * move it to the right place and adjust the stack.
6684 STPUTC('\0', expdest);
6685 startp = (char *)stackblock() + startloc;
6686 memmove(startp, (char *)stackblock() + workloc, len + 1);
6687 //bb_error_msg("startp:'%s'", startp);
6688 amount = expdest - (startp + len);
6689 STADJUST(-amount, expdest);
6692 #endif /* ENABLE_ASH_BASH_COMPAT */
6694 subtype -= VSTRIMRIGHT;
6696 if (subtype < 0 || subtype > 7)
6699 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6700 zero = subtype >> 1;
6701 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6702 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6704 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6707 memmove(startp, loc, str - loc);
6708 loc = startp + (str - loc) - 1;
6711 amount = loc - expdest;
6712 STADJUST(amount, expdest);
6718 * Add the value of a specialized variable to the stack string.
6719 * name parameter (examples):
6720 * ash -c 'echo $1' name:'1='
6721 * ash -c 'echo $qwe' name:'qwe='
6722 * ash -c 'echo $$' name:'$='
6723 * ash -c 'echo ${$}' name:'$='
6724 * ash -c 'echo ${$##q}' name:'$=q'
6725 * ash -c 'echo ${#$}' name:'$='
6726 * note: examples with bad shell syntax:
6727 * ash -c 'echo ${#$1}' name:'$=1'
6728 * ash -c 'echo ${#1#}' name:'1=#'
6730 static NOINLINE ssize_t
6731 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6738 int quoted = *quotedp;
6739 int subtype = varflags & VSTYPE;
6740 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6741 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6744 sep = (flags & EXP_FULL) << CHAR_BIT;
6745 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6755 num = shellparam.nparam;
6763 goto check_1char_name;
6765 expdest = makestrspace(NOPTS, expdest);
6766 for (i = NOPTS - 1; i >= 0; i--) {
6768 USTPUTC(optletters(i), expdest);
6774 /* handles cases similar to ${#$1} */
6775 if (name[2] != '\0')
6776 raise_error_syntax("bad substitution");
6789 sep |= ifsset() ? ifsval()[0] : ' ';
6796 while ((p = *ap++) != NULL) {
6797 len += strtodest(p, syntax, quotes);
6801 memtodest(&sepc, 1, syntax, quotes);
6816 num = atoi(name); /* number(name) fails on ${N#str} etc */
6817 if (num < 0 || num > shellparam.nparam)
6819 p = num ? shellparam.p[num - 1] : arg0;
6822 /* NB: name has form "VAR=..." */
6824 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6825 * which should be considered before we check variables. */
6827 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6831 str = var_str_list->text;
6832 eq = strchr(str, '=');
6833 if (!eq) /* stop at first non-assignment */
6836 if (name_len == (unsigned)(eq - str)
6837 && strncmp(str, name, name_len) == 0
6840 /* goto value; - WRONG! */
6841 /* think "A=1 A=2 B=$A" */
6843 var_str_list = var_str_list->next;
6844 } while (var_str_list);
6848 p = lookupvar(name);
6853 len = strtodest(p, syntax, quotes);
6854 #if ENABLE_UNICODE_SUPPORT
6855 if (subtype == VSLENGTH && len > 0) {
6856 reinit_unicode_for_ash();
6857 if (unicode_status == UNICODE_ON) {
6858 STADJUST(-len, expdest);
6860 len = unicode_strlen(p);
6868 STADJUST(-len, expdest);
6873 * Expand a variable, and return a pointer to the next character in the
6877 evalvar(char *p, int flag, struct strlist *var_str_list)
6888 varflags = (unsigned char) *p++;
6889 subtype = varflags & VSTYPE;
6892 raise_error_syntax("bad substitution");
6894 quoted = flag & EXP_QUOTED;
6896 easy = (!quoted || (*var == '@' && shellparam.nparam));
6897 startloc = expdest - (char *)stackblock();
6898 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6901 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6902 if (varflags & VSNUL)
6905 if (subtype == VSPLUS) {
6906 varlen = -1 - varlen;
6910 if (subtype == VSMINUS) {
6915 flag | EXP_TILDE | EXP_WORD,
6923 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6927 subevalvar(p, var, 0, subtype, startloc, varflags,
6928 flag & ~QUOTES_ESC, var_str_list);
6931 * Remove any recorded regions beyond
6934 removerecordregions(startloc);
6938 if (varlen < 0 && uflag)
6939 varunset(p, var, 0, 0);
6941 if (subtype == VSLENGTH) {
6942 cvtnum(varlen > 0 ? varlen : 0);
6946 if (subtype == VSNORMAL) {
6950 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6959 case VSTRIMRIGHTMAX:
6960 #if ENABLE_ASH_BASH_COMPAT
6973 * Terminate the string and start recording the pattern
6976 STPUTC('\0', expdest);
6977 patloc = expdest - (char *)stackblock();
6978 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6979 startloc, varflags, flag, var_str_list)) {
6980 int amount = expdest - (
6981 (char *)stackblock() + patloc - 1
6983 STADJUST(-amount, expdest);
6985 /* Remove any recorded regions beyond start of variable */
6986 removerecordregions(startloc);
6991 if (subtype != VSNORMAL) { /* skip to end of alternative */
6994 unsigned char c = *p++;
6997 else if (c == CTLBACKQ) {
6999 argbackq = argbackq->next;
7000 } else if (c == CTLVAR) {
7001 if ((*p++ & VSTYPE) != VSNORMAL)
7003 } else if (c == CTLENDVAR) {
7013 * Add a file name to the list.
7016 addfname(const char *name)
7020 sp = stzalloc(sizeof(*sp));
7021 sp->text = sstrdup(name);
7023 exparg.lastp = &sp->next;
7026 /* If we want to use glob() from libc... */
7027 #if !ENABLE_ASH_INTERNAL_GLOB
7029 /* Add the result of glob() to the list */
7031 addglob(const glob_t *pglob)
7033 char **p = pglob->gl_pathv;
7040 expandmeta(struct strlist *str /*, int flag*/)
7042 /* TODO - EXP_REDIR */
7052 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7053 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7054 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7056 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7057 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7058 // Which means you need to unescape the string, right? Not so fast:
7059 // if there _is_ a file named "file\?" (with backslash), it is returned
7060 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7061 // You DONT KNOW by looking at the result whether you need to unescape it.
7063 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7064 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7065 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7066 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7067 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7068 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7069 i = glob(p, 0, NULL, &pglob);
7070 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7075 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7076 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7077 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7089 *exparg.lastp = str;
7090 rmescapes(str->text, 0);
7091 exparg.lastp = &str->next;
7093 default: /* GLOB_NOSPACE */
7096 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7103 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7106 * Do metacharacter (i.e. *, ?, [...]) expansion.
7109 expmeta(char *expdir, char *enddir, char *name)
7125 for (p = name; esc = 0, *p; p += esc + 1) {
7126 if (*p == '*' || *p == '?')
7128 else if (*p == '[') {
7135 if (*q == '/' || *q == '\0')
7145 if (p[esc] == '/') {
7148 start = p + esc + 1;
7152 if (metaflag == 0) { /* we've reached the end of the file name */
7153 if (enddir != expdir)
7161 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7172 } while (p < start);
7174 if (enddir == expdir) {
7176 } else if (enddir == expdir + 1 && *expdir == '/') {
7185 if (enddir != expdir)
7187 if (*endname == 0) {
7200 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7201 if (dp->d_name[0] == '.' && !matchdot)
7203 if (pmatch(start, dp->d_name)) {
7205 strcpy(enddir, dp->d_name);
7208 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7211 expmeta(expdir, p, endname);
7217 endname[-esc - 1] = esc ? '\\' : '/';
7220 static struct strlist *
7221 msort(struct strlist *list, int len)
7223 struct strlist *p, *q = NULL;
7224 struct strlist **lpp;
7232 for (n = half; --n >= 0;) {
7236 q->next = NULL; /* terminate first half of list */
7237 q = msort(list, half); /* sort first half of list */
7238 p = msort(p, len - half); /* sort second half */
7241 #if ENABLE_LOCALE_SUPPORT
7242 if (strcoll(p->text, q->text) < 0)
7244 if (strcmp(p->text, q->text) < 0)
7268 * Sort the results of file name expansion. It calculates the number of
7269 * strings to sort and then calls msort (short for merge sort) to do the
7272 static struct strlist *
7273 expsort(struct strlist *str)
7279 for (sp = str; sp; sp = sp->next)
7281 return msort(str, len);
7285 expandmeta(struct strlist *str /*, int flag*/)
7287 static const char metachars[] ALIGN1 = {
7290 /* TODO - EXP_REDIR */
7294 struct strlist **savelastp;
7300 if (!strpbrk(str->text, metachars))
7302 savelastp = exparg.lastp;
7305 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7307 int i = strlen(str->text);
7308 //BUGGY estimation of how long expanded name can be
7309 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7311 expmeta(expdir, expdir, p);
7316 if (exparg.lastp == savelastp) {
7321 *exparg.lastp = str;
7322 rmescapes(str->text, 0);
7323 exparg.lastp = &str->next;
7325 *exparg.lastp = NULL;
7326 *savelastp = sp = expsort(*savelastp);
7327 while (sp->next != NULL)
7329 exparg.lastp = &sp->next;
7334 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7337 * Perform variable substitution and command substitution on an argument,
7338 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7339 * perform splitting and file name expansion. When arglist is NULL, perform
7340 * here document expansion.
7343 expandarg(union node *arg, struct arglist *arglist, int flag)
7348 argbackq = arg->narg.backquote;
7349 STARTSTACKSTR(expdest);
7350 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7351 argstr(arg->narg.text, flag,
7352 /* var_str_list: */ arglist ? arglist->list : NULL);
7353 p = _STPUTC('\0', expdest);
7355 if (arglist == NULL) {
7356 /* here document expanded */
7359 p = grabstackstr(p);
7360 TRACE(("expandarg: p:'%s'\n", p));
7361 exparg.lastp = &exparg.list;
7365 if (flag & EXP_FULL) {
7366 ifsbreakup(p, &exparg);
7367 *exparg.lastp = NULL;
7368 exparg.lastp = &exparg.list;
7369 expandmeta(exparg.list /*, flag*/);
7371 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7373 TRACE(("expandarg: rmescapes:'%s'\n", p));
7375 sp = stzalloc(sizeof(*sp));
7378 exparg.lastp = &sp->next;
7380 *exparg.lastp = NULL;
7382 *arglist->lastp = exparg.list;
7383 arglist->lastp = exparg.lastp;
7391 * Expand shell variables and backquotes inside a here document.
7394 expandhere(union node *arg, int fd)
7396 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7397 full_write(fd, stackblock(), expdest - (char *)stackblock());
7401 * Returns true if the pattern matches the string.
7404 patmatch(char *pattern, const char *string)
7406 return pmatch(preglob(pattern, 0), string);
7410 * See if a pattern matches in a case statement.
7413 casematch(union node *pattern, char *val)
7415 struct stackmark smark;
7418 setstackmark(&smark);
7419 argbackq = pattern->narg.backquote;
7420 STARTSTACKSTR(expdest);
7421 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7422 /* var_str_list: */ NULL);
7423 STACKSTRNUL(expdest);
7425 result = patmatch(stackblock(), val);
7426 popstackmark(&smark);
7431 /* ============ find_command */
7435 int (*builtin)(int, char **) FAST_FUNC;
7436 /* unsigned flags; */
7438 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7439 /* "regular" builtins always take precedence over commands,
7440 * regardless of PATH=....%builtin... position */
7441 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7442 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7445 smallint cmdtype; /* CMDxxx */
7448 /* index >= 0 for commands without path (slashes) */
7449 /* (TODO: what exactly does the value mean? PATH position?) */
7450 /* index == -1 for commands with slashes */
7451 /* index == (-2 - applet_no) for NOFORK applets */
7452 const struct builtincmd *cmd;
7453 struct funcnode *func;
7456 /* values of cmdtype */
7457 #define CMDUNKNOWN -1 /* no entry in table for command */
7458 #define CMDNORMAL 0 /* command is an executable program */
7459 #define CMDFUNCTION 1 /* command is a shell function */
7460 #define CMDBUILTIN 2 /* command is a shell builtin */
7462 /* action to find_command() */
7463 #define DO_ERR 0x01 /* prints errors */
7464 #define DO_ABS 0x02 /* checks absolute paths */
7465 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7466 #define DO_ALTPATH 0x08 /* using alternate path */
7467 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7469 static void find_command(char *, struct cmdentry *, int, const char *);
7472 /* ============ Hashing commands */
7475 * When commands are first encountered, they are entered in a hash table.
7476 * This ensures that a full path search will not have to be done for them
7477 * on each invocation.
7479 * We should investigate converting to a linear search, even though that
7480 * would make the command name "hash" a misnomer.
7484 struct tblentry *next; /* next entry in hash chain */
7485 union param param; /* definition of builtin function */
7486 smallint cmdtype; /* CMDxxx */
7487 char rehash; /* if set, cd done since entry created */
7488 char cmdname[1]; /* name of command */
7491 static struct tblentry **cmdtable;
7492 #define INIT_G_cmdtable() do { \
7493 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7496 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7500 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7502 #if ENABLE_FEATURE_SH_STANDALONE
7503 if (applet_no >= 0) {
7504 if (APPLET_IS_NOEXEC(applet_no)) {
7508 run_applet_no_and_exit(applet_no, argv);
7510 /* re-exec ourselves with the new arguments */
7511 execve(bb_busybox_exec_path, argv, envp);
7512 /* If they called chroot or otherwise made the binary no longer
7513 * executable, fall through */
7520 execve(cmd, argv, envp);
7521 } while (errno == EINTR);
7523 execve(cmd, argv, envp);
7525 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7526 /* Run "cmd" as a shell script:
7527 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7528 * "If the execve() function fails with ENOEXEC, the shell
7529 * shall execute a command equivalent to having a shell invoked
7530 * with the command name as its first operand,
7531 * with any remaining arguments passed to the new shell"
7533 * That is, do not use $SHELL, user's shell, or /bin/sh;
7534 * just call ourselves.
7536 * Note that bash reads ~80 chars of the file, and if it sees
7537 * a zero byte before it sees newline, it doesn't try to
7538 * interpret it, but fails with "cannot execute binary file"
7539 * message and exit code 126. For one, this prevents attempts
7540 * to interpret foreign ELF binaries as shell scripts.
7543 cmd = (char*) bb_busybox_exec_path;
7544 /* NB: this is only possible because all callers of shellexec()
7545 * ensure that the argv[-1] slot exists!
7548 argv[0] = (char*) "ash";
7554 * Exec a program. Never returns. If you change this routine, you may
7555 * have to change the find_command routine as well.
7556 * argv[-1] must exist and be writable! See tryexec() for why.
7558 static void shellexec(char **, const char *, int) NORETURN;
7560 shellexec(char **argv, const char *path, int idx)
7566 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7568 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7569 if (strchr(argv[0], '/') != NULL
7570 #if ENABLE_FEATURE_SH_STANDALONE
7571 || (applet_no = find_applet_by_name(argv[0])) >= 0
7574 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7575 if (applet_no >= 0) {
7576 /* We tried execing ourself, but it didn't work.
7577 * Maybe /proc/self/exe doesn't exist?
7586 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7587 if (--idx < 0 && pathopt == NULL) {
7588 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7589 if (errno != ENOENT && errno != ENOTDIR)
7596 /* Map to POSIX errors */
7608 exitstatus = exerrno;
7609 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7610 argv[0], e, suppress_int));
7611 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7616 printentry(struct tblentry *cmdp)
7622 idx = cmdp->param.index;
7625 name = path_advance(&path, cmdp->cmdname);
7627 } while (--idx >= 0);
7628 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7632 * Clear out command entries. The argument specifies the first entry in
7633 * PATH which has changed.
7636 clearcmdentry(int firstchange)
7638 struct tblentry **tblp;
7639 struct tblentry **pp;
7640 struct tblentry *cmdp;
7643 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7645 while ((cmdp = *pp) != NULL) {
7646 if ((cmdp->cmdtype == CMDNORMAL &&
7647 cmdp->param.index >= firstchange)
7648 || (cmdp->cmdtype == CMDBUILTIN &&
7649 builtinloc >= firstchange)
7662 * Locate a command in the command hash table. If "add" is nonzero,
7663 * add the command to the table if it is not already present. The
7664 * variable "lastcmdentry" is set to point to the address of the link
7665 * pointing to the entry, so that delete_cmd_entry can delete the
7668 * Interrupts must be off if called with add != 0.
7670 static struct tblentry **lastcmdentry;
7672 static struct tblentry *
7673 cmdlookup(const char *name, int add)
7675 unsigned int hashval;
7677 struct tblentry *cmdp;
7678 struct tblentry **pp;
7681 hashval = (unsigned char)*p << 4;
7683 hashval += (unsigned char)*p++;
7685 pp = &cmdtable[hashval % CMDTABLESIZE];
7686 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7687 if (strcmp(cmdp->cmdname, name) == 0)
7691 if (add && cmdp == NULL) {
7692 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7694 /* + 1 - already done because
7695 * tblentry::cmdname is char[1] */);
7696 /*cmdp->next = NULL; - ckzalloc did it */
7697 cmdp->cmdtype = CMDUNKNOWN;
7698 strcpy(cmdp->cmdname, name);
7705 * Delete the command entry returned on the last lookup.
7708 delete_cmd_entry(void)
7710 struct tblentry *cmdp;
7713 cmdp = *lastcmdentry;
7714 *lastcmdentry = cmdp->next;
7715 if (cmdp->cmdtype == CMDFUNCTION)
7716 freefunc(cmdp->param.func);
7722 * Add a new command entry, replacing any existing command entry for
7723 * the same name - except special builtins.
7726 addcmdentry(char *name, struct cmdentry *entry)
7728 struct tblentry *cmdp;
7730 cmdp = cmdlookup(name, 1);
7731 if (cmdp->cmdtype == CMDFUNCTION) {
7732 freefunc(cmdp->param.func);
7734 cmdp->cmdtype = entry->cmdtype;
7735 cmdp->param = entry->u;
7739 static int FAST_FUNC
7740 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7742 struct tblentry **pp;
7743 struct tblentry *cmdp;
7745 struct cmdentry entry;
7748 if (nextopt("r") != '\0') {
7753 if (*argptr == NULL) {
7754 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7755 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7756 if (cmdp->cmdtype == CMDNORMAL)
7764 while ((name = *argptr) != NULL) {
7765 cmdp = cmdlookup(name, 0);
7767 && (cmdp->cmdtype == CMDNORMAL
7768 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7772 find_command(name, &entry, DO_ERR, pathval());
7773 if (entry.cmdtype == CMDUNKNOWN)
7781 * Called when a cd is done. Marks all commands so the next time they
7782 * are executed they will be rehashed.
7787 struct tblentry **pp;
7788 struct tblentry *cmdp;
7790 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7791 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7792 if (cmdp->cmdtype == CMDNORMAL
7793 || (cmdp->cmdtype == CMDBUILTIN
7794 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7804 * Fix command hash table when PATH changed.
7805 * Called before PATH is changed. The argument is the new value of PATH;
7806 * pathval() still returns the old value at this point.
7807 * Called with interrupts off.
7809 static void FAST_FUNC
7810 changepath(const char *new)
7818 firstchange = 9999; /* assume no change */
7824 if ((*old == '\0' && *new == ':')
7825 || (*old == ':' && *new == '\0')
7829 old = new; /* ignore subsequent differences */
7833 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7840 if (builtinloc < 0 && idx_bltin >= 0)
7841 builtinloc = idx_bltin; /* zap builtins */
7842 if (builtinloc >= 0 && idx_bltin < 0)
7844 clearcmdentry(firstchange);
7845 builtinloc = idx_bltin;
7870 #if ENABLE_ASH_BASH_COMPAT
7881 typedef smallint token_id_t;
7883 /* Nth bit indicates if token marks the end of a list */
7886 /* 0 */ | (1u << TEOF)
7887 /* 1 */ | (0u << TNL)
7888 /* 2 */ | (0u << TREDIR)
7889 /* 3 */ | (0u << TWORD)
7890 /* 4 */ | (0u << TSEMI)
7891 /* 5 */ | (0u << TBACKGND)
7892 /* 6 */ | (0u << TAND)
7893 /* 7 */ | (0u << TOR)
7894 /* 8 */ | (0u << TPIPE)
7895 /* 9 */ | (0u << TLP)
7896 /* 10 */ | (1u << TRP)
7897 /* 11 */ | (1u << TENDCASE)
7898 /* 12 */ | (1u << TENDBQUOTE)
7899 /* 13 */ | (0u << TNOT)
7900 /* 14 */ | (0u << TCASE)
7901 /* 15 */ | (1u << TDO)
7902 /* 16 */ | (1u << TDONE)
7903 /* 17 */ | (1u << TELIF)
7904 /* 18 */ | (1u << TELSE)
7905 /* 19 */ | (1u << TESAC)
7906 /* 20 */ | (1u << TFI)
7907 /* 21 */ | (0u << TFOR)
7908 #if ENABLE_ASH_BASH_COMPAT
7909 /* 22 */ | (0u << TFUNCTION)
7911 /* 23 */ | (0u << TIF)
7912 /* 24 */ | (0u << TIN)
7913 /* 25 */ | (1u << TTHEN)
7914 /* 26 */ | (0u << TUNTIL)
7915 /* 27 */ | (0u << TWHILE)
7916 /* 28 */ | (0u << TBEGIN)
7917 /* 29 */ | (1u << TEND)
7918 , /* thus far 29 bits used */
7921 static const char *const tokname_array[] = {
7935 #define KWDOFFSET 13
7936 /* the following are keywords */
7946 #if ENABLE_ASH_BASH_COMPAT
7958 /* Wrapper around strcmp for qsort/bsearch/... */
7960 pstrcmp(const void *a, const void *b)
7962 return strcmp((char*)a, *(char**)b);
7965 static const char *const *
7966 findkwd(const char *s)
7968 return bsearch(s, tokname_array + KWDOFFSET,
7969 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7970 sizeof(tokname_array[0]), pstrcmp);
7974 * Locate and print what a word is...
7977 describe_command(char *command, const char *path, int describe_command_verbose)
7979 struct cmdentry entry;
7980 struct tblentry *cmdp;
7981 #if ENABLE_ASH_ALIAS
7982 const struct alias *ap;
7985 path = path ? path : pathval();
7987 if (describe_command_verbose) {
7991 /* First look at the keywords */
7992 if (findkwd(command)) {
7993 out1str(describe_command_verbose ? " is a shell keyword" : command);
7997 #if ENABLE_ASH_ALIAS
7998 /* Then look at the aliases */
7999 ap = lookupalias(command, 0);
8001 if (!describe_command_verbose) {
8006 out1fmt(" is an alias for %s", ap->val);
8010 /* Then check if it is a tracked alias */
8011 cmdp = cmdlookup(command, 0);
8013 entry.cmdtype = cmdp->cmdtype;
8014 entry.u = cmdp->param;
8016 /* Finally use brute force */
8017 find_command(command, &entry, DO_ABS, path);
8020 switch (entry.cmdtype) {
8022 int j = entry.u.index;
8028 p = path_advance(&path, command);
8032 if (describe_command_verbose) {
8034 (cmdp ? " a tracked alias for" : nullstr), p
8043 if (describe_command_verbose) {
8044 out1str(" is a shell function");
8051 if (describe_command_verbose) {
8052 out1fmt(" is a %sshell builtin",
8053 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8054 "special " : nullstr
8062 if (describe_command_verbose) {
8063 out1str(": not found\n");
8072 static int FAST_FUNC
8073 typecmd(int argc UNUSED_PARAM, char **argv)
8079 /* type -p ... ? (we don't bother checking for 'p') */
8080 if (argv[1] && argv[1][0] == '-') {
8085 err |= describe_command(argv[i++], NULL, verbose);
8090 #if ENABLE_ASH_CMDCMD
8091 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8093 parse_command_args(char **argv, const char **path)
8106 if (c == '-' && !*cp) {
8114 *path = bb_default_path;
8117 /* run 'typecmd' for other options */
8126 static int FAST_FUNC
8127 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8135 const char *path = NULL;
8137 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8138 * never reaches this function.
8141 while ((c = nextopt("pvV")) != '\0')
8143 verify |= VERIFY_VERBOSE;
8145 /*verify |= VERIFY_BRIEF*/;
8151 path = bb_default_path;
8153 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8155 if (/*verify && */ cmd)
8156 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8163 /*static int funcblocksize; // size of structures in function */
8164 /*static int funcstringsize; // size of strings in node */
8165 static void *funcblock; /* block to allocate function from */
8166 static char *funcstring_end; /* end of block to allocate strings from */
8168 /* flags in argument to evaltree */
8169 #define EV_EXIT 01 /* exit after evaluating tree */
8170 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8172 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8173 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8174 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8175 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8176 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8177 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8178 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8179 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8180 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8181 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8182 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8183 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8184 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8185 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8186 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8187 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8188 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8189 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8190 #if ENABLE_ASH_BASH_COMPAT
8191 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8193 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8194 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8195 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8196 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8197 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8198 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8199 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8200 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8201 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8204 static int calcsize(int funcblocksize, union node *n);
8207 sizenodelist(int funcblocksize, struct nodelist *lp)
8210 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8211 funcblocksize = calcsize(funcblocksize, lp->n);
8214 return funcblocksize;
8218 calcsize(int funcblocksize, union node *n)
8221 return funcblocksize;
8222 funcblocksize += nodesize[n->type];
8225 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8226 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8227 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8230 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8235 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8236 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8243 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8244 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8247 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8248 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8249 funcblocksize = calcsize(funcblocksize, n->nif.test);
8252 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8253 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8254 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8257 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8258 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8261 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8262 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8263 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8267 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8268 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8269 funcblocksize = calcsize(funcblocksize, n->narg.next);
8272 #if ENABLE_ASH_BASH_COMPAT
8279 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8280 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8284 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8285 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8289 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8290 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8293 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8296 return funcblocksize;
8300 nodeckstrdup(char *s)
8302 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8303 return strcpy(funcstring_end, s);
8306 static union node *copynode(union node *);
8308 static struct nodelist *
8309 copynodelist(struct nodelist *lp)
8311 struct nodelist *start;
8312 struct nodelist **lpp;
8317 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8318 (*lpp)->n = copynode(lp->n);
8320 lpp = &(*lpp)->next;
8327 copynode(union node *n)
8334 funcblock = (char *) funcblock + nodesize[n->type];
8338 new->ncmd.redirect = copynode(n->ncmd.redirect);
8339 new->ncmd.args = copynode(n->ncmd.args);
8340 new->ncmd.assign = copynode(n->ncmd.assign);
8343 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8344 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8349 new->nredir.redirect = copynode(n->nredir.redirect);
8350 new->nredir.n = copynode(n->nredir.n);
8357 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8358 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8361 new->nif.elsepart = copynode(n->nif.elsepart);
8362 new->nif.ifpart = copynode(n->nif.ifpart);
8363 new->nif.test = copynode(n->nif.test);
8366 new->nfor.var = nodeckstrdup(n->nfor.var);
8367 new->nfor.body = copynode(n->nfor.body);
8368 new->nfor.args = copynode(n->nfor.args);
8371 new->ncase.cases = copynode(n->ncase.cases);
8372 new->ncase.expr = copynode(n->ncase.expr);
8375 new->nclist.body = copynode(n->nclist.body);
8376 new->nclist.pattern = copynode(n->nclist.pattern);
8377 new->nclist.next = copynode(n->nclist.next);
8381 new->narg.backquote = copynodelist(n->narg.backquote);
8382 new->narg.text = nodeckstrdup(n->narg.text);
8383 new->narg.next = copynode(n->narg.next);
8386 #if ENABLE_ASH_BASH_COMPAT
8393 new->nfile.fname = copynode(n->nfile.fname);
8394 new->nfile.fd = n->nfile.fd;
8395 new->nfile.next = copynode(n->nfile.next);
8399 new->ndup.vname = copynode(n->ndup.vname);
8400 new->ndup.dupfd = n->ndup.dupfd;
8401 new->ndup.fd = n->ndup.fd;
8402 new->ndup.next = copynode(n->ndup.next);
8406 new->nhere.doc = copynode(n->nhere.doc);
8407 new->nhere.fd = n->nhere.fd;
8408 new->nhere.next = copynode(n->nhere.next);
8411 new->nnot.com = copynode(n->nnot.com);
8414 new->type = n->type;
8419 * Make a copy of a parse tree.
8421 static struct funcnode *
8422 copyfunc(union node *n)
8427 /*funcstringsize = 0;*/
8428 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8429 f = ckzalloc(blocksize /* + funcstringsize */);
8430 funcblock = (char *) f + offsetof(struct funcnode, n);
8431 funcstring_end = (char *) f + blocksize;
8433 /* f->count = 0; - ckzalloc did it */
8438 * Define a shell function.
8441 defun(union node *func)
8443 struct cmdentry entry;
8446 entry.cmdtype = CMDFUNCTION;
8447 entry.u.func = copyfunc(func);
8448 addcmdentry(func->narg.text, &entry);
8452 /* Reasons for skipping commands (see comment on breakcmd routine) */
8453 #define SKIPBREAK (1 << 0)
8454 #define SKIPCONT (1 << 1)
8455 #define SKIPFUNC (1 << 2)
8456 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8457 static int skipcount; /* number of levels to skip */
8458 static int funcnest; /* depth of function calls */
8459 static int loopnest; /* current loop nesting level */
8461 /* Forward decl way out to parsing code - dotrap needs it */
8462 static int evalstring(char *s, int flags);
8464 /* Called to execute a trap.
8465 * Single callsite - at the end of evaltree().
8466 * If we return non-zero, evaltree raises EXEXIT exception.
8468 * Perhaps we should avoid entering new trap handlers
8469 * while we are executing a trap handler. [is it a TODO?]
8476 uint8_t last_status;
8481 last_status = exitstatus;
8485 TRACE(("dotrap entered\n"));
8486 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8498 /* non-trapped SIGINT is handled separately by raise_interrupt,
8499 * don't upset it by resetting gotsig[SIGINT-1] */
8500 if (sig == SIGINT && !p)
8503 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8509 exitstatus = last_status;
8510 TRACE(("dotrap returns\n"));
8513 /* forward declarations - evaluation is fairly recursive business... */
8514 static int evalloop(union node *, int);
8515 static int evalfor(union node *, int);
8516 static int evalcase(union node *, int);
8517 static int evalsubshell(union node *, int);
8518 static void expredir(union node *);
8519 static int evalpipe(union node *, int);
8520 static int evalcommand(union node *, int);
8521 static int evalbltin(const struct builtincmd *, int, char **, int);
8522 static void prehash(union node *);
8525 * Evaluate a parse tree. The value is left in the global variable
8529 evaltree(union node *n, int flags)
8532 int (*evalfn)(union node *, int);
8536 TRACE(("evaltree(NULL) called\n"));
8539 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8546 out1fmt("Node type = %d\n", n->type);
8551 status = !evaltree(n->nnot.com, EV_TESTED);
8554 expredir(n->nredir.redirect);
8555 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8557 status = evaltree(n->nredir.n, flags & EV_TESTED);
8559 if (n->nredir.redirect)
8560 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8563 evalfn = evalcommand;
8565 if (eflag && !(flags & EV_TESTED))
8577 evalfn = evalsubshell;
8590 #error NAND + 1 != NOR
8592 #if NOR + 1 != NSEMI
8593 #error NOR + 1 != NSEMI
8595 unsigned is_or = n->type - NAND;
8598 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8600 if ((!status) == is_or || evalskip)
8606 status = evalfn(n, flags);
8610 status = evaltree(n->nif.test, EV_TESTED);
8617 if (n->nif.elsepart) {
8618 n = n->nif.elsepart;
8625 /* Not necessary. To test it:
8626 * "false; f() { qwerty; }; echo $?" should print 0.
8630 exitstatus = status;
8634 /* Order of checks below is important:
8635 * signal handlers trigger before exit caused by "set -e".
8639 if (checkexit & status)
8640 raise_exception(EXEXIT);
8641 if (flags & EV_EXIT)
8642 raise_exception(EXEXIT);
8644 TRACE(("leaving evaltree (no interrupts)\n"));
8648 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8651 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8656 int skip = evalskip;
8663 if (--skipcount <= 0) {
8674 evalloop(union node *n, int flags)
8685 i = evaltree(n->nbinary.ch1, EV_TESTED);
8687 if (skip == SKIPFUNC)
8691 if (n->type != NWHILE)
8695 status = evaltree(n->nbinary.ch2, flags);
8697 } while (!(skip & ~SKIPCONT));
8704 evalfor(union node *n, int flags)
8706 struct arglist arglist;
8709 struct stackmark smark;
8712 setstackmark(&smark);
8713 arglist.list = NULL;
8714 arglist.lastp = &arglist.list;
8715 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8716 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8718 *arglist.lastp = NULL;
8722 for (sp = arglist.list; sp; sp = sp->next) {
8723 setvar0(n->nfor.var, sp->text);
8724 status = evaltree(n->nfor.body, flags);
8725 if (skiploop() & ~SKIPCONT)
8729 popstackmark(&smark);
8735 evalcase(union node *n, int flags)
8739 struct arglist arglist;
8740 struct stackmark smark;
8743 setstackmark(&smark);
8744 arglist.list = NULL;
8745 arglist.lastp = &arglist.list;
8746 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8747 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8748 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8749 if (casematch(patp, arglist.list->text)) {
8750 /* Ensure body is non-empty as otherwise
8751 * EV_EXIT may prevent us from setting the
8754 if (evalskip == 0 && cp->nclist.body) {
8755 status = evaltree(cp->nclist.body, flags);
8762 popstackmark(&smark);
8768 * Kick off a subshell to evaluate a tree.
8771 evalsubshell(union node *n, int flags)
8774 int backgnd = (n->type == NBACKGND);
8777 expredir(n->nredir.redirect);
8778 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8781 jp = makejob(/*n,*/ 1);
8782 if (forkshell(jp, n, backgnd) == 0) {
8787 flags &= ~EV_TESTED;
8789 redirect(n->nredir.redirect, 0);
8790 evaltreenr(n->nredir.n, flags);
8796 status = waitforjob(jp);
8802 * Compute the names of the files in a redirection list.
8804 static void fixredir(union node *, const char *, int);
8806 expredir(union node *n)
8810 for (redir = n; redir; redir = redir->nfile.next) {
8814 fn.lastp = &fn.list;
8815 switch (redir->type) {
8819 #if ENABLE_ASH_BASH_COMPAT
8824 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8825 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8826 #if ENABLE_ASH_BASH_COMPAT
8830 // By the design of stack allocator, the loop of this kind:
8831 // while true; do while true; do break; done </dev/null; done
8832 // will look like a memory leak: ash plans to free expfname's
8833 // of "/dev/null" as soon as it finishes running the loop
8834 // (in this case, never).
8835 // This "fix" is wrong:
8836 if (redir->nfile.expfname)
8837 stunalloc(redir->nfile.expfname);
8838 // It results in corrupted state of stacked allocations.
8840 redir->nfile.expfname = fn.list->text;
8843 case NTOFD: /* >& */
8844 if (redir->ndup.vname) {
8845 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8846 if (fn.list == NULL)
8847 ash_msg_and_raise_error("redir error");
8848 #if ENABLE_ASH_BASH_COMPAT
8849 //FIXME: we used expandarg with different args!
8850 if (!isdigit_str9(fn.list->text)) {
8851 /* >&file, not >&fd */
8852 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8853 ash_msg_and_raise_error("redir error");
8855 goto store_expfname;
8858 fixredir(redir, fn.list->text, 1);
8866 * Evaluate a pipeline. All the processes in the pipeline are children
8867 * of the process creating the pipeline. (This differs from some versions
8868 * of the shell, which make the last process in a pipeline the parent
8872 evalpipe(union node *n, int flags)
8875 struct nodelist *lp;
8881 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8883 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8887 jp = makejob(/*n,*/ pipelen);
8889 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8893 if (pipe(pip) < 0) {
8895 ash_msg_and_raise_error("pipe call failed");
8898 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8912 evaltreenr(lp->n, flags);
8919 /* Don't want to trigger debugging */
8923 if (n->npipe.pipe_backgnd == 0) {
8924 status = waitforjob(jp);
8925 TRACE(("evalpipe: job done exit status %d\n", status));
8933 * Controls whether the shell is interactive or not.
8936 setinteractive(int on)
8938 static smallint is_interactive;
8940 if (++on == is_interactive)
8942 is_interactive = on;
8946 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8947 if (is_interactive > 1) {
8948 /* Looks like they want an interactive shell */
8949 static smallint did_banner;
8952 /* note: ash and hush share this string */
8953 out1fmt("\n\n%s %s\n"
8954 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8957 "built-in shell (ash)"
8971 setinteractive(iflag);
8973 #if ENABLE_FEATURE_EDITING_VI
8975 line_input_state->flags |= VI_MODE;
8977 line_input_state->flags &= ~VI_MODE;
8979 viflag = 0; /* forcibly keep the option off */
8983 static struct localvar *localvars;
8986 * Called after a function returns.
8987 * Interrupts must be off.
8992 struct localvar *lvp;
8995 while ((lvp = localvars) != NULL) {
8996 localvars = lvp->next;
8998 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8999 if (vp == NULL) { /* $- saved */
9000 memcpy(optlist, lvp->text, sizeof(optlist));
9001 free((char*)lvp->text);
9003 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9004 unsetvar(vp->var_text);
9007 vp->var_func(var_end(lvp->text));
9008 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9009 free((char*)vp->var_text);
9010 vp->flags = lvp->flags;
9011 vp->var_text = lvp->text;
9018 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9020 volatile struct shparam saveparam;
9021 struct localvar *volatile savelocalvars;
9022 struct jmploc *volatile savehandler;
9023 struct jmploc jmploc;
9026 saveparam = shellparam;
9027 savelocalvars = localvars;
9028 savehandler = exception_handler;
9029 e = setjmp(jmploc.loc);
9034 exception_handler = &jmploc;
9036 shellparam.malloced = 0;
9040 shellparam.nparam = argc - 1;
9041 shellparam.p = argv + 1;
9042 #if ENABLE_ASH_GETOPTS
9043 shellparam.optind = 1;
9044 shellparam.optoff = -1;
9046 evaltree(func->n.narg.next, flags & EV_TESTED);
9052 localvars = savelocalvars;
9053 freeparam(&shellparam);
9054 shellparam = saveparam;
9055 exception_handler = savehandler;
9057 evalskip &= ~SKIPFUNC;
9062 * Make a variable a local variable. When a variable is made local, it's
9063 * value and flags are saved in a localvar structure. The saved values
9064 * will be restored when the shell function returns. We handle the name
9065 * "-" as a special case: it makes changes to "set +-options" local
9066 * (options will be restored on return from the function).
9071 struct localvar *lvp;
9074 char *eq = strchr(name, '=');
9077 /* Cater for duplicate "local". Examples:
9078 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9079 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9083 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9087 * it's a duplicate "local VAR" declaration, do nothing
9094 lvp = ckzalloc(sizeof(*lvp));
9095 if (LONE_DASH(name)) {
9097 p = ckmalloc(sizeof(optlist));
9098 lvp->text = memcpy(p, optlist, sizeof(optlist));
9101 vpp = hashvar(name);
9102 vp = *findvar(vpp, name);
9104 /* variable did not exist yet */
9106 setvareq(name, VSTRFIXED);
9108 setvar(name, NULL, VSTRFIXED);
9109 vp = *vpp; /* the new variable */
9110 lvp->flags = VUNSET;
9112 lvp->text = vp->var_text;
9113 lvp->flags = vp->flags;
9114 /* make sure neither "struct var" nor string gets freed
9115 * during (un)setting:
9117 vp->flags |= VSTRFIXED|VTEXTFIXED;
9121 /* "local VAR" unsets VAR: */
9122 setvar0(name, NULL);
9126 lvp->next = localvars;
9132 * The "local" command.
9134 static int FAST_FUNC
9135 localcmd(int argc UNUSED_PARAM, char **argv)
9140 ash_msg_and_raise_error("not in a function");
9143 while ((name = *argv++) != NULL) {
9149 static int FAST_FUNC
9150 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9155 static int FAST_FUNC
9156 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9161 static int FAST_FUNC
9162 execcmd(int argc UNUSED_PARAM, char **argv)
9165 iflag = 0; /* exit on error */
9168 /* We should set up signals for "exec CMD"
9169 * the same way as for "CMD" without "exec".
9170 * But optschanged->setinteractive->setsignal
9171 * still thought we are a root shell. Therefore, for example,
9172 * SIGQUIT is still set to IGN. Fix it:
9176 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9177 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9178 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9180 shellexec(argv + 1, pathval(), 0);
9187 * The return command.
9189 static int FAST_FUNC
9190 returncmd(int argc UNUSED_PARAM, char **argv)
9193 * If called outside a function, do what ksh does;
9194 * skip the rest of the file.
9196 evalskip = SKIPFUNC;
9197 return argv[1] ? number(argv[1]) : exitstatus;
9200 /* Forward declarations for builtintab[] */
9201 static int breakcmd(int, char **) FAST_FUNC;
9202 static int dotcmd(int, char **) FAST_FUNC;
9203 static int evalcmd(int, char **, int) FAST_FUNC;
9204 static int exitcmd(int, char **) FAST_FUNC;
9205 static int exportcmd(int, char **) FAST_FUNC;
9206 #if ENABLE_ASH_GETOPTS
9207 static int getoptscmd(int, char **) FAST_FUNC;
9210 static int helpcmd(int, char **) FAST_FUNC;
9213 static int historycmd(int, char **) FAST_FUNC;
9215 #if ENABLE_SH_MATH_SUPPORT
9216 static int letcmd(int, char **) FAST_FUNC;
9218 static int readcmd(int, char **) FAST_FUNC;
9219 static int setcmd(int, char **) FAST_FUNC;
9220 static int shiftcmd(int, char **) FAST_FUNC;
9221 static int timescmd(int, char **) FAST_FUNC;
9222 static int trapcmd(int, char **) FAST_FUNC;
9223 static int umaskcmd(int, char **) FAST_FUNC;
9224 static int unsetcmd(int, char **) FAST_FUNC;
9225 static int ulimitcmd(int, char **) FAST_FUNC;
9227 #define BUILTIN_NOSPEC "0"
9228 #define BUILTIN_SPECIAL "1"
9229 #define BUILTIN_REGULAR "2"
9230 #define BUILTIN_SPEC_REG "3"
9231 #define BUILTIN_ASSIGN "4"
9232 #define BUILTIN_SPEC_ASSG "5"
9233 #define BUILTIN_REG_ASSG "6"
9234 #define BUILTIN_SPEC_REG_ASSG "7"
9236 /* Stubs for calling non-FAST_FUNC's */
9237 #if ENABLE_ASH_BUILTIN_ECHO
9238 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9240 #if ENABLE_ASH_BUILTIN_PRINTF
9241 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9243 #if ENABLE_ASH_BUILTIN_TEST
9244 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9247 /* Keep these in proper order since it is searched via bsearch() */
9248 static const struct builtincmd builtintab[] = {
9249 { BUILTIN_SPEC_REG "." , dotcmd },
9250 { BUILTIN_SPEC_REG ":" , truecmd },
9251 #if ENABLE_ASH_BUILTIN_TEST
9252 { BUILTIN_REGULAR "[" , testcmd },
9253 #if ENABLE_ASH_BASH_COMPAT
9254 { BUILTIN_REGULAR "[[" , testcmd },
9257 #if ENABLE_ASH_ALIAS
9258 { BUILTIN_REG_ASSG "alias" , aliascmd },
9261 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9263 { BUILTIN_SPEC_REG "break" , breakcmd },
9264 { BUILTIN_REGULAR "cd" , cdcmd },
9265 { BUILTIN_NOSPEC "chdir" , cdcmd },
9266 #if ENABLE_ASH_CMDCMD
9267 { BUILTIN_REGULAR "command" , commandcmd },
9269 { BUILTIN_SPEC_REG "continue", breakcmd },
9270 #if ENABLE_ASH_BUILTIN_ECHO
9271 { BUILTIN_REGULAR "echo" , echocmd },
9273 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9274 { BUILTIN_SPEC_REG "exec" , execcmd },
9275 { BUILTIN_SPEC_REG "exit" , exitcmd },
9276 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9277 { BUILTIN_REGULAR "false" , falsecmd },
9279 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9281 #if ENABLE_ASH_GETOPTS
9282 { BUILTIN_REGULAR "getopts" , getoptscmd },
9284 { BUILTIN_NOSPEC "hash" , hashcmd },
9286 { BUILTIN_NOSPEC "help" , helpcmd },
9289 { BUILTIN_NOSPEC "history" , historycmd },
9292 { BUILTIN_REGULAR "jobs" , jobscmd },
9293 { BUILTIN_REGULAR "kill" , killcmd },
9295 #if ENABLE_SH_MATH_SUPPORT
9296 { BUILTIN_NOSPEC "let" , letcmd },
9298 { BUILTIN_ASSIGN "local" , localcmd },
9299 #if ENABLE_ASH_BUILTIN_PRINTF
9300 { BUILTIN_REGULAR "printf" , printfcmd },
9302 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9303 { BUILTIN_REGULAR "read" , readcmd },
9304 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9305 { BUILTIN_SPEC_REG "return" , returncmd },
9306 { BUILTIN_SPEC_REG "set" , setcmd },
9307 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9308 #if ENABLE_ASH_BASH_COMPAT
9309 { BUILTIN_SPEC_REG "source" , dotcmd },
9311 #if ENABLE_ASH_BUILTIN_TEST
9312 { BUILTIN_REGULAR "test" , testcmd },
9314 { BUILTIN_SPEC_REG "times" , timescmd },
9315 { BUILTIN_SPEC_REG "trap" , trapcmd },
9316 { BUILTIN_REGULAR "true" , truecmd },
9317 { BUILTIN_NOSPEC "type" , typecmd },
9318 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9319 { BUILTIN_REGULAR "umask" , umaskcmd },
9320 #if ENABLE_ASH_ALIAS
9321 { BUILTIN_REGULAR "unalias" , unaliascmd },
9323 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9324 { BUILTIN_REGULAR "wait" , waitcmd },
9327 /* Should match the above table! */
9328 #define COMMANDCMD (builtintab + \
9330 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9331 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9332 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9333 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9334 /* break cd cddir */ 3)
9335 #define EVALCMD (COMMANDCMD + \
9336 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9337 /* continue */ 1 + \
9338 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9340 #define EXECCMD (EVALCMD + \
9344 * Search the table of builtin commands.
9347 pstrcmp1(const void *a, const void *b)
9349 return strcmp((char*)a, *(char**)b + 1);
9351 static struct builtincmd *
9352 find_builtin(const char *name)
9354 struct builtincmd *bp;
9357 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9364 * Execute a simple command.
9367 isassignment(const char *p)
9369 const char *q = endofname(p);
9374 static int FAST_FUNC
9375 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9377 /* Preserve exitstatus of a previous possible redirection
9378 * as POSIX mandates */
9379 return back_exitstatus;
9382 evalcommand(union node *cmd, int flags)
9384 static const struct builtincmd null_bltin = {
9385 "\0\0", bltincmd /* why three NULs? */
9387 struct stackmark smark;
9389 struct arglist arglist;
9390 struct arglist varlist;
9393 const struct strlist *sp;
9394 struct cmdentry cmdentry;
9401 struct builtincmd *bcmd;
9402 smallint cmd_is_exec;
9403 smallint pseudovarflag = 0;
9405 /* First expand the arguments. */
9406 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9407 setstackmark(&smark);
9408 back_exitstatus = 0;
9410 cmdentry.cmdtype = CMDBUILTIN;
9411 cmdentry.u.cmd = &null_bltin;
9412 varlist.lastp = &varlist.list;
9413 *varlist.lastp = NULL;
9414 arglist.lastp = &arglist.list;
9415 *arglist.lastp = NULL;
9418 if (cmd->ncmd.args) {
9419 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9420 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9423 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9424 struct strlist **spp;
9426 spp = arglist.lastp;
9427 if (pseudovarflag && isassignment(argp->narg.text))
9428 expandarg(argp, &arglist, EXP_VARTILDE);
9430 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9432 for (sp = *spp; sp; sp = sp->next)
9436 /* Reserve one extra spot at the front for shellexec. */
9437 nargv = stalloc(sizeof(char *) * (argc + 2));
9439 for (sp = arglist.list; sp; sp = sp->next) {
9440 TRACE(("evalcommand arg: %s\n", sp->text));
9441 *nargv++ = sp->text;
9446 if (iflag && funcnest == 0 && argc > 0)
9447 lastarg = nargv[-1];
9450 expredir(cmd->ncmd.redirect);
9451 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9453 path = vpath.var_text;
9454 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9455 struct strlist **spp;
9458 spp = varlist.lastp;
9459 expandarg(argp, &varlist, EXP_VARTILDE);
9462 * Modify the command lookup path, if a PATH= assignment
9466 if (varcmp(p, path) == 0)
9470 /* Print the command if xflag is set. */
9473 const char *p = " %s" + 1;
9475 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9477 for (n = 0; n < 2; n++) {
9479 fdprintf(preverrout_fd, p, sp->text);
9485 safe_write(preverrout_fd, "\n", 1);
9491 /* Now locate the command. */
9493 int cmd_flag = DO_ERR;
9494 #if ENABLE_ASH_CMDCMD
9495 const char *oldpath = path + 5;
9499 find_command(argv[0], &cmdentry, cmd_flag, path);
9500 if (cmdentry.cmdtype == CMDUNKNOWN) {
9501 flush_stdout_stderr();
9506 /* implement bltin and command here */
9507 if (cmdentry.cmdtype != CMDBUILTIN)
9510 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9511 if (cmdentry.u.cmd == EXECCMD)
9513 #if ENABLE_ASH_CMDCMD
9514 if (cmdentry.u.cmd == COMMANDCMD) {
9516 nargv = parse_command_args(argv, &path);
9519 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9520 * nargv => "PROG". path is updated if -p.
9522 argc -= nargv - argv;
9524 cmd_flag |= DO_NOFUNC;
9532 /* We have a redirection error. */
9534 raise_exception(EXERROR);
9536 exitstatus = status;
9540 /* Execute the command. */
9541 switch (cmdentry.cmdtype) {
9544 #if ENABLE_FEATURE_SH_NOFORK
9545 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9546 * around run_nofork_applet() call.
9547 * (2) Should this check also be done in forkshell()?
9548 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9550 /* find_command() encodes applet_no as (-2 - applet_no) */
9551 int applet_no = (- cmdentry.u.index - 2);
9552 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9553 listsetvar(varlist.list, VEXPORT|VSTACK);
9554 /* run <applet>_main() */
9555 status = run_nofork_applet(applet_no, argv);
9559 /* Can we avoid forking off? For example, very last command
9560 * in a script or a subshell does not need forking,
9561 * we can just exec it.
9563 if (!(flags & EV_EXIT) || may_have_traps) {
9564 /* No, forking off a child is necessary */
9566 jp = makejob(/*cmd,*/ 1);
9567 if (forkshell(jp, cmd, FORK_FG) != 0) {
9569 status = waitforjob(jp);
9571 TRACE(("forked child exited with %d\n", status));
9576 /* fall through to exec'ing external program */
9578 listsetvar(varlist.list, VEXPORT|VSTACK);
9579 shellexec(argv, path, cmdentry.u.index);
9583 cmdenviron = varlist.list;
9585 struct strlist *list = cmdenviron;
9587 if (spclbltin > 0 || argc == 0) {
9589 if (cmd_is_exec && argc > 1)
9592 listsetvar(list, i);
9594 /* Tight loop with builtins only:
9595 * "while kill -0 $child; do true; done"
9596 * will never exit even if $child died, unless we do this
9597 * to reap the zombie and make kill detect that it's gone: */
9598 dowait(DOWAIT_NONBLOCK, NULL);
9600 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9601 if (exception_type == EXERROR && spclbltin <= 0) {
9606 longjmp(exception_handler->loc, 1);
9611 listsetvar(varlist.list, 0);
9612 /* See above for the rationale */
9613 dowait(DOWAIT_NONBLOCK, NULL);
9614 if (evalfun(cmdentry.u.func, argc, argv, flags))
9617 status = exitstatus;
9622 if (cmd->ncmd.redirect)
9623 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9625 /* dsl: I think this is intended to be used to support
9626 * '_' in 'vi' command mode during line editing...
9627 * However I implemented that within libedit itself.
9629 setvar0("_", lastarg);
9631 popstackmark(&smark);
9637 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9639 char *volatile savecmdname;
9640 struct jmploc *volatile savehandler;
9641 struct jmploc jmploc;
9645 savecmdname = commandname;
9646 savehandler = exception_handler;
9647 i = setjmp(jmploc.loc);
9650 exception_handler = &jmploc;
9651 commandname = argv[0];
9653 optptr = NULL; /* initialize nextopt */
9655 status = evalcmd(argc, argv, flags);
9657 status = (*cmd->builtin)(argc, argv);
9658 flush_stdout_stderr();
9659 status |= ferror(stdout);
9660 exitstatus = status;
9663 commandname = savecmdname;
9664 exception_handler = savehandler;
9670 goodname(const char *p)
9672 return endofname(p)[0] == '\0';
9677 * Search for a command. This is called before we fork so that the
9678 * location of the command will be available in the parent as well as
9679 * the child. The check for "goodname" is an overly conservative
9680 * check that the name will not be subject to expansion.
9683 prehash(union node *n)
9685 struct cmdentry entry;
9687 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9688 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9692 /* ============ Builtin commands
9694 * Builtin commands whose functions are closely tied to evaluation
9695 * are implemented here.
9699 * Handle break and continue commands. Break, continue, and return are
9700 * all handled by setting the evalskip flag. The evaluation routines
9701 * above all check this flag, and if it is set they start skipping
9702 * commands rather than executing them. The variable skipcount is
9703 * the number of loops to break/continue, or the number of function
9704 * levels to return. (The latter is always 1.) It should probably
9705 * be an error to break out of more loops than exist, but it isn't
9706 * in the standard shell so we don't make it one here.
9708 static int FAST_FUNC
9709 breakcmd(int argc UNUSED_PARAM, char **argv)
9711 int n = argv[1] ? number(argv[1]) : 1;
9714 ash_msg_and_raise_error(msg_illnum, argv[1]);
9718 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9726 * This implements the input routines used by the parser.
9730 INPUT_PUSH_FILE = 1,
9731 INPUT_NOFILE_OK = 2,
9734 static smallint checkkwd;
9735 /* values of checkkwd variable */
9736 #define CHKALIAS 0x1
9741 * Push a string back onto the input at this current parsefile level.
9742 * We handle aliases this way.
9744 #if !ENABLE_ASH_ALIAS
9745 #define pushstring(s, ap) pushstring(s)
9748 pushstring(char *s, struct alias *ap)
9755 if (g_parsefile->strpush) {
9756 sp = ckzalloc(sizeof(*sp));
9757 sp->prev = g_parsefile->strpush;
9759 sp = &(g_parsefile->basestrpush);
9761 g_parsefile->strpush = sp;
9762 sp->prev_string = g_parsefile->next_to_pgetc;
9763 sp->prev_left_in_line = g_parsefile->left_in_line;
9764 sp->unget = g_parsefile->unget;
9765 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9766 #if ENABLE_ASH_ALIAS
9769 ap->flag |= ALIASINUSE;
9773 g_parsefile->next_to_pgetc = s;
9774 g_parsefile->left_in_line = len;
9775 g_parsefile->unget = 0;
9782 struct strpush *sp = g_parsefile->strpush;
9785 #if ENABLE_ASH_ALIAS
9787 if (g_parsefile->next_to_pgetc[-1] == ' '
9788 || g_parsefile->next_to_pgetc[-1] == '\t'
9790 checkkwd |= CHKALIAS;
9792 if (sp->string != sp->ap->val) {
9795 sp->ap->flag &= ~ALIASINUSE;
9796 if (sp->ap->flag & ALIASDEAD) {
9797 unalias(sp->ap->name);
9801 g_parsefile->next_to_pgetc = sp->prev_string;
9802 g_parsefile->left_in_line = sp->prev_left_in_line;
9803 g_parsefile->unget = sp->unget;
9804 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9805 g_parsefile->strpush = sp->prev;
9806 if (sp != &(g_parsefile->basestrpush))
9815 char *buf = g_parsefile->buf;
9817 g_parsefile->next_to_pgetc = buf;
9818 #if ENABLE_FEATURE_EDITING
9820 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9821 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9824 # if ENABLE_ASH_IDLE_TIMEOUT
9826 const char *tmout_var = lookupvar("TMOUT");
9828 timeout = atoi(tmout_var) * 1000;
9834 # if ENABLE_FEATURE_TAB_COMPLETION
9835 line_input_state->path_lookup = pathval();
9837 reinit_unicode_for_ash();
9838 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9840 /* Ctrl+C pressed */
9851 /* Ctrl+D pressed */
9854 # if ENABLE_ASH_IDLE_TIMEOUT
9855 else if (errno == EAGAIN && timeout > 0) {
9856 puts("\007timed out waiting for input: auto-logout");
9863 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9866 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9868 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9869 int flags = fcntl(0, F_GETFL);
9870 if (flags >= 0 && (flags & O_NONBLOCK)) {
9871 flags &= ~O_NONBLOCK;
9872 if (fcntl(0, F_SETFL, flags) >= 0) {
9873 out2str("sh: turning off NDELAY mode\n");
9884 * Refill the input buffer and return the next input character:
9886 * 1) If a string was pushed back on the input, pop it;
9887 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9888 * or we are reading from a string so we can't refill the buffer,
9890 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9891 * 4) Process input up to the next newline, deleting nul characters.
9893 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9894 #define pgetc_debug(...) ((void)0)
9895 static int pgetc(void);
9902 if (g_parsefile->strpush) {
9903 #if ENABLE_ASH_ALIAS
9904 if (g_parsefile->left_in_line == -1
9905 && g_parsefile->strpush->ap
9906 && g_parsefile->next_to_pgetc[-1] != ' '
9907 && g_parsefile->next_to_pgetc[-1] != '\t'
9909 pgetc_debug("preadbuffer PEOA");
9916 /* on both branches above g_parsefile->left_in_line < 0.
9917 * "pgetc" needs refilling.
9920 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9921 * pungetc() may increment it a few times.
9922 * Assuming it won't increment it to less than -90.
9924 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9925 pgetc_debug("preadbuffer PEOF1");
9926 /* even in failure keep left_in_line and next_to_pgetc
9927 * in lock step, for correct multi-layer pungetc.
9928 * left_in_line was decremented before preadbuffer(),
9929 * must inc next_to_pgetc: */
9930 g_parsefile->next_to_pgetc++;
9934 more = g_parsefile->left_in_buffer;
9936 flush_stdout_stderr();
9940 /* don't try reading again */
9941 g_parsefile->left_in_line = -99;
9942 pgetc_debug("preadbuffer PEOF2");
9943 g_parsefile->next_to_pgetc++;
9948 /* Find out where's the end of line.
9949 * Set g_parsefile->left_in_line
9950 * and g_parsefile->left_in_buffer acordingly.
9951 * NUL chars are deleted.
9953 q = g_parsefile->next_to_pgetc;
9961 memmove(q, q + 1, more);
9965 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9971 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9972 if (g_parsefile->left_in_line < 0)
9977 g_parsefile->left_in_buffer = more;
9982 out2str(g_parsefile->next_to_pgetc);
9986 pgetc_debug("preadbuffer at %d:%p'%s'",
9987 g_parsefile->left_in_line,
9988 g_parsefile->next_to_pgetc,
9989 g_parsefile->next_to_pgetc);
9990 return (unsigned char)*g_parsefile->next_to_pgetc++;
9996 g_parsefile->linno++;
9997 setprompt_if(doprompt, 2);
10002 g_parsefile->linno++;
10003 needprompt = doprompt;
10011 pgetc_debug("pgetc at %d:%p'%s'",
10012 g_parsefile->left_in_line,
10013 g_parsefile->next_to_pgetc,
10014 g_parsefile->next_to_pgetc);
10015 if (g_parsefile->unget)
10016 return g_parsefile->lastc[--g_parsefile->unget];
10018 if (--g_parsefile->left_in_line >= 0)
10019 c = (signed char)*g_parsefile->next_to_pgetc++;
10023 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10024 g_parsefile->lastc[0] = c;
10029 #if ENABLE_ASH_ALIAS
10031 pgetc_without_PEOA(void)
10035 pgetc_debug("pgetc at %d:%p'%s'",
10036 g_parsefile->left_in_line,
10037 g_parsefile->next_to_pgetc,
10038 g_parsefile->next_to_pgetc);
10040 } while (c == PEOA);
10044 # define pgetc_without_PEOA() pgetc()
10048 * Read a line from the script.
10051 pfgets(char *line, int len)
10057 while (--nleft > 0) {
10058 c = pgetc_without_PEOA();
10073 * Undo a call to pgetc. Only two characters may be pushed back.
10074 * PEOF may be pushed back.
10079 g_parsefile->unget++;
10082 /* This one eats backslash+newline */
10088 while ((c = pgetc()) == '\\') {
10089 if (pgetc() != '\n') {
10101 * To handle the "." command, a stack of input files is used. Pushfile
10102 * adds a new entry to the stack and popfile restores the previous level.
10107 struct parsefile *pf;
10109 pf = ckzalloc(sizeof(*pf));
10110 pf->prev = g_parsefile;
10112 /*pf->strpush = NULL; - ckzalloc did it */
10113 /*pf->basestrpush.prev = NULL;*/
10121 struct parsefile *pf = g_parsefile;
10124 if (pf->pf_fd >= 0)
10127 while (pf->strpush)
10129 g_parsefile = pf->prev;
10135 * Return to top level.
10140 while (g_parsefile != &basepf)
10145 * Close the file(s) that the shell is reading commands from. Called
10146 * after a fork is done.
10152 if (g_parsefile->pf_fd > 0) {
10153 close(g_parsefile->pf_fd);
10154 g_parsefile->pf_fd = 0;
10159 * Like setinputfile, but takes an open file descriptor. Call this with
10163 setinputfd(int fd, int push)
10167 g_parsefile->buf = NULL;
10169 g_parsefile->pf_fd = fd;
10170 if (g_parsefile->buf == NULL)
10171 g_parsefile->buf = ckmalloc(IBUFSIZ);
10172 g_parsefile->left_in_buffer = 0;
10173 g_parsefile->left_in_line = 0;
10174 g_parsefile->linno = 1;
10178 * Set the input to take input from a file. If push is set, push the
10179 * old input onto the stack first.
10182 setinputfile(const char *fname, int flags)
10187 fd = open(fname, O_RDONLY);
10189 if (flags & INPUT_NOFILE_OK)
10192 ash_msg_and_raise_error("can't open '%s'", fname);
10197 close_on_exec_on(fd);
10198 setinputfd(fd, flags & INPUT_PUSH_FILE);
10205 * Like setinputfile, but takes input from a string.
10208 setinputstring(char *string)
10212 g_parsefile->next_to_pgetc = string;
10213 g_parsefile->left_in_line = strlen(string);
10214 g_parsefile->buf = NULL;
10215 g_parsefile->linno = 1;
10221 * Routines to check for mail.
10224 #if ENABLE_ASH_MAIL
10226 /* Hash of mtimes of mailboxes */
10227 static unsigned mailtime_hash;
10228 /* Set if MAIL or MAILPATH is changed. */
10229 static smallint mail_var_path_changed;
10232 * Print appropriate message(s) if mail has arrived.
10233 * If mail_var_path_changed is set,
10234 * then the value of MAIL has mail_var_path_changed,
10235 * so we just update the values.
10244 struct stackmark smark;
10247 setstackmark(&smark);
10248 mpath = mpathset() ? mpathval() : mailval();
10251 p = path_advance(&mpath, nullstr);
10256 for (q = p; *q; q++)
10262 q[-1] = '\0'; /* delete trailing '/' */
10263 if (stat(p, &statb) < 0) {
10266 /* Very simplistic "hash": just a sum of all mtimes */
10267 new_hash += (unsigned)statb.st_mtime;
10269 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10270 if (mailtime_hash != 0)
10271 out2str("you have mail\n");
10272 mailtime_hash = new_hash;
10274 mail_var_path_changed = 0;
10275 popstackmark(&smark);
10278 static void FAST_FUNC
10279 changemail(const char *val UNUSED_PARAM)
10281 mail_var_path_changed = 1;
10284 #endif /* ASH_MAIL */
10287 /* ============ ??? */
10290 * Set the shell parameters.
10293 setparam(char **argv)
10299 for (nparam = 0; argv[nparam]; nparam++)
10301 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10303 *ap++ = ckstrdup(*argv++);
10306 freeparam(&shellparam);
10307 shellparam.malloced = 1;
10308 shellparam.nparam = nparam;
10309 shellparam.p = newparam;
10310 #if ENABLE_ASH_GETOPTS
10311 shellparam.optind = 1;
10312 shellparam.optoff = -1;
10317 * Process shell options. The global variable argptr contains a pointer
10318 * to the argument list; we advance it past the options.
10320 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10321 * For a non-interactive shell, an error condition encountered
10322 * by a special built-in ... shall cause the shell to write a diagnostic message
10323 * to standard error and exit as shown in the following table:
10324 * Error Special Built-In
10326 * Utility syntax error (option or operand error) Shall exit
10328 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10329 * we see that bash does not do that (set "finishes" with error code 1 instead,
10330 * and shell continues), and people rely on this behavior!
10332 * set -o barfoo 2>/dev/null
10335 * Oh well. Let's mimic that.
10338 plus_minus_o(char *name, int val)
10343 for (i = 0; i < NOPTS; i++) {
10344 if (strcmp(name, optnames(i)) == 0) {
10349 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10352 for (i = 0; i < NOPTS; i++) {
10354 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10356 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10362 setoption(int flag, int val)
10366 for (i = 0; i < NOPTS; i++) {
10367 if (optletters(i) == flag) {
10372 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10376 options(int cmdline)
10384 while ((p = *argptr) != NULL) {
10386 if (c != '-' && c != '+')
10389 val = 0; /* val = 0 if c == '+' */
10392 if (p[0] == '\0' || LONE_DASH(p)) {
10394 /* "-" means turn off -x and -v */
10397 /* "--" means reset params */
10398 else if (*argptr == NULL)
10401 break; /* "-" or "--" terminates options */
10404 /* first char was + or - */
10405 while ((c = *p++) != '\0') {
10406 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10407 if (c == 'c' && cmdline) {
10408 minusc = p; /* command is after shell args */
10409 } else if (c == 'o') {
10410 if (plus_minus_o(*argptr, val)) {
10411 /* it already printed err message */
10412 return 1; /* error */
10416 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10418 /* bash does not accept +-login, we also won't */
10419 } else if (cmdline && val && (c == '-')) { /* long options */
10420 if (strcmp(p, "login") == 0)
10432 * The shift builtin command.
10434 static int FAST_FUNC
10435 shiftcmd(int argc UNUSED_PARAM, char **argv)
10442 n = number(argv[1]);
10443 if (n > shellparam.nparam)
10444 n = 0; /* bash compat, was = shellparam.nparam; */
10446 shellparam.nparam -= n;
10447 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10448 if (shellparam.malloced)
10451 ap2 = shellparam.p;
10452 while ((*ap2++ = *ap1++) != NULL)
10454 #if ENABLE_ASH_GETOPTS
10455 shellparam.optind = 1;
10456 shellparam.optoff = -1;
10463 * POSIX requires that 'set' (but not export or readonly) output the
10464 * variables in lexicographic order - by the locale's collating order (sigh).
10465 * Maybe we could keep them in an ordered balanced binary tree
10466 * instead of hashed lists.
10467 * For now just roll 'em through qsort for printing...
10470 showvars(const char *sep_prefix, int on, int off)
10473 char **ep, **epend;
10475 ep = listvars(on, off, &epend);
10476 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10478 sep = *sep_prefix ? " " : sep_prefix;
10480 for (; ep < epend; ep++) {
10484 p = strchrnul(*ep, '=');
10487 q = single_quote(++p);
10488 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10494 * The set command builtin.
10496 static int FAST_FUNC
10497 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10502 return showvars(nullstr, 0, VUNSET);
10505 retval = options(/*cmdline:*/ 0);
10506 if (retval == 0) { /* if no parse error... */
10508 if (*argptr != NULL) {
10516 #if ENABLE_ASH_RANDOM_SUPPORT
10517 static void FAST_FUNC
10518 change_random(const char *value)
10522 if (value == NULL) {
10523 /* "get", generate */
10524 t = next_random(&random_gen);
10525 /* set without recursion */
10526 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10527 vrandom.flags &= ~VNOFUNC;
10530 t = strtoul(value, NULL, 10);
10531 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10536 #if ENABLE_ASH_GETOPTS
10538 getopts(char *optstr, char *optvar, char **optfirst)
10545 int ind = shellparam.optind;
10546 int off = shellparam.optoff;
10550 shellparam.optind = -1;
10551 optnext = optfirst + ind - 1;
10553 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10556 p = optnext[-1] + off;
10557 if (p == NULL || *p == '\0') {
10558 /* Current word is done, advance */
10560 if (p == NULL || *p != '-' || *++p == '\0') {
10567 if (LONE_DASH(p)) /* check for "--" */
10572 for (q = optstr; *q != c;) {
10574 if (optstr[0] == ':') {
10576 /*sbuf[1] = '\0'; - already is */
10577 setvar0("OPTARG", sbuf);
10579 fprintf(stderr, "Illegal option -%c\n", c);
10580 unsetvar("OPTARG");
10590 if (*p == '\0' && (p = *optnext) == NULL) {
10591 if (optstr[0] == ':') {
10593 /*sbuf[1] = '\0'; - already is */
10594 setvar0("OPTARG", sbuf);
10597 fprintf(stderr, "No arg for -%c option\n", c);
10598 unsetvar("OPTARG");
10606 setvar0("OPTARG", p);
10609 setvar0("OPTARG", nullstr);
10611 ind = optnext - optfirst + 1;
10612 setvar("OPTIND", itoa(ind), VNOFUNC);
10614 /*sbuf[1] = '\0'; - already is */
10615 setvar0(optvar, sbuf);
10617 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10618 shellparam.optind = ind;
10624 * The getopts builtin. Shellparam.optnext points to the next argument
10625 * to be processed. Shellparam.optptr points to the next character to
10626 * be processed in the current argument. If shellparam.optnext is NULL,
10627 * then it's the first time getopts has been called.
10629 static int FAST_FUNC
10630 getoptscmd(int argc, char **argv)
10635 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10637 optbase = shellparam.p;
10638 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10639 shellparam.optind = 1;
10640 shellparam.optoff = -1;
10643 optbase = &argv[3];
10644 if ((unsigned)shellparam.optind > argc - 2) {
10645 shellparam.optind = 1;
10646 shellparam.optoff = -1;
10650 return getopts(argv[1], argv[2], optbase);
10652 #endif /* ASH_GETOPTS */
10655 /* ============ Shell parser */
10658 struct heredoc *next; /* next here document in list */
10659 union node *here; /* redirection node */
10660 char *eofmark; /* string indicating end of input */
10661 smallint striptabs; /* if set, strip leading tabs */
10664 static smallint tokpushback; /* last token pushed back */
10665 static smallint quoteflag; /* set if (part of) last token was quoted */
10666 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10667 static struct heredoc *heredoclist; /* list of here documents to read */
10668 static char *wordtext; /* text of last word returned by readtoken */
10669 static struct nodelist *backquotelist;
10670 static union node *redirnode;
10671 static struct heredoc *heredoc;
10673 static const char *
10674 tokname(char *buf, int tok)
10677 return tokname_array[tok];
10678 sprintf(buf, "\"%s\"", tokname_array[tok]);
10682 /* raise_error_unexpected_syntax:
10683 * Called when an unexpected token is read during the parse. The argument
10684 * is the token that is expected, or -1 if more than one type of token can
10685 * occur at this point.
10687 static void raise_error_unexpected_syntax(int) NORETURN;
10689 raise_error_unexpected_syntax(int token)
10695 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10697 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10698 raise_error_syntax(msg);
10702 #define EOFMARKLEN 79
10704 /* parsing is heavily cross-recursive, need these forward decls */
10705 static union node *andor(void);
10706 static union node *pipeline(void);
10707 static union node *parse_command(void);
10708 static void parseheredoc(void);
10709 static int peektoken(void);
10710 static int readtoken(void);
10712 static union node *
10715 union node *n1, *n2, *n3;
10720 switch (peektoken()) {
10728 if (!n1 && (nlflag & 1))
10734 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10735 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10741 if (tok == TBACKGND) {
10742 if (n2->type == NPIPE) {
10743 n2->npipe.pipe_backgnd = 1;
10745 if (n2->type != NREDIR) {
10746 n3 = stzalloc(sizeof(struct nredir));
10748 /*n3->nredir.redirect = NULL; - stzalloc did it */
10751 n2->type = NBACKGND;
10757 n3 = stzalloc(sizeof(struct nbinary));
10759 n3->nbinary.ch1 = n1;
10760 n3->nbinary.ch2 = n2;
10773 raise_error_unexpected_syntax(-1);
10780 static union node *
10783 union node *n1, *n2, *n3;
10791 } else if (t == TOR) {
10797 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10799 n3 = stzalloc(sizeof(struct nbinary));
10801 n3->nbinary.ch1 = n1;
10802 n3->nbinary.ch2 = n2;
10807 static union node *
10810 union node *n1, *n2, *pipenode;
10811 struct nodelist *lp, *prev;
10815 TRACE(("pipeline: entered\n"));
10816 if (readtoken() == TNOT) {
10818 checkkwd = CHKKWD | CHKALIAS;
10821 n1 = parse_command();
10822 if (readtoken() == TPIPE) {
10823 pipenode = stzalloc(sizeof(struct npipe));
10824 pipenode->type = NPIPE;
10825 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10826 lp = stzalloc(sizeof(struct nodelist));
10827 pipenode->npipe.cmdlist = lp;
10831 lp = stzalloc(sizeof(struct nodelist));
10832 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10833 lp->n = parse_command();
10835 } while (readtoken() == TPIPE);
10841 n2 = stzalloc(sizeof(struct nnot));
10849 static union node *
10854 n = stzalloc(sizeof(struct narg));
10856 /*n->narg.next = NULL; - stzalloc did it */
10857 n->narg.text = wordtext;
10858 n->narg.backquote = backquotelist;
10863 fixredir(union node *n, const char *text, int err)
10867 TRACE(("Fix redir %s %d\n", text, err));
10869 n->ndup.vname = NULL;
10871 fd = bb_strtou(text, NULL, 10);
10872 if (!errno && fd >= 0)
10873 n->ndup.dupfd = fd;
10874 else if (LONE_DASH(text))
10875 n->ndup.dupfd = -1;
10878 raise_error_syntax("bad fd number");
10879 n->ndup.vname = makename();
10884 * Returns true if the text contains nothing to expand (no dollar signs
10888 noexpand(const char *text)
10892 while ((c = *text++) != '\0') {
10893 if (c == CTLQUOTEMARK)
10897 else if (SIT(c, BASESYNTAX) == CCTL)
10906 union node *n = redirnode;
10908 if (readtoken() != TWORD)
10909 raise_error_unexpected_syntax(-1);
10910 if (n->type == NHERE) {
10911 struct heredoc *here = heredoc;
10915 if (quoteflag == 0)
10917 TRACE(("Here document %d\n", n->type));
10918 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10919 raise_error_syntax("illegal eof marker for << redirection");
10920 rmescapes(wordtext, 0);
10921 here->eofmark = wordtext;
10923 if (heredoclist == NULL)
10924 heredoclist = here;
10926 for (p = heredoclist; p->next; p = p->next)
10930 } else if (n->type == NTOFD || n->type == NFROMFD) {
10931 fixredir(n, wordtext, 0);
10933 n->nfile.fname = makename();
10937 static union node *
10940 union node *args, **app;
10941 union node *n = NULL;
10942 union node *vars, **vpp;
10943 union node **rpp, *redir;
10945 #if ENABLE_ASH_BASH_COMPAT
10946 smallint double_brackets_flag = 0;
10947 smallint function_flag = 0;
10957 savecheckkwd = CHKALIAS;
10960 checkkwd = savecheckkwd;
10963 #if ENABLE_ASH_BASH_COMPAT
10965 if (peektoken() != TWORD)
10966 raise_error_unexpected_syntax(TWORD);
10969 case TAND: /* "&&" */
10970 case TOR: /* "||" */
10971 if (!double_brackets_flag) {
10975 wordtext = (char *) (t == TAND ? "-a" : "-o");
10978 n = stzalloc(sizeof(struct narg));
10980 /*n->narg.next = NULL; - stzalloc did it */
10981 n->narg.text = wordtext;
10982 #if ENABLE_ASH_BASH_COMPAT
10983 if (strcmp("[[", wordtext) == 0)
10984 double_brackets_flag = 1;
10985 else if (strcmp("]]", wordtext) == 0)
10986 double_brackets_flag = 0;
10988 n->narg.backquote = backquotelist;
10989 if (savecheckkwd && isassignment(wordtext)) {
10991 vpp = &n->narg.next;
10994 app = &n->narg.next;
10997 #if ENABLE_ASH_BASH_COMPAT
10998 if (function_flag) {
10999 checkkwd = CHKNL | CHKKWD;
11000 switch (peektoken()) {
11012 if (strcmp("[[", wordtext) == 0)
11016 raise_error_unexpected_syntax(-1);
11022 *rpp = n = redirnode;
11023 rpp = &n->nfile.next;
11024 parsefname(); /* read name of redirection file */
11027 IF_ASH_BASH_COMPAT(do_func:)
11028 if (args && app == &args->narg.next
11031 struct builtincmd *bcmd;
11034 /* We have a function */
11035 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11036 raise_error_unexpected_syntax(TRP);
11037 name = n->narg.text;
11038 if (!goodname(name)
11039 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11041 raise_error_syntax("bad function name");
11044 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11045 n->narg.next = parse_command();
11048 IF_ASH_BASH_COMPAT(function_flag = 0;)
11059 n = stzalloc(sizeof(struct ncmd));
11061 n->ncmd.args = args;
11062 n->ncmd.assign = vars;
11063 n->ncmd.redirect = redir;
11067 static union node *
11068 parse_command(void)
11070 union node *n1, *n2;
11071 union node *ap, **app;
11072 union node *cp, **cpp;
11073 union node *redir, **rpp;
11080 switch (readtoken()) {
11082 raise_error_unexpected_syntax(-1);
11085 n1 = stzalloc(sizeof(struct nif));
11087 n1->nif.test = list(0);
11088 if (readtoken() != TTHEN)
11089 raise_error_unexpected_syntax(TTHEN);
11090 n1->nif.ifpart = list(0);
11092 while (readtoken() == TELIF) {
11093 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11094 n2 = n2->nif.elsepart;
11096 n2->nif.test = list(0);
11097 if (readtoken() != TTHEN)
11098 raise_error_unexpected_syntax(TTHEN);
11099 n2->nif.ifpart = list(0);
11101 if (lasttoken == TELSE)
11102 n2->nif.elsepart = list(0);
11104 n2->nif.elsepart = NULL;
11112 n1 = stzalloc(sizeof(struct nbinary));
11113 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11114 n1->nbinary.ch1 = list(0);
11117 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11118 got == TWORD ? wordtext : ""));
11119 raise_error_unexpected_syntax(TDO);
11121 n1->nbinary.ch2 = list(0);
11126 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11127 raise_error_syntax("bad for loop variable");
11128 n1 = stzalloc(sizeof(struct nfor));
11130 n1->nfor.var = wordtext;
11131 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11132 if (readtoken() == TIN) {
11134 while (readtoken() == TWORD) {
11135 n2 = stzalloc(sizeof(struct narg));
11137 /*n2->narg.next = NULL; - stzalloc did it */
11138 n2->narg.text = wordtext;
11139 n2->narg.backquote = backquotelist;
11141 app = &n2->narg.next;
11144 n1->nfor.args = ap;
11145 if (lasttoken != TNL && lasttoken != TSEMI)
11146 raise_error_unexpected_syntax(-1);
11148 n2 = stzalloc(sizeof(struct narg));
11150 /*n2->narg.next = NULL; - stzalloc did it */
11151 n2->narg.text = (char *)dolatstr;
11152 /*n2->narg.backquote = NULL;*/
11153 n1->nfor.args = n2;
11155 * Newline or semicolon here is optional (but note
11156 * that the original Bourne shell only allowed NL).
11158 if (lasttoken != TSEMI)
11161 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11162 if (readtoken() != TDO)
11163 raise_error_unexpected_syntax(TDO);
11164 n1->nfor.body = list(0);
11168 n1 = stzalloc(sizeof(struct ncase));
11170 if (readtoken() != TWORD)
11171 raise_error_unexpected_syntax(TWORD);
11172 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11174 /*n2->narg.next = NULL; - stzalloc did it */
11175 n2->narg.text = wordtext;
11176 n2->narg.backquote = backquotelist;
11177 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11178 if (readtoken() != TIN)
11179 raise_error_unexpected_syntax(TIN);
11180 cpp = &n1->ncase.cases;
11182 checkkwd = CHKNL | CHKKWD;
11184 while (t != TESAC) {
11185 if (lasttoken == TLP)
11187 *cpp = cp = stzalloc(sizeof(struct nclist));
11189 app = &cp->nclist.pattern;
11191 *app = ap = stzalloc(sizeof(struct narg));
11193 /*ap->narg.next = NULL; - stzalloc did it */
11194 ap->narg.text = wordtext;
11195 ap->narg.backquote = backquotelist;
11196 if (readtoken() != TPIPE)
11198 app = &ap->narg.next;
11201 //ap->narg.next = NULL;
11202 if (lasttoken != TRP)
11203 raise_error_unexpected_syntax(TRP);
11204 cp->nclist.body = list(2);
11206 cpp = &cp->nclist.next;
11208 checkkwd = CHKNL | CHKKWD;
11212 raise_error_unexpected_syntax(TENDCASE);
11219 n1 = stzalloc(sizeof(struct nredir));
11220 n1->type = NSUBSHELL;
11221 n1->nredir.n = list(0);
11222 /*n1->nredir.redirect = NULL; - stzalloc did it */
11229 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11233 return simplecmd();
11236 if (readtoken() != t)
11237 raise_error_unexpected_syntax(t);
11240 /* Now check for redirection which may follow command */
11241 checkkwd = CHKKWD | CHKALIAS;
11243 while (readtoken() == TREDIR) {
11244 *rpp = n2 = redirnode;
11245 rpp = &n2->nfile.next;
11251 if (n1->type != NSUBSHELL) {
11252 n2 = stzalloc(sizeof(struct nredir));
11257 n1->nredir.redirect = redir;
11262 #if ENABLE_ASH_BASH_COMPAT
11264 decode_dollar_squote(void)
11266 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11272 p = strchr(C_escapes, c);
11277 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11281 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11283 } else if (c == 'x') { /* \xHH */
11287 } while (isxdigit(c) && --cnt);
11289 if (cnt == 3) { /* \x but next char is "bad" */
11293 } else { /* simple seq like \\ or \t */
11298 c = bb_process_escape_sequence((void*)&p);
11299 } else { /* unrecognized "\z": print both chars unless ' or " */
11300 if (c != '\'' && c != '"') {
11302 c |= 0x100; /* "please encode \, then me" */
11310 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11311 * is not NULL, read a here document. In the latter case, eofmark is the
11312 * word which marks the end of the document and striptabs is true if
11313 * leading tabs should be stripped from the document. The argument c
11314 * is the first character of the input token or document.
11316 * Because C does not have internal subroutines, I have simulated them
11317 * using goto's to implement the subroutine linkage. The following macros
11318 * will run code that appears at the end of readtoken1.
11320 #define CHECKEND() {goto checkend; checkend_return:;}
11321 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11322 #define PARSESUB() {goto parsesub; parsesub_return:;}
11323 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11324 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11325 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11327 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11329 /* NB: syntax parameter fits into smallint */
11330 /* c parameter is an unsigned char or PEOF or PEOA */
11333 char line[EOFMARKLEN + 1];
11334 struct nodelist *bqlist;
11338 smallint prevsyntax; /* syntax before arithmetic */
11339 #if ENABLE_ASH_EXPAND_PRMT
11340 smallint pssyntax; /* we are expanding a prompt string */
11342 int varnest; /* levels of variables expansion */
11343 int arinest; /* levels of arithmetic expansion */
11344 int parenlevel; /* levels of parens in arithmetic */
11345 int dqvarnest; /* levels of variables expansion within double quotes */
11347 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11349 startlinno = g_parsefile->linno;
11353 #if ENABLE_ASH_EXPAND_PRMT
11354 pssyntax = (syntax == PSSYNTAX);
11358 dblquote = (syntax == DQSYNTAX);
11364 STARTSTACKSTR(out);
11366 /* For each line, until end of word */
11367 CHECKEND(); /* set c to PEOF if at end of here document */
11368 for (;;) { /* until end of line or end of word */
11369 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11370 switch (SIT(c, syntax)) {
11371 case CNL: /* '\n' */
11372 if (syntax == BASESYNTAX)
11373 goto endword; /* exit outer loop */
11377 goto loop; /* continue outer loop */
11382 #if ENABLE_ASH_BASH_COMPAT
11383 if (c == '\\' && bash_dollar_squote) {
11384 c = decode_dollar_squote();
11386 /* skip $'\000', $'\x00' (like bash) */
11390 /* Unknown escape. Encode as '\z' */
11391 c = (unsigned char)c;
11392 if (eofmark == NULL || dblquote)
11393 USTPUTC(CTLESC, out);
11394 USTPUTC('\\', out);
11398 if (eofmark == NULL || dblquote)
11399 USTPUTC(CTLESC, out);
11402 case CBACK: /* backslash */
11403 c = pgetc_without_PEOA();
11405 USTPUTC(CTLESC, out);
11406 USTPUTC('\\', out);
11408 } else if (c == '\n') {
11411 #if ENABLE_ASH_EXPAND_PRMT
11412 if (c == '$' && pssyntax) {
11413 USTPUTC(CTLESC, out);
11414 USTPUTC('\\', out);
11417 /* Backslash is retained if we are in "str" and next char isn't special */
11422 && (c != '"' || eofmark != NULL)
11424 USTPUTC('\\', out);
11426 USTPUTC(CTLESC, out);
11434 if (eofmark == NULL) {
11435 USTPUTC(CTLQUOTEMARK, out);
11443 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11444 if (eofmark != NULL && varnest == 0) {
11447 if (dqvarnest == 0) {
11448 syntax = BASESYNTAX;
11455 case CVAR: /* '$' */
11456 PARSESUB(); /* parse substitution */
11458 case CENDVAR: /* '}' */
11461 if (dqvarnest > 0) {
11468 #if ENABLE_SH_MATH_SUPPORT
11469 case CLP: /* '(' in arithmetic */
11473 case CRP: /* ')' in arithmetic */
11474 if (parenlevel > 0) {
11477 if (pgetc_eatbnl() == ')') {
11479 if (--arinest == 0) {
11480 syntax = prevsyntax;
11484 * unbalanced parens
11485 * (don't 2nd guess - no error)
11493 case CBQUOTE: /* '`' */
11497 goto endword; /* exit outer loop */
11501 if (varnest == 0) {
11502 #if ENABLE_ASH_BASH_COMPAT
11504 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11505 if (pgetc() == '>')
11506 c = 0x100 + '>'; /* flag &> */
11510 goto endword; /* exit outer loop */
11512 IF_ASH_ALIAS(if (c != PEOA))
11519 #if ENABLE_SH_MATH_SUPPORT
11520 if (syntax == ARISYNTAX)
11521 raise_error_syntax("missing '))'");
11523 if (syntax != BASESYNTAX && eofmark == NULL)
11524 raise_error_syntax("unterminated quoted string");
11525 if (varnest != 0) {
11526 startlinno = g_parsefile->linno;
11528 raise_error_syntax("missing '}'");
11530 USTPUTC('\0', out);
11531 len = out - (char *)stackblock();
11532 out = stackblock();
11533 if (eofmark == NULL) {
11534 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11537 if (isdigit_str9(out)) {
11538 PARSEREDIR(); /* passed as params: out, c */
11539 lasttoken = TREDIR;
11542 /* else: non-number X seen, interpret it
11543 * as "NNNX>file" = "NNNX >file" */
11547 quoteflag = quotef;
11548 backquotelist = bqlist;
11549 grabstackblock(len);
11553 /* end of readtoken routine */
11556 * Check to see whether we are at the end of the here document. When this
11557 * is called, c is set to the first character of the next input line. If
11558 * we are at the end of the here document, this routine sets the c to PEOF.
11562 #if ENABLE_ASH_ALIAS
11564 c = pgetc_without_PEOA();
11567 while (c == '\t') {
11568 c = pgetc_without_PEOA();
11571 if (c == *eofmark) {
11572 if (pfgets(line, sizeof(line)) != NULL) {
11577 for (q = eofmark + 1;; p++, q++) {
11581 if (!*q || cc != *q)
11588 pushstring(line, NULL);
11593 goto checkend_return;
11597 * Parse a redirection operator. The variable "out" points to a string
11598 * specifying the fd to be redirected. The variable "c" contains the
11599 * first character of the redirection operator.
11602 /* out is already checked to be a valid number or "" */
11603 int fd = (*out == '\0' ? -1 : atoi(out));
11606 np = stzalloc(sizeof(struct nfile));
11611 np->type = NAPPEND;
11613 np->type = NCLOBBER;
11616 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11622 #if ENABLE_ASH_BASH_COMPAT
11623 else if (c == 0x100 + '>') { /* this flags &> redirection */
11625 pgetc(); /* this is '>', no need to check */
11629 else { /* c == '<' */
11630 /*np->nfile.fd = 0; - stzalloc did it */
11634 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11635 np = stzalloc(sizeof(struct nhere));
11636 /*np->nfile.fd = 0; - stzalloc did it */
11639 heredoc = stzalloc(sizeof(struct heredoc));
11640 heredoc->here = np;
11643 heredoc->striptabs = 1;
11645 /*heredoc->striptabs = 0; - stzalloc did it */
11651 np->type = NFROMFD;
11655 np->type = NFROMTO;
11667 goto parseredir_return;
11671 * Parse a substitution. At this point, we have read the dollar sign
11672 * and nothing else.
11675 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11676 * (assuming ascii char codes, as the original implementation did) */
11677 #define is_special(c) \
11678 (((unsigned)(c) - 33 < 32) \
11679 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11681 unsigned char subtype;
11684 c = pgetc_eatbnl();
11685 if (c > 255 /* PEOA or PEOF */
11686 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11688 #if ENABLE_ASH_BASH_COMPAT
11689 if (syntax != DQSYNTAX && c == '\'')
11690 bash_dollar_squote = 1;
11695 } else if (c == '(') {
11696 /* $(command) or $((arith)) */
11697 if (pgetc_eatbnl() == '(') {
11698 #if ENABLE_SH_MATH_SUPPORT
11701 raise_error_syntax("you disabled math support for $((arith)) syntax");
11708 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11709 USTPUTC(CTLVAR, out);
11710 typeloc = out - (char *)stackblock();
11712 subtype = VSNORMAL;
11714 c = pgetc_eatbnl();
11719 /* $[{[#]]NAME[}] */
11722 c = pgetc_eatbnl();
11723 } while (is_in_name(c));
11724 } else if (isdigit(c)) {
11725 /* $[{[#]]NUM[}] */
11728 c = pgetc_eatbnl();
11729 } while (isdigit(c));
11730 } else if (is_special(c)) {
11731 /* $[{[#]]<specialchar>[}] */
11734 c = pgetc_eatbnl();
11735 if (!subtype && cc == '#') {
11736 subtype = VSLENGTH;
11737 if (c == '_' || isalnum(c))
11740 c = pgetc_eatbnl();
11741 if (cc == '}' || c != '}') {
11752 if (c != '}' && subtype == VSLENGTH) {
11753 /* ${#VAR didn't end with } */
11757 if (subtype == 0) {
11758 static const char types[] ALIGN1 = "}-+?=";
11759 /* ${VAR...} but not $VAR or ${#VAR} */
11760 /* c == first char after VAR */
11763 c = pgetc_eatbnl();
11764 #if ENABLE_ASH_BASH_COMPAT
11765 /* This check is only needed to not misinterpret
11766 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11769 if (!strchr(types, c)) {
11770 subtype = VSSUBSTR;
11772 break; /* "goto badsub" is bigger (!) */
11778 const char *p = strchr(types, c);
11781 subtype |= p - types + VSNORMAL;
11787 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11788 c = pgetc_eatbnl();
11794 #if ENABLE_ASH_BASH_COMPAT
11796 /* ${v/[/]pattern/repl} */
11797 //TODO: encode pattern and repl separately.
11798 // Currently ${v/$var_with_slash/repl} is horribly broken
11799 subtype = VSREPLACE;
11800 c = pgetc_eatbnl();
11803 subtype++; /* VSREPLACEALL */
11811 ((unsigned char *)stackblock())[typeloc] = subtype;
11812 if (subtype != VSNORMAL) {
11819 goto parsesub_return;
11823 * Called to parse command substitutions. Newstyle is set if the command
11824 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11825 * list of commands (passed by reference), and savelen is the number of
11826 * characters on the top of the stack which must be preserved.
11829 struct nodelist **nlpp;
11833 smallint saveprompt = 0;
11836 savelen = out - (char *)stackblock();
11839 * FIXME: this can allocate very large block on stack and SEGV.
11841 * echo "..<100kbytes>..`true` $(true) `true` ..."
11842 * allocates 100kb for every command subst. With about
11843 * a hundred command substitutions stack overflows.
11844 * With larger prepended string, SEGV happens sooner.
11846 str = alloca(savelen);
11847 memcpy(str, stackblock(), savelen);
11851 /* We must read until the closing backquote, giving special
11852 * treatment to some slashes, and then push the string and
11853 * reread it as input, interpreting it normally.
11859 STARTSTACKSTR(pout);
11863 setprompt_if(needprompt, 2);
11874 * If eating a newline, avoid putting
11875 * the newline into the new character
11876 * stream (via the STPUTC after the
11881 if (pc != '\\' && pc != '`' && pc != '$'
11882 && (!dblquote || pc != '"')
11884 STPUTC('\\', pout);
11886 if (pc <= 255 /* not PEOA or PEOF */) {
11892 IF_ASH_ALIAS(case PEOA:)
11893 startlinno = g_parsefile->linno;
11894 raise_error_syntax("EOF in backquote substitution");
11906 STPUTC('\0', pout);
11907 psavelen = pout - (char *)stackblock();
11908 if (psavelen > 0) {
11909 pstr = grabstackstr(pout);
11910 setinputstring(pstr);
11915 nlpp = &(*nlpp)->next;
11916 *nlpp = stzalloc(sizeof(**nlpp));
11917 /* (*nlpp)->next = NULL; - stzalloc did it */
11920 saveprompt = doprompt;
11927 doprompt = saveprompt;
11928 else if (readtoken() != TRP)
11929 raise_error_unexpected_syntax(TRP);
11934 * Start reading from old file again, ignoring any pushed back
11935 * tokens left from the backquote parsing
11940 while (stackblocksize() <= savelen)
11942 STARTSTACKSTR(out);
11944 memcpy(out, str, savelen);
11945 STADJUST(savelen, out);
11947 USTPUTC(CTLBACKQ, out);
11949 goto parsebackq_oldreturn;
11950 goto parsebackq_newreturn;
11953 #if ENABLE_SH_MATH_SUPPORT
11955 * Parse an arithmetic expansion (indicate start of one and set state)
11958 if (++arinest == 1) {
11959 prevsyntax = syntax;
11960 syntax = ARISYNTAX;
11962 USTPUTC(CTLARI, out);
11963 goto parsearith_return;
11966 } /* end of readtoken */
11969 * Read the next input token.
11970 * If the token is a word, we set backquotelist to the list of cmds in
11971 * backquotes. We set quoteflag to true if any part of the word was
11973 * If the token is TREDIR, then we set redirnode to a structure containing
11975 * In all cases, the variable startlinno is set to the number of the line
11976 * on which the token starts.
11978 * [Change comment: here documents and internal procedures]
11979 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11980 * word parsing code into a separate routine. In this case, readtoken
11981 * doesn't need to have any internal procedures, but parseword does.
11982 * We could also make parseoperator in essence the main routine, and
11983 * have parseword (readtoken1?) handle both words and redirection.]
11985 #define NEW_xxreadtoken
11986 #ifdef NEW_xxreadtoken
11987 /* singles must be first! */
11988 static const char xxreadtoken_chars[7] ALIGN1 = {
11989 '\n', '(', ')', /* singles */
11990 '&', '|', ';', /* doubles */
11994 #define xxreadtoken_singles 3
11995 #define xxreadtoken_doubles 3
11997 static const char xxreadtoken_tokens[] ALIGN1 = {
11998 TNL, TLP, TRP, /* only single occurrence allowed */
11999 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12000 TEOF, /* corresponds to trailing nul */
12001 TAND, TOR, TENDCASE /* if double occurrence */
12013 setprompt_if(needprompt, 2);
12014 startlinno = g_parsefile->linno;
12015 for (;;) { /* until token or start of word found */
12017 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12021 while ((c = pgetc()) != '\n' && c != PEOF)
12024 } else if (c == '\\') {
12025 if (pgetc() != '\n') {
12027 break; /* return readtoken1(...) */
12033 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12039 p = strchr(xxreadtoken_chars, c);
12041 break; /* return readtoken1(...) */
12043 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12045 if (cc == c) { /* double occurrence? */
12046 p += xxreadtoken_doubles + 1;
12049 #if ENABLE_ASH_BASH_COMPAT
12050 if (c == '&' && cc == '>') /* &> */
12051 break; /* return readtoken1(...) */
12056 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12061 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12063 #else /* old xxreadtoken */
12064 #define RETURN(token) return lasttoken = token
12074 setprompt_if(needprompt, 2);
12075 startlinno = g_parsefile->linno;
12076 for (;;) { /* until token or start of word found */
12079 case ' ': case '\t':
12080 IF_ASH_ALIAS(case PEOA:)
12083 while ((c = pgetc()) != '\n' && c != PEOF)
12088 if (pgetc() == '\n') {
12100 if (pgetc() == '&')
12105 if (pgetc() == '|')
12110 if (pgetc() == ';')
12123 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12126 #endif /* old xxreadtoken */
12132 int kwd = checkkwd;
12134 smallint alreadyseen = tokpushback;
12137 #if ENABLE_ASH_ALIAS
12153 if (t != TWORD || quoteflag) {
12158 * check for keywords
12160 if (kwd & CHKKWD) {
12161 const char *const *pp;
12163 pp = findkwd(wordtext);
12165 lasttoken = t = pp - tokname_array;
12166 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12171 if (checkkwd & CHKALIAS) {
12172 #if ENABLE_ASH_ALIAS
12174 ap = lookupalias(wordtext, 1);
12177 pushstring(ap->val, ap);
12187 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12189 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12205 * Read and parse a command. Returns NODE_EOF on end of file.
12206 * (NULL is a valid parse tree indicating a blank line.)
12208 static union node *
12209 parsecmd(int interact)
12214 doprompt = interact;
12215 setprompt_if(doprompt, doprompt);
12221 * Input any here documents.
12226 struct heredoc *here;
12229 here = heredoclist;
12230 heredoclist = NULL;
12233 setprompt_if(needprompt, 2);
12234 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12235 here->eofmark, here->striptabs);
12236 n = stzalloc(sizeof(struct narg));
12237 n->narg.type = NARG;
12238 /*n->narg.next = NULL; - stzalloc did it */
12239 n->narg.text = wordtext;
12240 n->narg.backquote = backquotelist;
12241 here->here->nhere.doc = n;
12248 * called by editline -- any expansions to the prompt should be added here.
12250 #if ENABLE_ASH_EXPAND_PRMT
12251 static const char *
12252 expandstr(const char *ps)
12257 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12258 * and token processing _can_ alter it (delete NULs etc). */
12259 setinputstring((char *)ps);
12261 saveprompt = doprompt;
12263 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12264 doprompt = saveprompt;
12268 n.narg.type = NARG;
12269 n.narg.next = NULL;
12270 n.narg.text = wordtext;
12271 n.narg.backquote = backquotelist;
12273 expandarg(&n, NULL, EXP_QUOTED);
12274 return stackblock();
12279 * Execute a command or commands contained in a string.
12282 evalstring(char *s, int flags)
12284 struct jmploc *volatile savehandler = exception_handler;
12285 struct jmploc jmploc;
12289 struct stackmark smark;
12294 setstackmark(&smark);
12297 /* On exception inside execution loop, we must popfile().
12298 * Try interactively:
12300 * command eval "a=b" # throws "is read only" error
12301 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12302 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12304 savehandler = exception_handler;
12305 exception_handler = &jmploc;
12306 ex = setjmp(jmploc.loc);
12310 while ((n = parsecmd(0)) != NODE_EOF) {
12313 i = evaltree(n, flags);
12316 popstackmark(&smark);
12321 popstackmark(&smark);
12325 exception_handler = savehandler;
12327 longjmp(exception_handler->loc, ex);
12333 * The eval command.
12335 static int FAST_FUNC
12336 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12345 STARTSTACKSTR(concat);
12347 concat = stack_putstr(p, concat);
12351 STPUTC(' ', concat);
12353 STPUTC('\0', concat);
12354 p = grabstackstr(concat);
12356 return evalstring(p, flags & EV_TESTED);
12362 * Read and execute commands.
12363 * "Top" is nonzero for the top level command loop;
12364 * it turns on prompting if the shell is interactive.
12370 struct stackmark smark;
12375 TRACE(("cmdloop(%d) called\n", top));
12379 setstackmark(&smark);
12382 showjobs(SHOW_CHANGED|SHOW_STDERR);
12385 if (iflag && top) {
12389 n = parsecmd(inter);
12391 if (DEBUG > 2 && debug && (n != NODE_EOF))
12394 if (n == NODE_EOF) {
12395 if (!top || numeof >= 50)
12397 if (!stoppedjobs()) {
12400 out2str("\nUse \"exit\" to leave shell.\n");
12403 } else if (nflag == 0) {
12406 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12409 i = evaltree(n, 0);
12413 popstackmark(&smark);
12417 evalskip &= ~SKIPFUNC;
12425 * Take commands from a file. To be compatible we should do a path
12426 * search for the file, which is necessary to find sub-commands.
12429 find_dot_file(char *name)
12432 const char *path = pathval();
12435 /* don't try this for absolute or relative paths */
12436 if (strchr(name, '/'))
12439 /* IIRC standards do not say whether . is to be searched.
12440 * And it is even smaller this way, making it unconditional for now:
12442 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12447 while ((fullname = path_advance(&path, name)) != NULL) {
12449 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12451 * Don't bother freeing here, since it will
12452 * be freed by the caller.
12456 if (fullname != name)
12457 stunalloc(fullname);
12460 /* not found in the PATH */
12461 ash_msg_and_raise_error("%s: not found", name);
12465 static int FAST_FUNC
12466 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12468 /* "false; . empty_file; echo $?" should print 0, not 1: */
12472 struct strlist *sp;
12473 volatile struct shparam saveparam;
12475 for (sp = cmdenviron; sp; sp = sp->next)
12476 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12478 nextopt(nullstr); /* handle possible "--" */
12482 /* bash says: "bash: .: filename argument required" */
12483 return 2; /* bash compat */
12486 /* This aborts if file isn't found, which is POSIXly correct.
12487 * bash returns exitcode 1 instead.
12489 fullname = find_dot_file(argv[0]);
12491 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12493 saveparam = shellparam;
12494 shellparam.malloced = 0;
12498 shellparam.nparam = argc;
12499 shellparam.p = argv;
12502 /* This aborts if file can't be opened, which is POSIXly correct.
12503 * bash returns exitcode 1 instead.
12505 setinputfile(fullname, INPUT_PUSH_FILE);
12506 commandname = fullname;
12507 status = cmdloop(0);
12511 freeparam(&shellparam);
12512 shellparam = saveparam;
12518 static int FAST_FUNC
12519 exitcmd(int argc UNUSED_PARAM, char **argv)
12524 exitstatus = number(argv[1]);
12525 raise_exception(EXEXIT);
12530 * Read a file containing shell functions.
12533 readcmdfile(char *name)
12535 setinputfile(name, INPUT_PUSH_FILE);
12541 /* ============ find_command inplementation */
12544 * Resolve a command name. If you change this routine, you may have to
12545 * change the shellexec routine as well.
12548 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12550 struct tblentry *cmdp;
12557 struct builtincmd *bcmd;
12559 /* If name contains a slash, don't use PATH or hash table */
12560 if (strchr(name, '/') != NULL) {
12561 entry->u.index = -1;
12562 if (act & DO_ABS) {
12563 while (stat(name, &statb) < 0) {
12565 if (errno == EINTR)
12568 entry->cmdtype = CMDUNKNOWN;
12572 entry->cmdtype = CMDNORMAL;
12576 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12578 updatetbl = (path == pathval());
12581 if (strstr(path, "%builtin") != NULL)
12582 act |= DO_ALTBLTIN;
12585 /* If name is in the table, check answer will be ok */
12586 cmdp = cmdlookup(name, 0);
12587 if (cmdp != NULL) {
12590 switch (cmdp->cmdtype) {
12608 } else if (cmdp->rehash == 0)
12609 /* if not invalidated by cd, we're done */
12613 /* If %builtin not in path, check for builtin next */
12614 bcmd = find_builtin(name);
12616 if (IS_BUILTIN_REGULAR(bcmd))
12617 goto builtin_success;
12618 if (act & DO_ALTPATH) {
12619 if (!(act & DO_ALTBLTIN))
12620 goto builtin_success;
12621 } else if (builtinloc <= 0) {
12622 goto builtin_success;
12626 #if ENABLE_FEATURE_SH_STANDALONE
12628 int applet_no = find_applet_by_name(name);
12629 if (applet_no >= 0) {
12630 entry->cmdtype = CMDNORMAL;
12631 entry->u.index = -2 - applet_no;
12637 /* We have to search path. */
12638 prev = -1; /* where to start */
12639 if (cmdp && cmdp->rehash) { /* doing a rehash */
12640 if (cmdp->cmdtype == CMDBUILTIN)
12643 prev = cmdp->param.index;
12649 while ((fullname = path_advance(&path, name)) != NULL) {
12650 stunalloc(fullname);
12651 /* NB: code below will still use fullname
12652 * despite it being "unallocated" */
12655 if (prefix(pathopt, "builtin")) {
12657 goto builtin_success;
12660 if ((act & DO_NOFUNC)
12661 || !prefix(pathopt, "func")
12662 ) { /* ignore unimplemented options */
12666 /* if rehash, don't redo absolute path names */
12667 if (fullname[0] == '/' && idx <= prev) {
12670 TRACE(("searchexec \"%s\": no change\n", name));
12673 while (stat(fullname, &statb) < 0) {
12675 if (errno == EINTR)
12678 if (errno != ENOENT && errno != ENOTDIR)
12682 e = EACCES; /* if we fail, this will be the error */
12683 if (!S_ISREG(statb.st_mode))
12685 if (pathopt) { /* this is a %func directory */
12686 stalloc(strlen(fullname) + 1);
12687 /* NB: stalloc will return space pointed by fullname
12688 * (because we don't have any intervening allocations
12689 * between stunalloc above and this stalloc) */
12690 readcmdfile(fullname);
12691 cmdp = cmdlookup(name, 0);
12692 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12693 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12694 stunalloc(fullname);
12697 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12699 entry->cmdtype = CMDNORMAL;
12700 entry->u.index = idx;
12704 cmdp = cmdlookup(name, 1);
12705 cmdp->cmdtype = CMDNORMAL;
12706 cmdp->param.index = idx;
12711 /* We failed. If there was an entry for this command, delete it */
12712 if (cmdp && updatetbl)
12713 delete_cmd_entry();
12715 ash_msg("%s: %s", name, errmsg(e, "not found"));
12716 entry->cmdtype = CMDUNKNOWN;
12721 entry->cmdtype = CMDBUILTIN;
12722 entry->u.cmd = bcmd;
12726 cmdp = cmdlookup(name, 1);
12727 cmdp->cmdtype = CMDBUILTIN;
12728 cmdp->param.cmd = bcmd;
12732 entry->cmdtype = cmdp->cmdtype;
12733 entry->u = cmdp->param;
12738 * The trap builtin.
12740 static int FAST_FUNC
12741 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12745 int signo, exitcode;
12750 for (signo = 0; signo < NSIG; signo++) {
12751 char *tr = trap_ptr[signo];
12753 /* note: bash adds "SIG", but only if invoked
12754 * as "bash". If called as "sh", or if set -o posix,
12755 * then it prints short signal names.
12756 * We are printing short names: */
12757 out1fmt("trap -- %s %s\n",
12759 get_signame(signo));
12760 /* trap_ptr != trap only if we are in special-cased `trap` code.
12761 * In this case, we will exit very soon, no need to free(). */
12762 /* if (trap_ptr != trap && tp[0]) */
12767 if (trap_ptr != trap) {
12780 signo = get_signum(*ap);
12782 /* Mimic bash message exactly */
12783 ash_msg("%s: invalid signal specification", *ap);
12789 if (LONE_DASH(action))
12792 if (action[0]) /* not NULL and not "" and not "-" */
12793 may_have_traps = 1;
12794 action = ckstrdup(action);
12798 trap[signo] = action;
12809 /* ============ Builtins */
12811 #if ENABLE_ASH_HELP
12812 static int FAST_FUNC
12813 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12819 "Built-in commands:\n"
12820 "------------------\n");
12821 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12822 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12823 builtintab[i].name + 1);
12829 # if ENABLE_FEATURE_SH_STANDALONE
12831 const char *a = applet_names;
12833 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12838 while (*a++ != '\0')
12843 newline_and_flush(stdout);
12844 return EXIT_SUCCESS;
12849 static int FAST_FUNC
12850 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12852 show_history(line_input_state);
12853 return EXIT_SUCCESS;
12858 * The export and readonly commands.
12860 static int FAST_FUNC
12861 exportcmd(int argc UNUSED_PARAM, char **argv)
12871 /* "readonly" in bash accepts, but ignores -n.
12872 * We do the same: it saves a conditional in nextopt's param.
12875 while ((opt = nextopt("np")) != '\0') {
12877 flag_off = VEXPORT;
12880 if (argv[0][0] == 'r') {
12882 flag_off = 0; /* readonly ignores -n */
12884 flag_off = ~flag_off;
12886 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12892 p = strchr(name, '=');
12896 vp = *findvar(hashvar(name), name);
12898 vp->flags = ((vp->flags | flag) & flag_off);
12902 setvar(name, p, (flag & flag_off));
12903 } while ((name = *++aptr) != NULL);
12908 /* No arguments. Show the list of exported or readonly vars.
12911 showvars(argv[0], flag, 0);
12916 * Delete a function if it exists.
12919 unsetfunc(const char *name)
12921 struct tblentry *cmdp;
12923 cmdp = cmdlookup(name, 0);
12924 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12925 delete_cmd_entry();
12929 * The unset builtin command. We unset the function before we unset the
12930 * variable to allow a function to be unset when there is a readonly variable
12931 * with the same name.
12933 static int FAST_FUNC
12934 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12941 while ((i = nextopt("vf")) != 0) {
12945 for (ap = argptr; *ap; ap++) {
12958 static const unsigned char timescmd_str[] ALIGN1 = {
12959 ' ', offsetof(struct tms, tms_utime),
12960 '\n', offsetof(struct tms, tms_stime),
12961 ' ', offsetof(struct tms, tms_cutime),
12962 '\n', offsetof(struct tms, tms_cstime),
12965 static int FAST_FUNC
12966 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12968 unsigned long clk_tck, s, t;
12969 const unsigned char *p;
12972 clk_tck = bb_clk_tck();
12977 t = *(clock_t *)(((char *) &buf) + p[1]);
12980 out1fmt("%lum%lu.%03lus%c",
12982 (t * 1000) / clk_tck,
12990 #if ENABLE_SH_MATH_SUPPORT
12992 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12993 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12995 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12997 static int FAST_FUNC
12998 letcmd(int argc UNUSED_PARAM, char **argv)
13004 ash_msg_and_raise_error("expression expected");
13006 i = ash_arith(*argv);
13014 * The read builtin. Options:
13015 * -r Do not interpret '\' specially
13016 * -s Turn off echo (tty only)
13017 * -n NCHARS Read NCHARS max
13018 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13019 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13020 * -u FD Read from given FD instead of fd 0
13021 * This uses unbuffered input, which may be avoidable in some cases.
13022 * TODO: bash also has:
13023 * -a ARRAY Read into array[0],[1],etc
13024 * -d DELIM End on DELIM char, not newline
13025 * -e Use line editing (tty only)
13027 static int FAST_FUNC
13028 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13030 char *opt_n = NULL;
13031 char *opt_p = NULL;
13032 char *opt_t = NULL;
13033 char *opt_u = NULL;
13034 int read_flags = 0;
13038 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13047 read_flags |= BUILTIN_READ_SILENT;
13053 read_flags |= BUILTIN_READ_RAW;
13063 /* "read -s" needs to save/restore termios, can't allow ^C
13064 * to jump out of it.
13067 r = shell_builtin_read(setvar0,
13069 bltinlookup("IFS"), /* can be NULL */
13078 if ((uintptr_t)r > 1)
13079 ash_msg_and_raise_error(r);
13081 return (uintptr_t)r;
13084 static int FAST_FUNC
13085 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13087 static const char permuser[3] ALIGN1 = "ogu";
13090 int symbolic_mode = 0;
13092 while (nextopt("S") != '\0') {
13101 if (*argptr == NULL) {
13102 if (symbolic_mode) {
13103 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13110 *p++ = permuser[i];
13112 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13113 if (!(mask & 0400)) *p++ = 'r';
13114 if (!(mask & 0200)) *p++ = 'w';
13115 if (!(mask & 0100)) *p++ = 'x';
13123 out1fmt("%04o\n", mask);
13126 char *modestr = *argptr;
13127 /* numeric umasks are taken as-is */
13128 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13129 if (!isdigit(modestr[0]))
13131 mask = bb_parse_mode(modestr, mask);
13132 if ((unsigned)mask > 0777) {
13133 ash_msg_and_raise_error("illegal mode: %s", modestr);
13135 if (!isdigit(modestr[0]))
13142 static int FAST_FUNC
13143 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13145 return shell_builtin_ulimit(argv);
13148 /* ============ main() and helpers */
13151 * Called to exit the shell.
13160 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13161 save_history(line_input_state);
13163 status = exitstatus;
13164 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13165 if (setjmp(loc.loc)) {
13166 if (exception_type == EXEXIT)
13167 status = exitstatus;
13170 exception_handler = &loc;
13176 /*free(p); - we'll exit soon */
13179 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13180 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13183 flush_stdout_stderr();
13191 /* we will never free this */
13192 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13194 sigmode[SIGCHLD - 1] = S_DFL;
13195 setsignal(SIGCHLD);
13197 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13198 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13200 signal(SIGHUP, SIG_DFL);
13205 struct stat st1, st2;
13208 for (envp = environ; envp && *envp; envp++) {
13209 p = endofname(*envp);
13210 if (p != *envp && *p == '=') {
13211 setvareq(*envp, VEXPORT|VTEXTFIXED);
13215 setvareq((char*)defoptindvar, VTEXTFIXED);
13217 setvar0("PPID", utoa(getppid()));
13218 #if ENABLE_ASH_BASH_COMPAT
13219 p = lookupvar("SHLVL");
13220 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13221 if (!lookupvar("HOSTNAME")) {
13222 struct utsname uts;
13224 setvar0("HOSTNAME", uts.nodename);
13227 p = lookupvar("PWD");
13229 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13230 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13240 //usage:#define ash_trivial_usage
13241 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13242 //usage:#define ash_full_usage "\n\n"
13243 //usage: "Unix shell interpreter"
13245 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13246 //usage:# define sh_trivial_usage ash_trivial_usage
13247 //usage:# define sh_full_usage ash_full_usage
13249 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13250 //usage:# define bash_trivial_usage ash_trivial_usage
13251 //usage:# define bash_full_usage ash_full_usage
13255 * Process the shell command line arguments.
13258 procargs(char **argv)
13261 const char *xminusc;
13266 /* if (xargv[0]) - mmm, this is always true! */
13268 for (i = 0; i < NOPTS; i++)
13271 if (options(/*cmdline:*/ 1)) {
13272 /* it already printed err message */
13273 raise_exception(EXERROR);
13277 if (*xargv == NULL) {
13279 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13282 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13286 for (i = 0; i < NOPTS; i++)
13287 if (optlist[i] == 2)
13292 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13297 } else if (!sflag) {
13298 setinputfile(*xargv, 0);
13301 commandname = arg0;
13304 shellparam.p = xargv;
13305 #if ENABLE_ASH_GETOPTS
13306 shellparam.optind = 1;
13307 shellparam.optoff = -1;
13309 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13311 shellparam.nparam++;
13318 * Read /etc/profile, ~/.profile, $ENV.
13321 read_profile(const char *name)
13323 name = expandstr(name);
13324 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13331 * This routine is called when an error or an interrupt occurs in an
13332 * interactive shell and control is returned to the main command loop.
13333 * (In dash, this function is auto-generated by build machinery).
13342 /* from expand.c: */
13345 /* from input.c: */
13346 g_parsefile->left_in_buffer = 0;
13347 g_parsefile->left_in_line = 0; /* clear input buffer */
13350 /* from redir.c: */
13352 popredir(/*drop:*/ 0, /*restore:*/ 0);
13356 static short profile_buf[16384];
13357 extern int etext();
13361 * Main routine. We initialize things, parse the arguments, execute
13362 * profiles if we're a login shell, and then call cmdloop to execute
13363 * commands. The setjmp call sets up the location to jump to when an
13364 * exception occurs. When an exception occurs the variable "state"
13365 * is used to figure out how far we had gotten.
13367 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13368 int ash_main(int argc UNUSED_PARAM, char **argv)
13370 volatile smallint state;
13371 struct jmploc jmploc;
13372 struct stackmark smark;
13374 /* Initialize global data */
13378 #if ENABLE_ASH_ALIAS
13384 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13387 #if ENABLE_FEATURE_EDITING
13388 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13391 if (setjmp(jmploc.loc)) {
13397 e = exception_type;
13399 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13403 newline_and_flush(stderr);
13406 popstackmark(&smark);
13407 FORCE_INT_ON; /* enable interrupts */
13416 exception_handler = &jmploc;
13419 TRACE(("Shell args: "));
13420 trace_puts_args(argv);
13422 rootpid = getpid();
13425 setstackmark(&smark);
13428 if (argv[0] && argv[0][0] == '-')
13434 read_profile("/etc/profile");
13437 hp = lookupvar("HOME");
13439 read_profile("$HOME/.profile");
13445 getuid() == geteuid() && getgid() == getegid() &&
13449 const char *shinit = lookupvar("ENV");
13450 if (shinit != NULL && *shinit != '\0')
13451 read_profile(shinit);
13453 popstackmark(&smark);
13457 /* evalstring pushes parsefile stack.
13458 * Ensure we don't falsely claim that 0 (stdin)
13459 * is one of stacked source fds.
13460 * Testcase: ash -c 'exec 1>&0' must not complain. */
13461 // if (!sflag) g_parsefile->pf_fd = -1;
13462 // ^^ not necessary since now we special-case fd 0
13463 // in is_hidden_fd() to not be considered "hidden fd"
13464 evalstring(minusc, 0);
13467 if (sflag || minusc == NULL) {
13468 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13470 const char *hp = lookupvar("HISTFILE");
13472 hp = lookupvar("HOME");
13474 hp = concat_path_file(hp, ".ash_history");
13475 setvar0("HISTFILE", hp);
13477 hp = lookupvar("HISTFILE");
13481 line_input_state->hist_file = hp;
13482 # if ENABLE_FEATURE_SH_HISTFILESIZE
13483 hp = lookupvar("HISTFILESIZE");
13484 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13488 state4: /* XXX ??? - why isn't this before the "if" statement */
13496 extern void _mcleanup(void);
13500 TRACE(("End of main reached\n"));
13507 * Copyright (c) 1989, 1991, 1993, 1994
13508 * The Regents of the University of California. All rights reserved.
13510 * This code is derived from software contributed to Berkeley by
13511 * Kenneth Almquist.
13513 * Redistribution and use in source and binary forms, with or without
13514 * modification, are permitted provided that the following conditions
13516 * 1. Redistributions of source code must retain the above copyright
13517 * notice, this list of conditions and the following disclaimer.
13518 * 2. Redistributions in binary form must reproduce the above copyright
13519 * notice, this list of conditions and the following disclaimer in the
13520 * documentation and/or other materials provided with the distribution.
13521 * 3. Neither the name of the University nor the names of its contributors
13522 * may be used to endorse or promote products derived from this software
13523 * without specific prior written permission.
13525 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13526 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13527 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13528 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13529 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13530 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13531 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13532 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13533 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13534 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF