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)
2183 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2189 if (vp->var_func && !(flags & VNOFUNC))
2190 vp->var_func(var_end(s));
2192 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2193 free((char*)vp->var_text);
2195 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2197 /* variable s is not found */
2200 vp = ckzalloc(sizeof(*vp));
2202 /*vp->func = NULL; - ckzalloc did it */
2205 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2212 * Set the value of a variable. The flags argument is ored with the
2213 * flags of the variable. If val is NULL, the variable is unset.
2216 setvar(const char *name, const char *val, int flags)
2224 q = endofname(name);
2225 p = strchrnul(q, '=');
2227 if (!namelen || p != q)
2228 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2233 vallen = strlen(val);
2237 nameeq = ckmalloc(namelen + vallen + 2);
2238 p = memcpy(nameeq, name, namelen) + namelen;
2241 p = memcpy(p, val, vallen) + vallen;
2244 setvareq(nameeq, flags | VNOSAVE);
2248 static void FAST_FUNC
2249 setvar0(const char *name, const char *val)
2251 setvar(name, val, 0);
2255 * Unset the specified variable.
2258 unsetvar(const char *s)
2264 vpp = findvar(hashvar(s), s);
2268 int flags = vp->flags;
2271 if (flags & VREADONLY)
2273 #if ENABLE_ASH_RANDOM_SUPPORT
2274 vp->flags &= ~VDYNAMIC;
2278 if ((flags & VSTRFIXED) == 0) {
2280 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2281 free((char*)vp->var_text);
2287 vp->flags &= ~VEXPORT;
2297 * Process a linked list of variable assignments.
2300 listsetvar(struct strlist *list_set_var, int flags)
2302 struct strlist *lp = list_set_var;
2308 setvareq(lp->text, flags);
2315 * Generate a list of variables satisfying the given conditions.
2318 listvars(int on, int off, char ***end)
2329 for (vp = *vpp; vp; vp = vp->next) {
2330 if ((vp->flags & mask) == on) {
2331 if (ep == stackstrend())
2332 ep = growstackstr();
2333 *ep++ = (char*)vp->var_text;
2336 } while (++vpp < vartab + VTABSIZE);
2337 if (ep == stackstrend())
2338 ep = growstackstr();
2342 return grabstackstr(ep);
2346 /* ============ Path search helper
2348 * The variable path (passed by reference) should be set to the start
2349 * of the path before the first call; path_advance will update
2350 * this value as it proceeds. Successive calls to path_advance will return
2351 * the possible path expansions in sequence. If an option (indicated by
2352 * a percent sign) appears in the path entry then the global variable
2353 * pathopt will be set to point to it; otherwise pathopt will be set to
2356 static const char *pathopt; /* set by path_advance */
2359 path_advance(const char **path, const char *name)
2369 for (p = start; *p && *p != ':' && *p != '%'; p++)
2371 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2372 while (stackblocksize() < len)
2376 memcpy(q, start, p - start);
2384 while (*p && *p != ':')
2391 return stalloc(len);
2395 /* ============ Prompt */
2397 static smallint doprompt; /* if set, prompt the user */
2398 static smallint needprompt; /* true if interactive and at start of line */
2400 #if ENABLE_FEATURE_EDITING
2401 static line_input_t *line_input_state;
2402 static const char *cmdedit_prompt;
2404 putprompt(const char *s)
2406 if (ENABLE_ASH_EXPAND_PRMT) {
2407 free((char*)cmdedit_prompt);
2408 cmdedit_prompt = ckstrdup(s);
2415 putprompt(const char *s)
2421 #if ENABLE_ASH_EXPAND_PRMT
2422 /* expandstr() needs parsing machinery, so it is far away ahead... */
2423 static const char *expandstr(const char *ps);
2425 #define expandstr(s) s
2429 setprompt_if(smallint do_set, int whichprompt)
2432 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2439 switch (whichprompt) {
2449 #if ENABLE_ASH_EXPAND_PRMT
2450 pushstackmark(&smark, stackblocksize());
2452 putprompt(expandstr(prompt));
2453 #if ENABLE_ASH_EXPAND_PRMT
2454 popstackmark(&smark);
2459 /* ============ The cd and pwd commands */
2461 #define CD_PHYSICAL 1
2471 while ((i = nextopt("LP")) != '\0') {
2473 flags ^= CD_PHYSICAL;
2482 * Update curdir (the name of the current directory) in response to a
2486 updatepwd(const char *dir)
2493 cdcomppath = sstrdup(dir);
2496 if (curdir == nullstr)
2498 new = stack_putstr(curdir, new);
2500 new = makestrspace(strlen(dir) + 2, new);
2501 lim = (char *)stackblock() + 1;
2505 if (new > lim && *lim == '/')
2510 if (dir[1] == '/' && dir[2] != '/') {
2516 p = strtok(cdcomppath, "/");
2520 if (p[1] == '.' && p[2] == '\0') {
2532 new = stack_putstr(p, new);
2535 p = strtok(NULL, "/");
2540 return stackblock();
2544 * Find out what the current directory is. If we already know the current
2545 * directory, this routine returns immediately.
2550 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2551 return dir ? dir : nullstr;
2555 setpwd(const char *val, int setold)
2559 oldcur = dir = curdir;
2562 setvar("OLDPWD", oldcur, VEXPORT);
2565 if (physdir != nullstr) {
2566 if (physdir != oldcur)
2570 if (oldcur == val || !val) {
2576 dir = ckstrdup(val);
2577 if (oldcur != dir && oldcur != nullstr) {
2582 setvar("PWD", dir, VEXPORT);
2585 static void hashcd(void);
2588 * Actually do the chdir. We also call hashcd to let other routines
2589 * know that the current directory has changed.
2592 docd(const char *dest, int flags)
2594 const char *dir = NULL;
2597 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2600 if (!(flags & CD_PHYSICAL)) {
2601 dir = updatepwd(dest);
2615 static int FAST_FUNC
2616 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2628 dest = bltinlookup("HOME");
2629 else if (LONE_DASH(dest)) {
2630 dest = bltinlookup("OLDPWD");
2652 path = bltinlookup("CDPATH");
2655 p = path_advance(&path, dest);
2656 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2660 if (!docd(p, flags))
2671 ash_msg_and_raise_error("can't cd to %s", dest);
2674 if (flags & CD_PRINT)
2675 out1fmt("%s\n", curdir);
2679 static int FAST_FUNC
2680 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2683 const char *dir = curdir;
2687 if (physdir == nullstr)
2691 out1fmt("%s\n", dir);
2696 /* ============ ... */
2699 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2701 /* Syntax classes */
2702 #define CWORD 0 /* character is nothing special */
2703 #define CNL 1 /* newline character */
2704 #define CBACK 2 /* a backslash character */
2705 #define CSQUOTE 3 /* single quote */
2706 #define CDQUOTE 4 /* double quote */
2707 #define CENDQUOTE 5 /* a terminating quote */
2708 #define CBQUOTE 6 /* backwards single quote */
2709 #define CVAR 7 /* a dollar sign */
2710 #define CENDVAR 8 /* a '}' character */
2711 #define CLP 9 /* a left paren in arithmetic */
2712 #define CRP 10 /* a right paren in arithmetic */
2713 #define CENDFILE 11 /* end of file */
2714 #define CCTL 12 /* like CWORD, except it must be escaped */
2715 #define CSPCL 13 /* these terminate a word */
2716 #define CIGN 14 /* character should be ignored */
2719 #if ENABLE_ASH_ALIAS
2723 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2725 #if ENABLE_SH_MATH_SUPPORT
2726 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2728 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2730 static const uint16_t S_I_T[] ALIGN2 = {
2731 #if ENABLE_ASH_ALIAS
2732 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2734 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2735 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2736 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2737 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2738 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2739 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2740 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2741 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2742 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2743 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2744 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2745 #if !USE_SIT_FUNCTION
2746 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2747 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2748 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2752 /* Constants below must match table above */
2754 #if ENABLE_ASH_ALIAS
2755 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2757 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2758 CNL_CNL_CNL_CNL , /* 2 */
2759 CWORD_CCTL_CCTL_CWORD , /* 3 */
2760 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2761 CVAR_CVAR_CWORD_CVAR , /* 5 */
2762 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2763 CSPCL_CWORD_CWORD_CLP , /* 7 */
2764 CSPCL_CWORD_CWORD_CRP , /* 8 */
2765 CBACK_CBACK_CCTL_CBACK , /* 9 */
2766 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2767 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2768 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2769 CWORD_CWORD_CWORD_CWORD , /* 13 */
2770 CCTL_CCTL_CCTL_CCTL , /* 14 */
2773 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2774 * caller must ensure proper cast on it if c is *char_ptr!
2776 /* Values for syntax param */
2777 #define BASESYNTAX 0 /* not in quotes */
2778 #define DQSYNTAX 1 /* in double quotes */
2779 #define SQSYNTAX 2 /* in single quotes */
2780 #define ARISYNTAX 3 /* in arithmetic */
2781 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2783 #if USE_SIT_FUNCTION
2786 SIT(int c, int syntax)
2788 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2789 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2791 * This causes '/' to be prepended with CTLESC in dquoted string,
2792 * making "./file"* treated incorrectly because we feed
2793 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2794 * The "homegrown" glob implementation is okay with that,
2795 * but glibc one isn't. With '/' always treated as CWORD,
2798 # if ENABLE_ASH_ALIAS
2799 static const uint8_t syntax_index_table[] ALIGN1 = {
2800 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2801 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2802 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2806 static const uint8_t syntax_index_table[] ALIGN1 = {
2807 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2808 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2809 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2818 # if ENABLE_ASH_ALIAS
2824 /* Cast is purely for paranoia here,
2825 * just in case someone passed signed char to us */
2826 if ((unsigned char)c >= CTL_FIRST
2827 && (unsigned char)c <= CTL_LAST
2831 s = strchrnul(spec_symbls, c);
2834 indx = syntax_index_table[s - spec_symbls];
2836 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2839 #else /* !USE_SIT_FUNCTION */
2841 static const uint8_t syntax_index_table[] ALIGN1 = {
2842 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2843 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2854 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2876 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2877 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2878 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2879 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2880 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2881 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2882 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2883 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2884 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2885 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2886 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2888 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2889 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2890 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2891 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2899 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2901 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2903 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2904 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2905 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2906 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2907 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2936 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2937 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2941 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2969 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2970 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2971 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2972 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2974 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2975 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2976 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2977 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2978 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2979 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2980 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2981 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3100 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3101 # if ENABLE_ASH_ALIAS
3102 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3106 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3108 #endif /* !USE_SIT_FUNCTION */
3111 /* ============ Alias handling */
3113 #if ENABLE_ASH_ALIAS
3115 #define ALIASINUSE 1
3126 static struct alias **atab; // [ATABSIZE];
3127 #define INIT_G_alias() do { \
3128 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3132 static struct alias **
3133 __lookupalias(const char *name)
3135 unsigned int hashval;
3142 ch = (unsigned char)*p;
3146 ch = (unsigned char)*++p;
3148 app = &atab[hashval % ATABSIZE];
3150 for (; *app; app = &(*app)->next) {
3151 if (strcmp(name, (*app)->name) == 0) {
3159 static struct alias *
3160 lookupalias(const char *name, int check)
3162 struct alias *ap = *__lookupalias(name);
3164 if (check && ap && (ap->flag & ALIASINUSE))
3169 static struct alias *
3170 freealias(struct alias *ap)
3174 if (ap->flag & ALIASINUSE) {
3175 ap->flag |= ALIASDEAD;
3187 setalias(const char *name, const char *val)
3189 struct alias *ap, **app;
3191 app = __lookupalias(name);
3195 if (!(ap->flag & ALIASINUSE)) {
3198 ap->val = ckstrdup(val);
3199 ap->flag &= ~ALIASDEAD;
3202 ap = ckzalloc(sizeof(struct alias));
3203 ap->name = ckstrdup(name);
3204 ap->val = ckstrdup(val);
3205 /*ap->flag = 0; - ckzalloc did it */
3206 /*ap->next = NULL;*/
3213 unalias(const char *name)
3217 app = __lookupalias(name);
3221 *app = freealias(*app);
3232 struct alias *ap, **app;
3236 for (i = 0; i < ATABSIZE; i++) {
3238 for (ap = *app; ap; ap = *app) {
3239 *app = freealias(*app);
3249 printalias(const struct alias *ap)
3251 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3255 * TODO - sort output
3257 static int FAST_FUNC
3258 aliascmd(int argc UNUSED_PARAM, char **argv)
3267 for (i = 0; i < ATABSIZE; i++) {
3268 for (ap = atab[i]; ap; ap = ap->next) {
3274 while ((n = *++argv) != NULL) {
3275 v = strchr(n+1, '=');
3276 if (v == NULL) { /* n+1: funny ksh stuff */
3277 ap = *__lookupalias(n);
3279 fprintf(stderr, "%s: %s not found\n", "alias", n);
3292 static int FAST_FUNC
3293 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3297 while ((i = nextopt("a")) != '\0') {
3303 for (i = 0; *argptr; argptr++) {
3304 if (unalias(*argptr)) {
3305 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3313 #endif /* ASH_ALIAS */
3316 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3319 #define FORK_NOJOB 2
3321 /* mode flags for showjob(s) */
3322 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3323 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3324 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3325 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3328 * A job structure contains information about a job. A job is either a
3329 * single process or a set of processes contained in a pipeline. In the
3330 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3334 pid_t ps_pid; /* process id */
3335 int ps_status; /* last process status from wait() */
3336 char *ps_cmd; /* text of command being run */
3340 struct procstat ps0; /* status of process */
3341 struct procstat *ps; /* status or processes when more than one */
3343 int stopstatus; /* status of a stopped job */
3346 nprocs: 16, /* number of processes */
3348 #define JOBRUNNING 0 /* at least one proc running */
3349 #define JOBSTOPPED 1 /* all procs are stopped */
3350 #define JOBDONE 2 /* all procs are completed */
3352 sigint: 1, /* job was killed by SIGINT */
3353 jobctl: 1, /* job running under job control */
3355 waited: 1, /* true if this entry has been waited for */
3356 used: 1, /* true if this entry is in used */
3357 changed: 1; /* true if status has changed */
3358 struct job *prev_job; /* previous job */
3361 static struct job *makejob(/*union node *,*/ int);
3362 static int forkshell(struct job *, union node *, int);
3363 static int waitforjob(struct job *);
3366 enum { doing_jobctl = 0 };
3367 #define setjobctl(on) do {} while (0)
3369 static smallint doing_jobctl; //references:8
3370 static void setjobctl(int);
3377 ignoresig(int signo)
3379 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3380 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3381 /* No, need to do it */
3382 signal(signo, SIG_IGN);
3384 sigmode[signo - 1] = S_HARD_IGN;
3388 * Only one usage site - in setsignal()
3391 signal_handler(int signo)
3393 if (signo == SIGCHLD) {
3399 gotsig[signo - 1] = 1;
3400 pending_sig = signo;
3402 if (signo == SIGINT && !trap[SIGINT]) {
3403 if (!suppress_int) {
3405 raise_interrupt(); /* does not return */
3412 * Set the signal handler for the specified signal. The routine figures
3413 * out what it should be set to.
3416 setsignal(int signo)
3419 char cur_act, new_act;
3420 struct sigaction act;
3424 if (t != NULL) { /* trap for this sig is set */
3426 if (t[0] == '\0') /* trap is "": ignore this sig */
3430 if (rootshell && new_act == S_DFL) {
3433 if (iflag || minusc || sflag == 0)
3442 * "In all cases, bash ignores SIGQUIT. Non-builtin
3443 * commands run by bash have signal handlers
3444 * set to the values inherited by the shell
3445 * from its parent". */
3461 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3462 //whereas we have to restore it to what shell got on entry
3463 //from the parent. See comment above
3465 if (signo == SIGCHLD)
3468 t = &sigmode[signo - 1];
3471 /* current setting is not yet known */
3472 if (sigaction(signo, NULL, &act)) {
3473 /* pretend it worked; maybe we should give a warning,
3474 * but other shells don't. We don't alter sigmode,
3475 * so we retry every time.
3476 * btw, in Linux it never fails. --vda */
3479 if (act.sa_handler == SIG_IGN) {
3480 cur_act = S_HARD_IGN;
3482 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3484 cur_act = S_IGN; /* don't hard ignore these */
3488 if (cur_act == S_HARD_IGN || cur_act == new_act)
3491 act.sa_handler = SIG_DFL;
3494 act.sa_handler = signal_handler;
3497 act.sa_handler = SIG_IGN;
3501 /* flags and mask matter only if !DFL and !IGN, but we do it
3502 * for all cases for more deterministic behavior:
3505 sigfillset(&act.sa_mask);
3507 sigaction_set(signo, &act);
3512 /* mode flags for set_curjob */
3513 #define CUR_DELETE 2
3514 #define CUR_RUNNING 1
3515 #define CUR_STOPPED 0
3517 /* mode flags for dowait */
3518 #define DOWAIT_NONBLOCK 0
3519 #define DOWAIT_BLOCK 1
3520 #define DOWAIT_BLOCK_OR_SIG 2
3523 /* pgrp of shell on invocation */
3524 static int initialpgrp; //references:2
3525 static int ttyfd = -1; //5
3528 static struct job *jobtab; //5
3530 static unsigned njobs; //4
3532 static struct job *curjob; //lots
3533 /* number of presumed living untracked jobs */
3534 static int jobless; //4
3537 set_curjob(struct job *jp, unsigned mode)
3540 struct job **jpp, **curp;
3542 /* first remove from list */
3543 jpp = curp = &curjob;
3548 jpp = &jp1->prev_job;
3550 *jpp = jp1->prev_job;
3552 /* Then re-insert in correct position */
3560 /* job being deleted */
3563 /* newly created job or backgrounded job,
3564 * put after all stopped jobs.
3569 if (!jp1 || jp1->state != JOBSTOPPED)
3572 jpp = &jp1->prev_job;
3578 /* newly stopped job - becomes curjob */
3579 jp->prev_job = *jpp;
3587 jobno(const struct job *jp)
3589 return jp - jobtab + 1;
3594 * Convert a job name to a job structure.
3597 #define getjob(name, getctl) getjob(name)
3600 getjob(const char *name, int getctl)
3604 const char *err_msg = "%s: no such job";
3608 char *(*match)(const char *, const char *);
3623 if (c == '+' || c == '%') {
3625 err_msg = "No current job";
3631 err_msg = "No previous job";
3641 if (num > 0 && num <= njobs) {
3642 jp = jobtab + num - 1;
3657 if (match(jp->ps[0].ps_cmd, p)) {
3661 err_msg = "%s: ambiguous";
3671 err_msg = "job %s not created under job control";
3672 if (getctl && jp->jobctl == 0)
3677 ash_msg_and_raise_error(err_msg, name);
3681 * Mark a job structure as unused.
3684 freejob(struct job *jp)
3686 struct procstat *ps;
3690 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3691 if (ps->ps_cmd != nullstr)
3694 if (jp->ps != &jp->ps0)
3697 set_curjob(jp, CUR_DELETE);
3703 xtcsetpgrp(int fd, pid_t pgrp)
3705 if (tcsetpgrp(fd, pgrp))
3706 ash_msg_and_raise_error("can't set tty process group (%m)");
3710 * Turn job control on and off.
3712 * Note: This code assumes that the third arg to ioctl is a character
3713 * pointer, which is true on Berkeley systems but not System V. Since
3714 * System V doesn't have job control yet, this isn't a problem now.
3716 * Called with interrupts off.
3724 if (on == doing_jobctl || rootshell == 0)
3728 ofd = fd = open(_PATH_TTY, O_RDWR);
3730 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3731 * That sometimes helps to acquire controlling tty.
3732 * Obviously, a workaround for bugs when someone
3733 * failed to provide a controlling tty to bash! :) */
3739 /* fd is a tty at this point */
3740 fd = fcntl(fd, F_DUPFD, 10);
3741 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3744 goto out; /* F_DUPFD failed */
3745 close_on_exec_on(fd);
3746 while (1) { /* while we are in the background */
3747 pgrp = tcgetpgrp(fd);
3750 ash_msg("can't access tty; job control turned off");
3754 if (pgrp == getpgrp())
3765 xtcsetpgrp(fd, pgrp);
3767 /* turning job control off */
3770 /* was xtcsetpgrp, but this can make exiting ash
3771 * loop forever if pty is already deleted */
3772 tcsetpgrp(fd, pgrp);
3786 static int FAST_FUNC
3787 killcmd(int argc, char **argv)
3789 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3792 if (argv[i][0] == '%') {
3794 * "kill %N" - job kill
3795 * Converting to pgrp / pid kill
3801 jp = getjob(argv[i], 0);
3803 * In jobs started under job control, we signal
3804 * entire process group by kill -PGRP_ID.
3805 * This happens, f.e., in interactive shell.
3807 * Otherwise, we signal each child via
3808 * kill PID1 PID2 PID3.
3810 * sh -c 'sleep 1|sleep 1 & kill %1'
3811 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3812 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3814 n = jp->nprocs; /* can't be 0 (I hope) */
3817 dst = alloca(n * sizeof(int)*4);
3819 for (j = 0; j < n; j++) {
3820 struct procstat *ps = &jp->ps[j];
3821 /* Skip non-running and not-stopped members
3822 * (i.e. dead members) of the job
3824 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3827 * kill_main has matching code to expect
3828 * leading space. Needed to not confuse
3829 * negative pids with "kill -SIGNAL_NO" syntax
3831 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3835 } while (argv[++i]);
3837 return kill_main(argc, argv);
3841 showpipe(struct job *jp /*, FILE *out*/)
3843 struct procstat *ps;
3844 struct procstat *psend;
3846 psend = jp->ps + jp->nprocs;
3847 for (ps = jp->ps + 1; ps < psend; ps++)
3848 printf(" | %s", ps->ps_cmd);
3849 newline_and_flush(stdout);
3850 flush_stdout_stderr();
3855 restartjob(struct job *jp, int mode)
3857 struct procstat *ps;
3863 if (jp->state == JOBDONE)
3865 jp->state = JOBRUNNING;
3866 pgid = jp->ps[0].ps_pid;
3867 if (mode == FORK_FG)
3868 xtcsetpgrp(ttyfd, pgid);
3869 killpg(pgid, SIGCONT);
3873 if (WIFSTOPPED(ps->ps_status)) {
3879 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3884 static int FAST_FUNC
3885 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3891 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3895 jp = getjob(*argv, 1);
3896 if (mode == FORK_BG) {
3897 set_curjob(jp, CUR_RUNNING);
3898 printf("[%d] ", jobno(jp));
3900 out1str(jp->ps[0].ps_cmd);
3901 showpipe(jp /*, stdout*/);
3902 retval = restartjob(jp, mode);
3903 } while (*argv && *++argv);
3909 sprint_status48(char *s, int status, int sigonly)
3915 if (!WIFEXITED(status)) {
3916 if (JOBS && WIFSTOPPED(status))
3917 st = WSTOPSIG(status);
3919 st = WTERMSIG(status);
3921 if (st == SIGINT || st == SIGPIPE)
3923 if (JOBS && WIFSTOPPED(status))
3927 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3928 col = fmtstr(s, 32, strsignal(st));
3929 if (WCOREDUMP(status)) {
3930 strcpy(s + col, " (core dumped)");
3931 col += sizeof(" (core dumped)")-1;
3933 } else if (!sigonly) {
3934 st = WEXITSTATUS(status);
3935 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3942 wait_block_or_sig(int *status, int wait_flags)
3948 /* Poll all children for changes in their state */
3950 pid = waitpid(-1, status, wait_flags | WNOHANG);
3952 break; /* Error (e.g. EINTR) or pid */
3954 /* No child is ready. Sleep until interesting signal is received */
3956 sigprocmask(SIG_SETMASK, &mask, &mask);
3957 while (!got_sigchld && !pending_sig)
3959 sigprocmask(SIG_SETMASK, &mask, NULL);
3961 /* If it was SIGCHLD, poll children again */
3962 } while (got_sigchld);
3969 dowait(int block, struct job *job)
3975 struct job *thisjob = NULL;
3977 TRACE(("dowait(0x%x) called\n", block));
3980 if (block == DOWAIT_NONBLOCK)
3981 wait_flags = WNOHANG;
3982 /* If job control is compiled in, we accept stopped processes too. */
3984 wait_flags |= WUNTRACED;
3986 /* It's wrong to call waitpid() outside of INT_OFF region:
3987 * signal can arrive just after syscall return and handler can
3988 * longjmp away, losing stop/exit notification processing.
3989 * Thus, for "jobs" builtin, and for waiting for a fg job,
3990 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
3992 * However, for "wait" builtin it is wrong to simply call waitpid()
3993 * in INT_OFF region: "wait" needs to wait for any running job
3994 * to change state, but should exit on any trap too.
3995 * In INT_OFF region, a signal just before syscall entry can set
3996 * pending_sig valiables, but we can't check them, and we would
3997 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
3998 * Because of this, we run inside INT_OFF, but use a special routine
3999 * which combines waitpid() and sigsuspend().
4002 if (block == DOWAIT_BLOCK_OR_SIG)
4003 pid = wait_block_or_sig(&status, wait_flags);
4005 /* NB: _not_ safe_waitpid, we need to detect EINTR. */
4006 pid = waitpid(-1, &status, wait_flags);
4007 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4008 pid, status, errno, strerror(errno)));
4013 for (jp = curjob; jp; jp = jp->prev_job) {
4015 struct procstat *ps;
4016 struct procstat *psend;
4017 if (jp->state == JOBDONE)
4021 psend = ps + jp->nprocs;
4023 if (ps->ps_pid == pid) {
4024 TRACE(("Job %d: changing status of proc %d "
4025 "from 0x%x to 0x%x\n",
4026 jobno(jp), pid, ps->ps_status, status));
4027 ps->ps_status = status;
4030 if (ps->ps_status == -1)
4031 jobstate = JOBRUNNING;
4033 if (jobstate == JOBRUNNING)
4035 if (WIFSTOPPED(ps->ps_status)) {
4036 jp->stopstatus = ps->ps_status;
4037 jobstate = JOBSTOPPED;
4040 } while (++ps < psend);
4044 /* Found the job where one of its processes changed its state.
4045 * Is there at least one live and running process in this job? */
4046 if (jobstate != JOBRUNNING) {
4047 /* No. All live processes in the job are stopped
4048 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4050 thisjob->changed = 1;
4051 if (thisjob->state != jobstate) {
4052 TRACE(("Job %d: changing state from %d to %d\n",
4053 jobno(thisjob), thisjob->state, jobstate));
4054 thisjob->state = jobstate;
4056 if (jobstate == JOBSTOPPED)
4057 set_curjob(thisjob, CUR_STOPPED);
4063 /* The process wasn't found in job list */
4064 if (JOBS && !WIFSTOPPED(status))
4069 if (thisjob && thisjob == job) {
4073 len = sprint_status48(s, status, 1);
4085 showjob(struct job *jp, int mode)
4087 struct procstat *ps;
4088 struct procstat *psend;
4091 char s[16 + 16 + 48];
4092 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4096 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4097 /* just output process (group) id of pipeline */
4098 fprintf(out, "%d\n", ps->ps_pid);
4102 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4107 else if (curjob && jp == curjob->prev_job)
4110 if (mode & SHOW_PIDS)
4111 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4113 psend = ps + jp->nprocs;
4115 if (jp->state == JOBRUNNING) {
4116 strcpy(s + col, "Running");
4117 col += sizeof("Running") - 1;
4119 int status = psend[-1].ps_status;
4120 if (jp->state == JOBSTOPPED)
4121 status = jp->stopstatus;
4122 col += sprint_status48(s + col, status, 0);
4124 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4126 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4127 * or prints several "PID | <cmdN>" lines,
4128 * depending on SHOW_PIDS bit.
4129 * We do not print status of individual processes
4130 * between PID and <cmdN>. bash does it, but not very well:
4131 * first line shows overall job status, not process status,
4132 * making it impossible to know 1st process status.
4136 /* for each process */
4139 if (mode & SHOW_PIDS)
4140 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4142 fprintf(out, "%s%*c%s%s",
4144 33 - col >= 0 ? 33 - col : 0, ' ',
4145 ps == jp->ps ? "" : "| ",
4148 } while (++ps != psend);
4149 newline_and_flush(out);
4153 if (jp->state == JOBDONE) {
4154 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4160 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4161 * statuses have changed since the last call to showjobs.
4168 TRACE(("showjobs(0x%x) called\n", mode));
4170 /* Handle all finished jobs */
4171 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4174 for (jp = curjob; jp; jp = jp->prev_job) {
4175 if (!(mode & SHOW_CHANGED) || jp->changed) {
4181 static int FAST_FUNC
4182 jobscmd(int argc UNUSED_PARAM, char **argv)
4187 while ((m = nextopt("lp")) != '\0') {
4191 mode |= SHOW_ONLY_PGID;
4197 showjob(getjob(*argv, 0), mode);
4207 /* Called only on finished or stopped jobs (no members are running) */
4209 getstatus(struct job *job)
4213 struct procstat *ps;
4215 /* Fetch last member's status */
4216 ps = job->ps + job->nprocs - 1;
4217 status = ps->ps_status;
4219 /* "set -o pipefail" mode: use last _nonzero_ status */
4220 while (status == 0 && --ps >= job->ps)
4221 status = ps->ps_status;
4224 retval = WEXITSTATUS(status);
4225 if (!WIFEXITED(status)) {
4227 retval = WSTOPSIG(status);
4228 if (!WIFSTOPPED(status))
4231 /* XXX: limits number of signals */
4232 retval = WTERMSIG(status);
4234 if (retval == SIGINT)
4240 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4241 jobno(job), job->nprocs, status, retval));
4245 static int FAST_FUNC
4246 waitcmd(int argc UNUSED_PARAM, char **argv)
4257 /* wait for all jobs */
4261 if (!jp) /* no running procs */
4263 if (jp->state == JOBRUNNING)
4269 * "When bash is waiting for an asynchronous command via
4270 * the wait builtin, the reception of a signal for which a trap
4271 * has been set will cause the wait builtin to return immediately
4272 * with an exit status greater than 128, immediately after which
4273 * the trap is executed."
4275 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4276 /* if child sends us a signal *and immediately exits*,
4277 * dowait() returns pid > 0. Check this case,
4278 * not "if (dowait() < 0)"!
4287 if (**argv != '%') {
4288 pid_t pid = number(*argv);
4293 if (job->ps[job->nprocs - 1].ps_pid == pid)
4295 job = job->prev_job;
4298 job = getjob(*argv, 0);
4300 /* loop until process terminated or stopped */
4301 while (job->state == JOBRUNNING) {
4302 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4307 retval = getstatus(job);
4314 retval = 128 + pending_sig;
4323 struct job *jp, *jq;
4325 len = njobs * sizeof(*jp);
4327 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4329 offset = (char *)jp - (char *)jq;
4331 /* Relocate pointers */
4334 jq = (struct job *)((char *)jq + l);
4338 #define joff(p) ((struct job *)((char *)(p) + l))
4339 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4340 if (joff(jp)->ps == &jq->ps0)
4341 jmove(joff(jp)->ps);
4342 if (joff(jp)->prev_job)
4343 jmove(joff(jp)->prev_job);
4353 jp = (struct job *)((char *)jp + len);
4357 } while (--jq >= jp);
4362 * Return a new job structure.
4363 * Called with interrupts off.
4366 makejob(/*union node *node,*/ int nprocs)
4371 for (i = njobs, jp = jobtab; ; jp++) {
4378 if (jp->state != JOBDONE || !jp->waited)
4387 memset(jp, 0, sizeof(*jp));
4389 /* jp->jobctl is a bitfield.
4390 * "jp->jobctl |= jobctl" likely to give awful code */
4394 jp->prev_job = curjob;
4399 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4401 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4408 * Return a string identifying a command (to be printed by the
4411 static char *cmdnextc;
4414 cmdputs(const char *s)
4416 static const char vstype[VSTYPE + 1][3] = {
4417 "", "}", "-", "+", "?", "=",
4418 "%", "%%", "#", "##"
4419 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4422 const char *p, *str;
4426 unsigned char subtype = 0;
4430 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4432 while ((c = *p++) != '\0') {
4440 if ((subtype & VSTYPE) == VSLENGTH)
4446 str = "\"}" + !(quoted & 1);
4453 #if ENABLE_SH_MATH_SUPPORT
4468 if ((subtype & VSTYPE) != VSNORMAL)
4470 str = vstype[subtype & VSTYPE];
4471 if (subtype & VSNUL)
4480 /* These can only happen inside quotes */
4493 while ((c = *str++) != '\0') {
4496 } /* while *p++ not NUL */
4499 USTPUTC('"', nextc);
4505 /* cmdtxt() and cmdlist() call each other */
4506 static void cmdtxt(union node *n);
4509 cmdlist(union node *np, int sep)
4511 for (; np; np = np->narg.next) {
4515 if (sep && np->narg.next)
4521 cmdtxt(union node *n)
4524 struct nodelist *lp;
4535 lp = n->npipe.cmdlist;
4553 cmdtxt(n->nbinary.ch1);
4569 cmdtxt(n->nif.test);
4571 if (n->nif.elsepart) {
4572 cmdtxt(n->nif.ifpart);
4574 n = n->nif.elsepart;
4592 cmdtxt(n->nbinary.ch1);
4602 cmdputs(n->nfor.var);
4604 cmdlist(n->nfor.args, 1);
4609 cmdputs(n->narg.text);
4613 cmdlist(n->ncmd.args, 1);
4614 cmdlist(n->ncmd.redirect, 0);
4627 cmdputs(n->ncase.expr->narg.text);
4629 for (np = n->ncase.cases; np; np = np->nclist.next) {
4630 cmdtxt(np->nclist.pattern);
4632 cmdtxt(np->nclist.body);
4646 #if ENABLE_ASH_BASH_COMPAT
4661 cmdputs(utoa(n->nfile.fd));
4663 if (n->type == NTOFD || n->type == NFROMFD) {
4664 cmdputs(utoa(n->ndup.dupfd));
4673 commandtext(union node *n)
4677 STARTSTACKSTR(cmdnextc);
4679 name = stackblock();
4680 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4681 return ckstrdup(name);
4686 * Fork off a subshell. If we are doing job control, give the subshell its
4687 * own process group. Jp is a job structure that the job is to be added to.
4688 * N is the command that will be evaluated by the child. Both jp and n may
4689 * be NULL. The mode parameter can be one of the following:
4690 * FORK_FG - Fork off a foreground process.
4691 * FORK_BG - Fork off a background process.
4692 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4693 * process group even if job control is on.
4695 * When job control is turned off, background processes have their standard
4696 * input redirected to /dev/null (except for the second and later processes
4699 * Called with interrupts off.
4702 * Clear traps on a fork.
4710 for (tp = trap; tp < &trap[NSIG]; tp++) {
4711 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4712 if (trap_ptr == trap)
4714 /* else: it "belongs" to trap_ptr vector, don't free */
4716 if ((tp - trap) != 0)
4717 setsignal(tp - trap);
4724 /* Lives far away from here, needed for forkchild */
4725 static void closescript(void);
4727 /* Called after fork(), in child */
4728 /* jp and n are NULL when called by openhere() for heredoc support */
4729 static NOINLINE void
4730 forkchild(struct job *jp, union node *n, int mode)
4734 TRACE(("Child shell %d\n", getpid()));
4738 /* man bash: "Non-builtin commands run by bash have signal handlers
4739 * set to the values inherited by the shell from its parent".
4740 * Do we do it correctly? */
4744 if (mode == FORK_NOJOB /* is it `xxx` ? */
4745 && n && n->type == NCMD /* is it single cmd? */
4746 /* && n->ncmd.args->type == NARG - always true? */
4747 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4748 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4749 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4751 TRACE(("Trap hack\n"));
4752 /* Awful hack for `trap` or $(trap).
4754 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4755 * contains an example where "trap" is executed in a subshell:
4757 * save_traps=$(trap)
4759 * eval "$save_traps"
4761 * Standard does not say that "trap" in subshell shall print
4762 * parent shell's traps. It only says that its output
4763 * must have suitable form, but then, in the above example
4764 * (which is not supposed to be normative), it implies that.
4766 * bash (and probably other shell) does implement it
4767 * (traps are reset to defaults, but "trap" still shows them),
4768 * but as a result, "trap" logic is hopelessly messed up:
4771 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4772 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4773 * # true | trap <--- trap is in subshell - no output (ditto)
4774 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4775 * trap -- 'echo Ho' SIGWINCH
4776 * # echo `(trap)` <--- in subshell in subshell - output
4777 * trap -- 'echo Ho' SIGWINCH
4778 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4779 * trap -- 'echo Ho' SIGWINCH
4781 * The rules when to forget and when to not forget traps
4782 * get really complex and nonsensical.
4784 * Our solution: ONLY bare $(trap) or `trap` is special.
4786 /* Save trap handler strings for trap builtin to print */
4787 trap_ptr = xmemdup(trap, sizeof(trap));
4788 /* Fall through into clearing traps */
4792 /* do job control only in root shell */
4794 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4797 if (jp->nprocs == 0)
4800 pgrp = jp->ps[0].ps_pid;
4801 /* this can fail because we are doing it in the parent also */
4803 if (mode == FORK_FG)
4804 xtcsetpgrp(ttyfd, pgrp);
4809 if (mode == FORK_BG) {
4810 /* man bash: "When job control is not in effect,
4811 * asynchronous commands ignore SIGINT and SIGQUIT" */
4814 if (jp->nprocs == 0) {
4816 if (open(bb_dev_null, O_RDONLY) != 0)
4817 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4821 if (iflag) { /* why if iflag only? */
4826 * "In all cases, bash ignores SIGQUIT. Non-builtin
4827 * commands run by bash have signal handlers
4828 * set to the values inherited by the shell
4830 * Take care of the second rule: */
4834 if (n && n->type == NCMD
4835 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4837 TRACE(("Job hack\n"));
4838 /* "jobs": we do not want to clear job list for it,
4839 * instead we remove only _its_ own_ job from job list.
4840 * This makes "jobs .... | cat" more useful.
4846 for (jp = curjob; jp; jp = jp->prev_job)
4851 /* Called after fork(), in parent */
4853 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4856 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4858 TRACE(("In parent shell: child = %d\n", pid));
4860 /* jp is NULL when called by openhere() for heredoc support */
4861 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4867 if (mode != FORK_NOJOB && jp->jobctl) {
4870 if (jp->nprocs == 0)
4873 pgrp = jp->ps[0].ps_pid;
4874 /* This can fail because we are doing it in the child also */
4878 if (mode == FORK_BG) {
4879 backgndpid = pid; /* set $! */
4880 set_curjob(jp, CUR_RUNNING);
4883 struct procstat *ps = &jp->ps[jp->nprocs++];
4886 ps->ps_cmd = nullstr;
4888 if (doing_jobctl && n)
4889 ps->ps_cmd = commandtext(n);
4894 /* jp and n are NULL when called by openhere() for heredoc support */
4896 forkshell(struct job *jp, union node *n, int mode)
4900 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4903 TRACE(("Fork failed, errno=%d", errno));
4906 ash_msg_and_raise_error("can't fork");
4909 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4910 forkchild(jp, n, mode);
4912 forkparent(jp, n, mode, pid);
4918 * Wait for job to finish.
4920 * Under job control we have the problem that while a child process
4921 * is running interrupts generated by the user are sent to the child
4922 * but not to the shell. This means that an infinite loop started by
4923 * an interactive user may be hard to kill. With job control turned off,
4924 * an interactive user may place an interactive program inside a loop.
4925 * If the interactive program catches interrupts, the user doesn't want
4926 * these interrupts to also abort the loop. The approach we take here
4927 * is to have the shell ignore interrupt signals while waiting for a
4928 * foreground process to terminate, and then send itself an interrupt
4929 * signal if the child process was terminated by an interrupt signal.
4930 * Unfortunately, some programs want to do a bit of cleanup and then
4931 * exit on interrupt; unless these processes terminate themselves by
4932 * sending a signal to themselves (instead of calling exit) they will
4933 * confuse this approach.
4935 * Called with interrupts off.
4938 waitforjob(struct job *jp)
4942 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4945 while (jp->state == JOBRUNNING) {
4946 /* In non-interactive shells, we _can_ get
4947 * a keyboard signal here and be EINTRed,
4948 * but we just loop back, waiting for command to complete.
4951 * "If bash is waiting for a command to complete and receives
4952 * a signal for which a trap has been set, the trap
4953 * will not be executed until the command completes."
4955 * Reality is that even if trap is not set, bash
4956 * will not act on the signal until command completes.
4957 * Try this. sleep5intoff.c:
4958 * #include <signal.h>
4959 * #include <unistd.h>
4962 * sigemptyset(&set);
4963 * sigaddset(&set, SIGINT);
4964 * sigaddset(&set, SIGQUIT);
4965 * sigprocmask(SIG_BLOCK, &set, NULL);
4969 * $ bash -c './sleep5intoff; echo hi'
4970 * ^C^C^C^C <--- pressing ^C once a second
4972 * $ bash -c './sleep5intoff; echo hi'
4973 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4976 dowait(DOWAIT_BLOCK, jp);
4983 xtcsetpgrp(ttyfd, rootpid);
4985 * This is truly gross.
4986 * If we're doing job control, then we did a TIOCSPGRP which
4987 * caused us (the shell) to no longer be in the controlling
4988 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4989 * intuit from the subprocess exit status whether a SIGINT
4990 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4992 if (jp->sigint) /* TODO: do the same with all signals */
4993 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4995 if (jp->state == JOBDONE)
5002 * return 1 if there are stopped jobs, otherwise 0
5014 if (jp && jp->state == JOBSTOPPED) {
5015 out2str("You have stopped jobs.\n");
5025 * Code for dealing with input/output redirection.
5030 #define EMPTY -2 /* marks an unused slot in redirtab */
5031 #define CLOSED -3 /* marks a slot of previously-closed fd */
5034 * Open a file in noclobber mode.
5035 * The code was copied from bash.
5038 noclobberopen(const char *fname)
5041 struct stat finfo, finfo2;
5044 * If the file exists and is a regular file, return an error
5047 r = stat(fname, &finfo);
5048 if (r == 0 && S_ISREG(finfo.st_mode)) {
5054 * If the file was not present (r != 0), make sure we open it
5055 * exclusively so that if it is created before we open it, our open
5056 * will fail. Make sure that we do not truncate an existing file.
5057 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5058 * file was not a regular file, we leave O_EXCL off.
5061 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5062 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5064 /* If the open failed, return the file descriptor right away. */
5069 * OK, the open succeeded, but the file may have been changed from a
5070 * non-regular file to a regular file between the stat and the open.
5071 * We are assuming that the O_EXCL open handles the case where FILENAME
5072 * did not exist and is symlinked to an existing file between the stat
5077 * If we can open it and fstat the file descriptor, and neither check
5078 * revealed that it was a regular file, and the file has not been
5079 * replaced, return the file descriptor.
5081 if (fstat(fd, &finfo2) == 0
5082 && !S_ISREG(finfo2.st_mode)
5083 && finfo.st_dev == finfo2.st_dev
5084 && finfo.st_ino == finfo2.st_ino
5089 /* The file has been replaced. badness. */
5096 * Handle here documents. Normally we fork off a process to write the
5097 * data to a pipe. If the document is short, we can stuff the data in
5098 * the pipe without forking.
5100 /* openhere needs this forward reference */
5101 static void expandhere(union node *arg, int fd);
5103 openhere(union node *redir)
5109 ash_msg_and_raise_error("pipe call failed");
5110 if (redir->type == NHERE) {
5111 len = strlen(redir->nhere.doc->narg.text);
5112 if (len <= PIPE_BUF) {
5113 full_write(pip[1], redir->nhere.doc->narg.text, len);
5117 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5120 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5121 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5122 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5123 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5124 signal(SIGPIPE, SIG_DFL);
5125 if (redir->type == NHERE)
5126 full_write(pip[1], redir->nhere.doc->narg.text, len);
5128 expandhere(redir->nhere.doc, pip[1]);
5129 _exit(EXIT_SUCCESS);
5137 openredirect(union node *redir)
5142 switch (redir->nfile.type) {
5143 /* Can't happen, our single caller does this itself */
5149 return openhere(redir);
5152 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5153 * allocated space. Do it only when we know it is safe.
5155 fname = redir->nfile.expfname;
5157 switch (redir->nfile.type) {
5163 f = open(fname, O_RDONLY);
5168 f = open(fname, O_RDWR|O_CREAT, 0666);
5173 #if ENABLE_ASH_BASH_COMPAT
5176 /* Take care of noclobber mode. */
5178 f = noclobberopen(fname);
5185 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5190 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5198 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5200 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5204 * Copy a file descriptor to be >= 10. Throws exception on error.
5212 newfd = fcntl(from, F_DUPFD, 10);
5213 err = newfd < 0 ? errno : 0;
5216 ash_msg_and_raise_error("%d: %m", from);
5218 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5224 dup2_or_raise(int from, int to)
5228 newfd = (from != to) ? dup2(from, to) : to;
5230 /* Happens when source fd is not open: try "echo >&99" */
5231 ash_msg_and_raise_error("%d: %m", from);
5236 /* Struct def and variable are moved down to the first usage site */
5241 struct redirtab *next;
5243 struct two_fd_t two_fd[];
5245 #define redirlist (G_var.redirlist)
5247 COPYFD_RESTORE = (int)~(INT_MAX),
5251 need_to_remember(struct redirtab *rp, int fd)
5255 if (!rp) /* remembering was not requested */
5258 for (i = 0; i < rp->pair_count; i++) {
5259 if (rp->two_fd[i].orig == fd) {
5260 /* already remembered */
5267 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5269 is_hidden_fd(struct redirtab *rp, int fd)
5272 struct parsefile *pf;
5276 /* Check open scripts' fds */
5279 /* We skip pf_fd == 0 case because of the following case:
5280 * $ ash # running ash interactively
5282 * and in script.sh: "exec 9>&0".
5283 * Even though top-level pf_fd _is_ 0,
5284 * it's still ok to use it: "read" builtin uses it,
5285 * why should we cripple "exec" builtin?
5287 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5295 /* Check saved fds of redirects */
5296 fd |= COPYFD_RESTORE;
5297 for (i = 0; i < rp->pair_count; i++) {
5298 if (rp->two_fd[i].copy == fd) {
5306 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5307 * old file descriptors are stashed away so that the redirection can be
5308 * undone by calling popredir.
5310 /* flags passed to redirect */
5311 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5312 #define REDIR_SAVEFD2 03 /* set preverrout */
5314 redirect(union node *redir, int flags)
5316 struct redirtab *sv;
5321 int copied_fd2 = -1;
5330 if (flags & REDIR_PUSH) {
5331 union node *tmp = redir;
5334 #if ENABLE_ASH_BASH_COMPAT
5335 if (tmp->nfile.type == NTO2)
5338 tmp = tmp->nfile.next;
5340 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5341 sv->next = redirlist;
5342 sv->pair_count = sv_pos;
5344 while (sv_pos > 0) {
5346 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5352 fd = redir->nfile.fd;
5353 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5354 right_fd = redir->ndup.dupfd;
5355 //bb_error_msg("doing %d > %d", fd, right_fd);
5356 /* redirect from/to same file descriptor? */
5359 /* "echo >&10" and 10 is a fd opened to a sh script? */
5360 if (is_hidden_fd(sv, right_fd)) {
5361 errno = EBADF; /* as if it is closed */
5362 ash_msg_and_raise_error("%d: %m", right_fd);
5366 newfd = openredirect(redir); /* always >= 0 */
5368 /* Descriptor wasn't open before redirect.
5369 * Mark it for close in the future */
5370 if (need_to_remember(sv, fd)) {
5371 goto remember_to_close;
5376 #if ENABLE_ASH_BASH_COMPAT
5379 if (need_to_remember(sv, fd)) {
5380 /* Copy old descriptor */
5381 /* Careful to not accidentally "save"
5382 * to the same fd as right side fd in N>&M */
5383 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5384 i = fcntl(fd, F_DUPFD, minfd);
5385 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5386 * are closed in popredir() in the child, preventing them from leaking
5387 * into child. (popredir() also cleans up the mess in case of failures)
5392 /* Strange error (e.g. "too many files" EMFILE?) */
5396 ash_msg_and_raise_error("%d: %m", fd);
5399 /* EBADF: it is not open - good, remember to close it */
5402 } else { /* fd is open, save its copy */
5403 /* "exec fd>&-" should not close fds
5404 * which point to script file(s).
5405 * Force them to be restored afterwards */
5406 if (is_hidden_fd(sv, fd))
5407 i |= COPYFD_RESTORE;
5411 sv->two_fd[sv_pos].orig = fd;
5412 sv->two_fd[sv_pos].copy = i;
5416 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5417 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5418 /* Don't want to trigger debugging */
5422 dup2_or_raise(redir->ndup.dupfd, fd);
5424 } else if (fd != newfd) { /* move newfd to fd */
5425 dup2_or_raise(newfd, fd);
5426 #if ENABLE_ASH_BASH_COMPAT
5427 if (!(redir->nfile.type == NTO2 && fd == 2))
5431 #if ENABLE_ASH_BASH_COMPAT
5432 if (redir->nfile.type == NTO2 && fd == 1) {
5433 /* We already redirected it to fd 1, now copy it to 2 */
5439 } while ((redir = redir->nfile.next) != NULL);
5442 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5443 preverrout_fd = copied_fd2;
5447 * Undo the effects of the last redirection.
5450 popredir(int drop, int restore)
5452 struct redirtab *rp;
5455 if (redirlist == NULL)
5459 for (i = 0; i < rp->pair_count; i++) {
5460 int fd = rp->two_fd[i].orig;
5461 int copy = rp->two_fd[i].copy;
5462 if (copy == CLOSED) {
5467 if (copy != EMPTY) {
5468 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5469 copy &= ~COPYFD_RESTORE;
5471 dup2_or_raise(copy, fd);
5473 close(copy & ~COPYFD_RESTORE);
5476 redirlist = rp->next;
5482 * Undo all redirections. Called on error or interrupt.
5486 redirectsafe(union node *redir, int flags)
5489 volatile int saveint;
5490 struct jmploc *volatile savehandler = exception_handler;
5491 struct jmploc jmploc;
5494 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5495 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5497 exception_handler = &jmploc;
5498 redirect(redir, flags);
5500 exception_handler = savehandler;
5501 if (err && exception_type != EXERROR)
5502 longjmp(exception_handler->loc, 1);
5503 RESTORE_INT(saveint);
5508 /* ============ Routines to expand arguments to commands
5510 * We have to deal with backquotes, shell variables, and file metacharacters.
5513 #if ENABLE_SH_MATH_SUPPORT
5515 ash_arith(const char *s)
5517 arith_state_t math_state;
5520 math_state.lookupvar = lookupvar;
5521 math_state.setvar = setvar0;
5522 //math_state.endofname = endofname;
5525 result = arith(&math_state, s);
5526 if (math_state.errmsg)
5527 ash_msg_and_raise_error(math_state.errmsg);
5537 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5538 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5539 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5540 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5541 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5542 * POSIX says for this case:
5543 * Pathname expansion shall not be performed on the word by a
5544 * non-interactive shell; an interactive shell may perform it, but shall
5545 * do so only when the expansion would result in one word.
5546 * Currently, our code complies to the above rule by never globbing
5547 * redirection filenames.
5548 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5549 * (this means that on a typical Linux distro, bash almost always
5550 * performs globbing, and thus diverges from what we do).
5552 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5553 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5554 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5555 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5556 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5560 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5561 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5562 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5563 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5564 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5566 /* Add CTLESC when necessary. */
5567 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5568 /* Do not skip NUL characters. */
5569 #define QUOTES_KEEPNUL EXP_TILDE
5572 * Structure specifying which parts of the string should be searched
5573 * for IFS characters.
5576 struct ifsregion *next; /* next region in list */
5577 int begoff; /* offset of start of region */
5578 int endoff; /* offset of end of region */
5579 int nulonly; /* search for nul bytes only */
5583 struct strlist *list;
5584 struct strlist **lastp;
5587 /* output of current string */
5588 static char *expdest;
5589 /* list of back quote expressions */
5590 static struct nodelist *argbackq;
5591 /* first struct in list of ifs regions */
5592 static struct ifsregion ifsfirst;
5593 /* last struct in list */
5594 static struct ifsregion *ifslastp;
5595 /* holds expanded arg list */
5596 static struct arglist exparg;
5601 #if !ENABLE_SH_MATH_SUPPORT
5602 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5603 typedef long arith_t;
5604 # define ARITH_FMT "%ld"
5611 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5612 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5613 STADJUST(len, expdest);
5618 * Break the argument string into pieces based upon IFS and add the
5619 * strings to the argument list. The regions of the string to be
5620 * searched for IFS characters have been stored by recordregion.
5623 ifsbreakup(char *string, struct arglist *arglist)
5625 struct ifsregion *ifsp;
5630 const char *ifs, *realifs;
5635 if (ifslastp != NULL) {
5638 realifs = ifsset() ? ifsval() : defifs;
5641 p = string + ifsp->begoff;
5642 nulonly = ifsp->nulonly;
5643 ifs = nulonly ? nullstr : realifs;
5645 while (p < string + ifsp->endoff) {
5647 if ((unsigned char)*p == CTLESC)
5649 if (!strchr(ifs, *p)) {
5654 ifsspc = (strchr(defifs, *p) != NULL);
5655 /* Ignore IFS whitespace at start */
5656 if (q == start && ifsspc) {
5662 sp = stzalloc(sizeof(*sp));
5664 *arglist->lastp = sp;
5665 arglist->lastp = &sp->next;
5669 if (p >= string + ifsp->endoff) {
5673 if ((unsigned char)*p == CTLESC)
5675 if (strchr(ifs, *p) == NULL) {
5679 if (strchr(defifs, *p) == NULL) {
5694 } while (ifsp != NULL);
5703 sp = stzalloc(sizeof(*sp));
5705 *arglist->lastp = sp;
5706 arglist->lastp = &sp->next;
5712 struct ifsregion *p = ifsfirst.next;
5719 struct ifsregion *ifsp;
5724 ifsfirst.next = NULL;
5731 esclen(const char *start, const char *p)
5735 while (p > start && (unsigned char)*--p == CTLESC) {
5742 * Remove any CTLESC characters from a string.
5745 rmescapes(char *str, int flag)
5747 static const char qchars[] ALIGN1 = {
5748 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5752 unsigned protect_against_glob;
5754 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5756 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5762 if (flag & RMESCAPE_ALLOC) {
5763 size_t len = p - str;
5764 size_t fulllen = len + strlen(p) + 1;
5766 if (flag & RMESCAPE_GROW) {
5767 int strloc = str - (char *)stackblock();
5768 r = makestrspace(fulllen, expdest);
5769 /* p and str may be invalidated by makestrspace */
5770 str = (char *)stackblock() + strloc;
5772 } else if (flag & RMESCAPE_HEAP) {
5773 r = ckmalloc(fulllen);
5775 r = stalloc(fulllen);
5779 q = (char *)memcpy(q, str, len) + len;
5784 globbing = flag & RMESCAPE_GLOB;
5785 protect_against_glob = globbing;
5787 if ((unsigned char)*p == CTLQUOTEMARK) {
5788 // Note: both inquotes and protect_against_glob only affect whether
5789 inquotes = ~inquotes;
5791 protect_against_glob = globbing;
5794 if ((unsigned char)*p == CTLESC) {
5798 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5800 if (protect_against_glob) {
5803 } else if (*p == '\\' && !inquotes) {
5804 /* naked back slash */
5805 protect_against_glob = 0;
5808 #if ENABLE_ASH_BASH_COMPAT
5809 else if (*p == '/' && slash) {
5810 /* stop handling globbing and mark location of slash */
5811 globbing = slash = 0;
5815 protect_against_glob = globbing;
5820 if (flag & RMESCAPE_GROW) {
5822 STADJUST(q - r + 1, expdest);
5826 #define pmatch(a, b) !fnmatch((a), (b), 0)
5829 * Prepare a pattern for a expmeta (internal glob(3)) call.
5831 * Returns an stalloced string.
5834 preglob(const char *pattern, int flag)
5836 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5840 * Put a string on the stack.
5843 memtodest(const char *p, size_t len, int syntax, int quotes)
5850 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5853 unsigned char c = *p++;
5855 int n = SIT(c, syntax);
5856 if ((quotes & QUOTES_ESC)
5858 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5864 } else if (!(quotes & QUOTES_KEEPNUL))
5873 strtodest(const char *p, int syntax, int quotes)
5875 size_t len = strlen(p);
5876 memtodest(p, len, syntax, quotes);
5881 * Record the fact that we have to scan this region of the
5882 * string for IFS characters.
5885 recordregion(int start, int end, int nulonly)
5887 struct ifsregion *ifsp;
5889 if (ifslastp == NULL) {
5893 ifsp = ckzalloc(sizeof(*ifsp));
5894 /*ifsp->next = NULL; - ckzalloc did it */
5895 ifslastp->next = ifsp;
5899 ifslastp->begoff = start;
5900 ifslastp->endoff = end;
5901 ifslastp->nulonly = nulonly;
5905 removerecordregions(int endoff)
5907 if (ifslastp == NULL)
5910 if (ifsfirst.endoff > endoff) {
5911 while (ifsfirst.next) {
5912 struct ifsregion *ifsp;
5914 ifsp = ifsfirst.next->next;
5915 free(ifsfirst.next);
5916 ifsfirst.next = ifsp;
5919 if (ifsfirst.begoff > endoff) {
5922 ifslastp = &ifsfirst;
5923 ifsfirst.endoff = endoff;
5928 ifslastp = &ifsfirst;
5929 while (ifslastp->next && ifslastp->next->begoff < endoff)
5930 ifslastp = ifslastp->next;
5931 while (ifslastp->next) {
5932 struct ifsregion *ifsp;
5934 ifsp = ifslastp->next->next;
5935 free(ifslastp->next);
5936 ifslastp->next = ifsp;
5939 if (ifslastp->endoff > endoff)
5940 ifslastp->endoff = endoff;
5944 exptilde(char *startp, char *p, int flags)
5950 int quotes = flags & QUOTES_ESC;
5954 while ((c = *++p) != '\0') {
5961 if (flags & EXP_VARTILDE)
5971 if (*name == '\0') {
5972 home = lookupvar("HOME");
5974 pw = getpwnam(name);
5979 if (!home || !*home)
5982 strtodest(home, SQSYNTAX, quotes);
5990 * Execute a command inside back quotes. If it's a builtin command, we
5991 * want to save its output in a block obtained from malloc. Otherwise
5992 * we fork off a subprocess and get the output of the command via a pipe.
5993 * Should be called with interrupts off.
5995 struct backcmd { /* result of evalbackcmd */
5996 int fd; /* file descriptor to read from */
5997 int nleft; /* number of chars in buffer */
5998 char *buf; /* buffer */
5999 struct job *jp; /* job structure for command */
6002 /* These forward decls are needed to use "eval" code for backticks handling: */
6003 #define EV_EXIT 01 /* exit after evaluating tree */
6004 static int evaltree(union node *, int);
6006 static void FAST_FUNC
6007 evalbackcmd(union node *n, struct backcmd *result)
6021 ash_msg_and_raise_error("pipe call failed");
6022 jp = makejob(/*n,*/ 1);
6023 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6029 dup2_or_raise(pip[1], 1);
6032 /* TODO: eflag clearing makes the following not abort:
6033 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6034 * which is what bash does (unless it is in POSIX mode).
6035 * dash deleted "eflag = 0" line in the commit
6036 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6037 * [EVAL] Don't clear eflag in evalbackcmd
6038 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6042 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6047 result->fd = pip[0];
6051 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6052 result->fd, result->buf, result->nleft, result->jp));
6056 * Expand stuff in backwards quotes.
6059 expbackq(union node *cmd, int flag)
6067 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6068 struct stackmark smark;
6071 startloc = expdest - (char *)stackblock();
6072 pushstackmark(&smark, startloc);
6073 evalbackcmd(cmd, &in);
6074 popstackmark(&smark);
6081 memtodest(p, i, syntax, flag & QUOTES_ESC);
6085 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6086 TRACE(("expbackq: read returns %d\n", i));
6095 back_exitstatus = waitforjob(in.jp);
6099 /* Eat all trailing newlines */
6101 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6105 if (!(flag & EXP_QUOTED))
6106 recordregion(startloc, dest - (char *)stackblock(), 0);
6107 TRACE(("evalbackq: size:%d:'%.*s'\n",
6108 (int)((dest - (char *)stackblock()) - startloc),
6109 (int)((dest - (char *)stackblock()) - startloc),
6110 stackblock() + startloc));
6113 #if ENABLE_SH_MATH_SUPPORT
6115 * Expand arithmetic expression. Backup to start of expression,
6116 * evaluate, place result in (backed up) result, adjust string position.
6128 * This routine is slightly over-complicated for
6129 * efficiency. Next we scan backwards looking for the
6130 * start of arithmetic.
6132 start = stackblock();
6139 while ((unsigned char)*p != CTLARI) {
6143 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6148 esc = esclen(start, p);
6158 removerecordregions(begoff);
6162 if (flag & QUOTES_ESC)
6163 rmescapes(p + 1, 0);
6165 len = cvtnum(ash_arith(p + 1));
6167 if (!(flag & EXP_QUOTED))
6168 recordregion(begoff, begoff + len, 0);
6172 /* argstr needs it */
6173 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6176 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6177 * characters to allow for further processing. Otherwise treat
6178 * $@ like $* since no splitting will be performed.
6180 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6181 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6182 * for correct expansion of "B=$A" word.
6185 argstr(char *p, int flags, struct strlist *var_str_list)
6187 static const char spclchars[] ALIGN1 = {
6195 #if ENABLE_SH_MATH_SUPPORT
6200 const char *reject = spclchars;
6201 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6206 if (!(flags & EXP_VARTILDE)) {
6208 } else if (flags & EXP_VARTILDE2) {
6213 if (flags & EXP_TILDE) {
6216 flags &= ~EXP_TILDE;
6220 p = exptilde(p, q, flags);
6223 startloc = expdest - (char *)stackblock();
6227 length += strcspn(p + length, reject);
6231 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6233 /* c == '=' || c == ':' || c == CTLENDARI */
6239 expdest = stack_nputstr(p, length, expdest);
6240 newloc = expdest - (char *)stackblock();
6241 if (breakall && !inquotes && newloc > startloc) {
6242 recordregion(startloc, newloc, 0);
6253 if (flags & EXP_VARTILDE2) {
6257 flags |= EXP_VARTILDE2;
6262 * sort of a hack - expand tildes in variable
6263 * assignments (after the first '=' and after ':'s).
6272 case CTLENDVAR: /* ??? */
6275 inquotes ^= EXP_QUOTED;
6276 /* "$@" syntax adherence hack */
6277 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6278 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6282 if (flags & QUOTES_ESC) {
6293 * Quoted parameter expansion pattern: remove quote
6294 * unless inside inner quotes or we have a literal
6297 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6298 EXP_QPAT && *p != '\\')
6303 TRACE(("argstr: evalvar('%s')\n", p));
6304 p = evalvar(p, flags | inquotes, var_str_list);
6305 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6308 expbackq(argbackq->n, flags | inquotes);
6309 argbackq = argbackq->next;
6311 #if ENABLE_SH_MATH_SUPPORT
6314 expari(flags | inquotes);
6323 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6324 char *pattern, int quotes, int zero)
6333 const char *s = loc2;
6340 match = pmatch(pattern, s);
6345 if (quotes && (unsigned char)*loc == CTLESC)
6354 scanright(char *startp, char *rmesc, char *rmescend,
6355 char *pattern, int quotes, int match_at_start)
6357 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6358 int try2optimize = match_at_start;
6364 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6365 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6366 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6368 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6369 * and on each iteration they go back two/one char until they reach the beginning.
6370 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6372 /* TODO: document in what other circumstances we are called. */
6374 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6377 const char *s = loc2;
6378 if (match_at_start) {
6382 match = pmatch(pattern, s);
6383 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6387 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6389 /* Maybe we can optimize this:
6390 * if pattern ends with unescaped *, we can avoid checking
6391 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6392 * it wont match truncated "raw_value_of_" strings too.
6394 unsigned plen = strlen(pattern);
6395 /* Does it end with "*"? */
6396 if (plen != 0 && pattern[--plen] == '*') {
6397 /* "xxxx*" is not escaped */
6398 /* "xxx\*" is escaped */
6399 /* "xx\\*" is not escaped */
6400 /* "x\\\*" is escaped */
6402 while (plen != 0 && pattern[--plen] == '\\')
6405 break; /* ends with unescaped "*" */
6413 esc = esclen(startp, loc);
6424 static void varunset(const char *, const char *, const char *, int) NORETURN;
6426 varunset(const char *end, const char *var, const char *umsg, int varflags)
6432 msg = "parameter not set";
6434 if ((unsigned char)*end == CTLENDVAR) {
6435 if (varflags & VSNUL)
6441 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6445 subevalvar(char *p, char *varname, int strloc, int subtype,
6446 int startloc, int varflags, int flag, struct strlist *var_str_list)
6448 struct nodelist *saveargbackq = argbackq;
6449 int quotes = flag & QUOTES_ESC;
6452 char *rmesc, *rmescend;
6454 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6455 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6456 int amount, resetloc;
6457 IF_ASH_BASH_COMPAT(int workloc;)
6459 char *(*scan)(char*, char*, char*, char*, int, int);
6461 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6462 // p, varname, strloc, subtype, startloc, varflags, quotes);
6464 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6465 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6467 STPUTC('\0', expdest);
6468 argbackq = saveargbackq;
6469 startp = (char *)stackblock() + startloc;
6473 setvar0(varname, startp);
6474 amount = startp - expdest;
6475 STADJUST(amount, expdest);
6479 varunset(p, varname, startp, varflags);
6482 #if ENABLE_ASH_BASH_COMPAT
6484 //TODO: support more general format ${v:EXPR:EXPR},
6485 // where EXPR follows $(()) rules
6486 loc = str = stackblock() + strloc;
6487 /* Read POS in ${var:POS:LEN} */
6488 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6489 len = str - startp - 1;
6491 /* *loc != '\0', guaranteed by parser */
6495 /* Adjust the length by the number of escapes */
6496 for (ptr = startp; ptr < (str - 1); ptr++) {
6497 if ((unsigned char)*ptr == CTLESC) {
6505 if (*loc++ == ':') {
6509 /* Skip POS in ${var:POS:LEN} */
6511 while (*loc && *loc != ':') {
6513 * bash complains on: var=qwe; echo ${var:1a:123}
6515 ash_msg_and_raise_error(msg_illnum, str);
6519 if (*loc++ == ':') {
6524 /* ${VAR:$((-n)):l} starts n chars from the end */
6525 pos = orig_len + pos;
6527 if ((unsigned)pos >= orig_len) {
6528 /* apart from obvious ${VAR:999999:l},
6529 * covers ${VAR:$((-9999999)):l} - result is ""
6535 if (len > (orig_len - pos))
6536 len = orig_len - pos;
6538 for (str = startp; pos; str++, pos--) {
6539 if (quotes && (unsigned char)*str == CTLESC)
6542 for (loc = startp; len; len--) {
6543 if (quotes && (unsigned char)*str == CTLESC)
6548 amount = loc - expdest;
6549 STADJUST(amount, expdest);
6554 resetloc = expdest - (char *)stackblock();
6556 /* We'll comeback here if we grow the stack while handling
6557 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6558 * stack will need rebasing, and we'll need to remove our work
6561 IF_ASH_BASH_COMPAT(restart:)
6563 amount = expdest - ((char *)stackblock() + resetloc);
6564 STADJUST(-amount, expdest);
6565 startp = (char *)stackblock() + startloc;
6568 rmescend = (char *)stackblock() + strloc;
6570 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6571 if (rmesc != startp) {
6573 startp = (char *)stackblock() + startloc;
6577 str = (char *)stackblock() + strloc;
6579 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6580 * The result is a_\_z_c (not a\_\_z_c)!
6582 * The search pattern and replace string treat backslashes differently!
6583 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6584 * and string. It's only used on the first call.
6586 preglob(str, IF_ASH_BASH_COMPAT(
6587 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6588 RMESCAPE_SLASH :) 0);
6590 #if ENABLE_ASH_BASH_COMPAT
6591 workloc = expdest - (char *)stackblock();
6592 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6596 repl = strchr(str, CTLESC);
6602 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6604 /* If there's no pattern to match, return the expansion unmolested */
6613 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6614 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6616 /* No match, advance */
6617 char *restart_detect = stackblock();
6619 STPUTC(*idx, expdest);
6620 if (quotes && (unsigned char)*idx == CTLESC) {
6623 STPUTC(*idx, expdest);
6625 if (stackblock() != restart_detect)
6630 /* continue; - prone to quadratic behavior, smarter code: */
6633 if (str[0] == '*') {
6634 /* Pattern is "*foo". If "*foo" does not match "long_string",
6635 * it would never match "ong_string" etc, no point in trying.
6642 if (subtype == VSREPLACEALL) {
6644 if (quotes && (unsigned char)*idx == CTLESC)
6653 //bb_error_msg("repl:'%s'", repl);
6654 for (loc = (char*)repl; *loc; loc++) {
6655 char *restart_detect = stackblock();
6656 if (quotes && *loc == '\\') {
6657 STPUTC(CTLESC, expdest);
6660 STPUTC(*loc, expdest);
6661 if (stackblock() != restart_detect)
6666 if (subtype == VSREPLACE) {
6667 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6669 char *restart_detect = stackblock();
6670 STPUTC(*idx, expdest);
6671 if (stackblock() != restart_detect)
6680 /* We've put the replaced text into a buffer at workloc, now
6681 * move it to the right place and adjust the stack.
6683 STPUTC('\0', expdest);
6684 startp = (char *)stackblock() + startloc;
6685 memmove(startp, (char *)stackblock() + workloc, len + 1);
6686 //bb_error_msg("startp:'%s'", startp);
6687 amount = expdest - (startp + len);
6688 STADJUST(-amount, expdest);
6691 #endif /* ENABLE_ASH_BASH_COMPAT */
6693 subtype -= VSTRIMRIGHT;
6695 if (subtype < 0 || subtype > 7)
6698 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6699 zero = subtype >> 1;
6700 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6701 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6703 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6706 memmove(startp, loc, str - loc);
6707 loc = startp + (str - loc) - 1;
6710 amount = loc - expdest;
6711 STADJUST(amount, expdest);
6717 * Add the value of a specialized variable to the stack string.
6718 * name parameter (examples):
6719 * ash -c 'echo $1' name:'1='
6720 * ash -c 'echo $qwe' name:'qwe='
6721 * ash -c 'echo $$' name:'$='
6722 * ash -c 'echo ${$}' name:'$='
6723 * ash -c 'echo ${$##q}' name:'$=q'
6724 * ash -c 'echo ${#$}' name:'$='
6725 * note: examples with bad shell syntax:
6726 * ash -c 'echo ${#$1}' name:'$=1'
6727 * ash -c 'echo ${#1#}' name:'1=#'
6729 static NOINLINE ssize_t
6730 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6737 int quoted = *quotedp;
6738 int subtype = varflags & VSTYPE;
6739 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6740 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6743 sep = (flags & EXP_FULL) << CHAR_BIT;
6744 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6754 num = shellparam.nparam;
6762 goto check_1char_name;
6764 expdest = makestrspace(NOPTS, expdest);
6765 for (i = NOPTS - 1; i >= 0; i--) {
6767 USTPUTC(optletters(i), expdest);
6773 /* handles cases similar to ${#$1} */
6774 if (name[2] != '\0')
6775 raise_error_syntax("bad substitution");
6788 sep |= ifsset() ? ifsval()[0] : ' ';
6795 while ((p = *ap++) != NULL) {
6796 len += strtodest(p, syntax, quotes);
6800 memtodest(&sepc, 1, syntax, quotes);
6815 num = atoi(name); /* number(name) fails on ${N#str} etc */
6816 if (num < 0 || num > shellparam.nparam)
6818 p = num ? shellparam.p[num - 1] : arg0;
6821 /* NB: name has form "VAR=..." */
6823 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6824 * which should be considered before we check variables. */
6826 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6830 str = var_str_list->text;
6831 eq = strchr(str, '=');
6832 if (!eq) /* stop at first non-assignment */
6835 if (name_len == (unsigned)(eq - str)
6836 && strncmp(str, name, name_len) == 0
6839 /* goto value; - WRONG! */
6840 /* think "A=1 A=2 B=$A" */
6842 var_str_list = var_str_list->next;
6843 } while (var_str_list);
6847 p = lookupvar(name);
6852 len = strtodest(p, syntax, quotes);
6853 #if ENABLE_UNICODE_SUPPORT
6854 if (subtype == VSLENGTH && len > 0) {
6855 reinit_unicode_for_ash();
6856 if (unicode_status == UNICODE_ON) {
6857 STADJUST(-len, expdest);
6859 len = unicode_strlen(p);
6867 STADJUST(-len, expdest);
6872 * Expand a variable, and return a pointer to the next character in the
6876 evalvar(char *p, int flag, struct strlist *var_str_list)
6887 varflags = (unsigned char) *p++;
6888 subtype = varflags & VSTYPE;
6891 raise_error_syntax("bad substitution");
6893 quoted = flag & EXP_QUOTED;
6895 easy = (!quoted || (*var == '@' && shellparam.nparam));
6896 startloc = expdest - (char *)stackblock();
6897 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6900 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6901 if (varflags & VSNUL)
6904 if (subtype == VSPLUS) {
6905 varlen = -1 - varlen;
6909 if (subtype == VSMINUS) {
6914 flag | EXP_TILDE | EXP_WORD,
6922 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6926 subevalvar(p, var, 0, subtype, startloc, varflags,
6927 flag & ~QUOTES_ESC, var_str_list);
6930 * Remove any recorded regions beyond
6933 removerecordregions(startloc);
6937 if (varlen < 0 && uflag)
6938 varunset(p, var, 0, 0);
6940 if (subtype == VSLENGTH) {
6941 cvtnum(varlen > 0 ? varlen : 0);
6945 if (subtype == VSNORMAL) {
6949 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6958 case VSTRIMRIGHTMAX:
6959 #if ENABLE_ASH_BASH_COMPAT
6972 * Terminate the string and start recording the pattern
6975 STPUTC('\0', expdest);
6976 patloc = expdest - (char *)stackblock();
6977 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6978 startloc, varflags, flag, var_str_list)) {
6979 int amount = expdest - (
6980 (char *)stackblock() + patloc - 1
6982 STADJUST(-amount, expdest);
6984 /* Remove any recorded regions beyond start of variable */
6985 removerecordregions(startloc);
6990 if (subtype != VSNORMAL) { /* skip to end of alternative */
6993 unsigned char c = *p++;
6996 else if (c == CTLBACKQ) {
6998 argbackq = argbackq->next;
6999 } else if (c == CTLVAR) {
7000 if ((*p++ & VSTYPE) != VSNORMAL)
7002 } else if (c == CTLENDVAR) {
7012 * Add a file name to the list.
7015 addfname(const char *name)
7019 sp = stzalloc(sizeof(*sp));
7020 sp->text = sstrdup(name);
7022 exparg.lastp = &sp->next;
7025 /* If we want to use glob() from libc... */
7026 #if !ENABLE_ASH_INTERNAL_GLOB
7028 /* Add the result of glob() to the list */
7030 addglob(const glob_t *pglob)
7032 char **p = pglob->gl_pathv;
7039 expandmeta(struct strlist *str /*, int flag*/)
7041 /* TODO - EXP_REDIR */
7051 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7052 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7053 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7055 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7056 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7057 // Which means you need to unescape the string, right? Not so fast:
7058 // if there _is_ a file named "file\?" (with backslash), it is returned
7059 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7060 // You DONT KNOW by looking at the result whether you need to unescape it.
7062 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7063 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7064 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7065 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7066 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7067 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7068 i = glob(p, 0, NULL, &pglob);
7069 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7074 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7075 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7076 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7088 *exparg.lastp = str;
7089 rmescapes(str->text, 0);
7090 exparg.lastp = &str->next;
7092 default: /* GLOB_NOSPACE */
7095 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7102 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7105 * Do metacharacter (i.e. *, ?, [...]) expansion.
7108 expmeta(char *expdir, char *enddir, char *name)
7124 for (p = name; esc = 0, *p; p += esc + 1) {
7125 if (*p == '*' || *p == '?')
7127 else if (*p == '[') {
7134 if (*q == '/' || *q == '\0')
7144 if (p[esc] == '/') {
7147 start = p + esc + 1;
7151 if (metaflag == 0) { /* we've reached the end of the file name */
7152 if (enddir != expdir)
7160 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7171 } while (p < start);
7173 if (enddir == expdir) {
7175 } else if (enddir == expdir + 1 && *expdir == '/') {
7184 if (enddir != expdir)
7186 if (*endname == 0) {
7199 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7200 if (dp->d_name[0] == '.' && !matchdot)
7202 if (pmatch(start, dp->d_name)) {
7204 strcpy(enddir, dp->d_name);
7207 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7210 expmeta(expdir, p, endname);
7216 endname[-esc - 1] = esc ? '\\' : '/';
7219 static struct strlist *
7220 msort(struct strlist *list, int len)
7222 struct strlist *p, *q = NULL;
7223 struct strlist **lpp;
7231 for (n = half; --n >= 0;) {
7235 q->next = NULL; /* terminate first half of list */
7236 q = msort(list, half); /* sort first half of list */
7237 p = msort(p, len - half); /* sort second half */
7240 #if ENABLE_LOCALE_SUPPORT
7241 if (strcoll(p->text, q->text) < 0)
7243 if (strcmp(p->text, q->text) < 0)
7267 * Sort the results of file name expansion. It calculates the number of
7268 * strings to sort and then calls msort (short for merge sort) to do the
7271 static struct strlist *
7272 expsort(struct strlist *str)
7278 for (sp = str; sp; sp = sp->next)
7280 return msort(str, len);
7284 expandmeta(struct strlist *str /*, int flag*/)
7286 static const char metachars[] ALIGN1 = {
7289 /* TODO - EXP_REDIR */
7293 struct strlist **savelastp;
7299 if (!strpbrk(str->text, metachars))
7301 savelastp = exparg.lastp;
7304 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7306 int i = strlen(str->text);
7307 //BUGGY estimation of how long expanded name can be
7308 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7310 expmeta(expdir, expdir, p);
7315 if (exparg.lastp == savelastp) {
7320 *exparg.lastp = str;
7321 rmescapes(str->text, 0);
7322 exparg.lastp = &str->next;
7324 *exparg.lastp = NULL;
7325 *savelastp = sp = expsort(*savelastp);
7326 while (sp->next != NULL)
7328 exparg.lastp = &sp->next;
7333 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7336 * Perform variable substitution and command substitution on an argument,
7337 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7338 * perform splitting and file name expansion. When arglist is NULL, perform
7339 * here document expansion.
7342 expandarg(union node *arg, struct arglist *arglist, int flag)
7347 argbackq = arg->narg.backquote;
7348 STARTSTACKSTR(expdest);
7349 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7350 argstr(arg->narg.text, flag,
7351 /* var_str_list: */ arglist ? arglist->list : NULL);
7352 p = _STPUTC('\0', expdest);
7354 if (arglist == NULL) {
7355 /* here document expanded */
7358 p = grabstackstr(p);
7359 TRACE(("expandarg: p:'%s'\n", p));
7360 exparg.lastp = &exparg.list;
7364 if (flag & EXP_FULL) {
7365 ifsbreakup(p, &exparg);
7366 *exparg.lastp = NULL;
7367 exparg.lastp = &exparg.list;
7368 expandmeta(exparg.list /*, flag*/);
7370 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7372 TRACE(("expandarg: rmescapes:'%s'\n", p));
7374 sp = stzalloc(sizeof(*sp));
7377 exparg.lastp = &sp->next;
7379 *exparg.lastp = NULL;
7381 *arglist->lastp = exparg.list;
7382 arglist->lastp = exparg.lastp;
7390 * Expand shell variables and backquotes inside a here document.
7393 expandhere(union node *arg, int fd)
7395 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7396 full_write(fd, stackblock(), expdest - (char *)stackblock());
7400 * Returns true if the pattern matches the string.
7403 patmatch(char *pattern, const char *string)
7405 return pmatch(preglob(pattern, 0), string);
7409 * See if a pattern matches in a case statement.
7412 casematch(union node *pattern, char *val)
7414 struct stackmark smark;
7417 setstackmark(&smark);
7418 argbackq = pattern->narg.backquote;
7419 STARTSTACKSTR(expdest);
7420 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7421 /* var_str_list: */ NULL);
7422 STACKSTRNUL(expdest);
7424 result = patmatch(stackblock(), val);
7425 popstackmark(&smark);
7430 /* ============ find_command */
7434 int (*builtin)(int, char **) FAST_FUNC;
7435 /* unsigned flags; */
7437 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7438 /* "regular" builtins always take precedence over commands,
7439 * regardless of PATH=....%builtin... position */
7440 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7441 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7444 smallint cmdtype; /* CMDxxx */
7447 /* index >= 0 for commands without path (slashes) */
7448 /* (TODO: what exactly does the value mean? PATH position?) */
7449 /* index == -1 for commands with slashes */
7450 /* index == (-2 - applet_no) for NOFORK applets */
7451 const struct builtincmd *cmd;
7452 struct funcnode *func;
7455 /* values of cmdtype */
7456 #define CMDUNKNOWN -1 /* no entry in table for command */
7457 #define CMDNORMAL 0 /* command is an executable program */
7458 #define CMDFUNCTION 1 /* command is a shell function */
7459 #define CMDBUILTIN 2 /* command is a shell builtin */
7461 /* action to find_command() */
7462 #define DO_ERR 0x01 /* prints errors */
7463 #define DO_ABS 0x02 /* checks absolute paths */
7464 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7465 #define DO_ALTPATH 0x08 /* using alternate path */
7466 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7468 static void find_command(char *, struct cmdentry *, int, const char *);
7471 /* ============ Hashing commands */
7474 * When commands are first encountered, they are entered in a hash table.
7475 * This ensures that a full path search will not have to be done for them
7476 * on each invocation.
7478 * We should investigate converting to a linear search, even though that
7479 * would make the command name "hash" a misnomer.
7483 struct tblentry *next; /* next entry in hash chain */
7484 union param param; /* definition of builtin function */
7485 smallint cmdtype; /* CMDxxx */
7486 char rehash; /* if set, cd done since entry created */
7487 char cmdname[1]; /* name of command */
7490 static struct tblentry **cmdtable;
7491 #define INIT_G_cmdtable() do { \
7492 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7495 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7499 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7501 #if ENABLE_FEATURE_SH_STANDALONE
7502 if (applet_no >= 0) {
7503 if (APPLET_IS_NOEXEC(applet_no)) {
7507 run_applet_no_and_exit(applet_no, argv);
7509 /* re-exec ourselves with the new arguments */
7510 execve(bb_busybox_exec_path, argv, envp);
7511 /* If they called chroot or otherwise made the binary no longer
7512 * executable, fall through */
7519 execve(cmd, argv, envp);
7520 } while (errno == EINTR);
7522 execve(cmd, argv, envp);
7524 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7525 /* Run "cmd" as a shell script:
7526 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7527 * "If the execve() function fails with ENOEXEC, the shell
7528 * shall execute a command equivalent to having a shell invoked
7529 * with the command name as its first operand,
7530 * with any remaining arguments passed to the new shell"
7532 * That is, do not use $SHELL, user's shell, or /bin/sh;
7533 * just call ourselves.
7535 * Note that bash reads ~80 chars of the file, and if it sees
7536 * a zero byte before it sees newline, it doesn't try to
7537 * interpret it, but fails with "cannot execute binary file"
7538 * message and exit code 126. For one, this prevents attempts
7539 * to interpret foreign ELF binaries as shell scripts.
7542 cmd = (char*) bb_busybox_exec_path;
7543 /* NB: this is only possible because all callers of shellexec()
7544 * ensure that the argv[-1] slot exists!
7547 argv[0] = (char*) "ash";
7553 * Exec a program. Never returns. If you change this routine, you may
7554 * have to change the find_command routine as well.
7555 * argv[-1] must exist and be writable! See tryexec() for why.
7557 static void shellexec(char **, const char *, int) NORETURN;
7559 shellexec(char **argv, const char *path, int idx)
7565 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7567 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7568 if (strchr(argv[0], '/') != NULL
7569 #if ENABLE_FEATURE_SH_STANDALONE
7570 || (applet_no = find_applet_by_name(argv[0])) >= 0
7573 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7574 if (applet_no >= 0) {
7575 /* We tried execing ourself, but it didn't work.
7576 * Maybe /proc/self/exe doesn't exist?
7585 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7586 if (--idx < 0 && pathopt == NULL) {
7587 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7588 if (errno != ENOENT && errno != ENOTDIR)
7595 /* Map to POSIX errors */
7607 exitstatus = exerrno;
7608 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7609 argv[0], e, suppress_int));
7610 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7615 printentry(struct tblentry *cmdp)
7621 idx = cmdp->param.index;
7624 name = path_advance(&path, cmdp->cmdname);
7626 } while (--idx >= 0);
7627 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7631 * Clear out command entries. The argument specifies the first entry in
7632 * PATH which has changed.
7635 clearcmdentry(int firstchange)
7637 struct tblentry **tblp;
7638 struct tblentry **pp;
7639 struct tblentry *cmdp;
7642 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7644 while ((cmdp = *pp) != NULL) {
7645 if ((cmdp->cmdtype == CMDNORMAL &&
7646 cmdp->param.index >= firstchange)
7647 || (cmdp->cmdtype == CMDBUILTIN &&
7648 builtinloc >= firstchange)
7661 * Locate a command in the command hash table. If "add" is nonzero,
7662 * add the command to the table if it is not already present. The
7663 * variable "lastcmdentry" is set to point to the address of the link
7664 * pointing to the entry, so that delete_cmd_entry can delete the
7667 * Interrupts must be off if called with add != 0.
7669 static struct tblentry **lastcmdentry;
7671 static struct tblentry *
7672 cmdlookup(const char *name, int add)
7674 unsigned int hashval;
7676 struct tblentry *cmdp;
7677 struct tblentry **pp;
7680 hashval = (unsigned char)*p << 4;
7682 hashval += (unsigned char)*p++;
7684 pp = &cmdtable[hashval % CMDTABLESIZE];
7685 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7686 if (strcmp(cmdp->cmdname, name) == 0)
7690 if (add && cmdp == NULL) {
7691 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7693 /* + 1 - already done because
7694 * tblentry::cmdname is char[1] */);
7695 /*cmdp->next = NULL; - ckzalloc did it */
7696 cmdp->cmdtype = CMDUNKNOWN;
7697 strcpy(cmdp->cmdname, name);
7704 * Delete the command entry returned on the last lookup.
7707 delete_cmd_entry(void)
7709 struct tblentry *cmdp;
7712 cmdp = *lastcmdentry;
7713 *lastcmdentry = cmdp->next;
7714 if (cmdp->cmdtype == CMDFUNCTION)
7715 freefunc(cmdp->param.func);
7721 * Add a new command entry, replacing any existing command entry for
7722 * the same name - except special builtins.
7725 addcmdentry(char *name, struct cmdentry *entry)
7727 struct tblentry *cmdp;
7729 cmdp = cmdlookup(name, 1);
7730 if (cmdp->cmdtype == CMDFUNCTION) {
7731 freefunc(cmdp->param.func);
7733 cmdp->cmdtype = entry->cmdtype;
7734 cmdp->param = entry->u;
7738 static int FAST_FUNC
7739 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7741 struct tblentry **pp;
7742 struct tblentry *cmdp;
7744 struct cmdentry entry;
7747 if (nextopt("r") != '\0') {
7752 if (*argptr == NULL) {
7753 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7754 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7755 if (cmdp->cmdtype == CMDNORMAL)
7763 while ((name = *argptr) != NULL) {
7764 cmdp = cmdlookup(name, 0);
7766 && (cmdp->cmdtype == CMDNORMAL
7767 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7771 find_command(name, &entry, DO_ERR, pathval());
7772 if (entry.cmdtype == CMDUNKNOWN)
7780 * Called when a cd is done. Marks all commands so the next time they
7781 * are executed they will be rehashed.
7786 struct tblentry **pp;
7787 struct tblentry *cmdp;
7789 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7790 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7791 if (cmdp->cmdtype == CMDNORMAL
7792 || (cmdp->cmdtype == CMDBUILTIN
7793 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7803 * Fix command hash table when PATH changed.
7804 * Called before PATH is changed. The argument is the new value of PATH;
7805 * pathval() still returns the old value at this point.
7806 * Called with interrupts off.
7808 static void FAST_FUNC
7809 changepath(const char *new)
7817 firstchange = 9999; /* assume no change */
7823 if ((*old == '\0' && *new == ':')
7824 || (*old == ':' && *new == '\0')
7828 old = new; /* ignore subsequent differences */
7832 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7839 if (builtinloc < 0 && idx_bltin >= 0)
7840 builtinloc = idx_bltin; /* zap builtins */
7841 if (builtinloc >= 0 && idx_bltin < 0)
7843 clearcmdentry(firstchange);
7844 builtinloc = idx_bltin;
7869 #if ENABLE_ASH_BASH_COMPAT
7880 typedef smallint token_id_t;
7882 /* Nth bit indicates if token marks the end of a list */
7885 /* 0 */ | (1u << TEOF)
7886 /* 1 */ | (0u << TNL)
7887 /* 2 */ | (0u << TREDIR)
7888 /* 3 */ | (0u << TWORD)
7889 /* 4 */ | (0u << TSEMI)
7890 /* 5 */ | (0u << TBACKGND)
7891 /* 6 */ | (0u << TAND)
7892 /* 7 */ | (0u << TOR)
7893 /* 8 */ | (0u << TPIPE)
7894 /* 9 */ | (0u << TLP)
7895 /* 10 */ | (1u << TRP)
7896 /* 11 */ | (1u << TENDCASE)
7897 /* 12 */ | (1u << TENDBQUOTE)
7898 /* 13 */ | (0u << TNOT)
7899 /* 14 */ | (0u << TCASE)
7900 /* 15 */ | (1u << TDO)
7901 /* 16 */ | (1u << TDONE)
7902 /* 17 */ | (1u << TELIF)
7903 /* 18 */ | (1u << TELSE)
7904 /* 19 */ | (1u << TESAC)
7905 /* 20 */ | (1u << TFI)
7906 /* 21 */ | (0u << TFOR)
7907 #if ENABLE_ASH_BASH_COMPAT
7908 /* 22 */ | (0u << TFUNCTION)
7910 /* 23 */ | (0u << TIF)
7911 /* 24 */ | (0u << TIN)
7912 /* 25 */ | (1u << TTHEN)
7913 /* 26 */ | (0u << TUNTIL)
7914 /* 27 */ | (0u << TWHILE)
7915 /* 28 */ | (0u << TBEGIN)
7916 /* 29 */ | (1u << TEND)
7917 , /* thus far 29 bits used */
7920 static const char *const tokname_array[] = {
7934 #define KWDOFFSET 13
7935 /* the following are keywords */
7945 #if ENABLE_ASH_BASH_COMPAT
7957 /* Wrapper around strcmp for qsort/bsearch/... */
7959 pstrcmp(const void *a, const void *b)
7961 return strcmp((char*)a, *(char**)b);
7964 static const char *const *
7965 findkwd(const char *s)
7967 return bsearch(s, tokname_array + KWDOFFSET,
7968 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7969 sizeof(tokname_array[0]), pstrcmp);
7973 * Locate and print what a word is...
7976 describe_command(char *command, const char *path, int describe_command_verbose)
7978 struct cmdentry entry;
7979 struct tblentry *cmdp;
7980 #if ENABLE_ASH_ALIAS
7981 const struct alias *ap;
7984 path = path ? path : pathval();
7986 if (describe_command_verbose) {
7990 /* First look at the keywords */
7991 if (findkwd(command)) {
7992 out1str(describe_command_verbose ? " is a shell keyword" : command);
7996 #if ENABLE_ASH_ALIAS
7997 /* Then look at the aliases */
7998 ap = lookupalias(command, 0);
8000 if (!describe_command_verbose) {
8005 out1fmt(" is an alias for %s", ap->val);
8009 /* Then check if it is a tracked alias */
8010 cmdp = cmdlookup(command, 0);
8012 entry.cmdtype = cmdp->cmdtype;
8013 entry.u = cmdp->param;
8015 /* Finally use brute force */
8016 find_command(command, &entry, DO_ABS, path);
8019 switch (entry.cmdtype) {
8021 int j = entry.u.index;
8027 p = path_advance(&path, command);
8031 if (describe_command_verbose) {
8033 (cmdp ? " a tracked alias for" : nullstr), p
8042 if (describe_command_verbose) {
8043 out1str(" is a shell function");
8050 if (describe_command_verbose) {
8051 out1fmt(" is a %sshell builtin",
8052 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8053 "special " : nullstr
8061 if (describe_command_verbose) {
8062 out1str(": not found\n");
8071 static int FAST_FUNC
8072 typecmd(int argc UNUSED_PARAM, char **argv)
8078 /* type -p ... ? (we don't bother checking for 'p') */
8079 if (argv[1] && argv[1][0] == '-') {
8084 err |= describe_command(argv[i++], NULL, verbose);
8089 #if ENABLE_ASH_CMDCMD
8090 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8092 parse_command_args(char **argv, const char **path)
8105 if (c == '-' && !*cp) {
8113 *path = bb_default_path;
8116 /* run 'typecmd' for other options */
8125 static int FAST_FUNC
8126 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8134 const char *path = NULL;
8136 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8137 * never reaches this function.
8140 while ((c = nextopt("pvV")) != '\0')
8142 verify |= VERIFY_VERBOSE;
8144 /*verify |= VERIFY_BRIEF*/;
8150 path = bb_default_path;
8152 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8154 if (/*verify && */ cmd)
8155 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8162 /*static int funcblocksize; // size of structures in function */
8163 /*static int funcstringsize; // size of strings in node */
8164 static void *funcblock; /* block to allocate function from */
8165 static char *funcstring_end; /* end of block to allocate strings from */
8167 /* flags in argument to evaltree */
8168 #define EV_EXIT 01 /* exit after evaluating tree */
8169 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8171 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8172 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8173 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8174 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8175 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8176 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8177 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8178 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8179 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8180 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8181 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8182 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8183 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8184 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8185 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8186 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8187 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8188 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8189 #if ENABLE_ASH_BASH_COMPAT
8190 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8192 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8193 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8194 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8195 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8196 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8197 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8198 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8199 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8200 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8203 static int calcsize(int funcblocksize, union node *n);
8206 sizenodelist(int funcblocksize, struct nodelist *lp)
8209 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8210 funcblocksize = calcsize(funcblocksize, lp->n);
8213 return funcblocksize;
8217 calcsize(int funcblocksize, union node *n)
8220 return funcblocksize;
8221 funcblocksize += nodesize[n->type];
8224 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8225 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8226 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8229 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8234 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8235 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8242 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8243 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8246 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8247 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8248 funcblocksize = calcsize(funcblocksize, n->nif.test);
8251 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8252 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8253 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8256 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8257 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8260 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8261 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8262 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8266 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8267 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8268 funcblocksize = calcsize(funcblocksize, n->narg.next);
8271 #if ENABLE_ASH_BASH_COMPAT
8278 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8279 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8283 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8284 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8288 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8289 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8292 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8295 return funcblocksize;
8299 nodeckstrdup(char *s)
8301 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8302 return strcpy(funcstring_end, s);
8305 static union node *copynode(union node *);
8307 static struct nodelist *
8308 copynodelist(struct nodelist *lp)
8310 struct nodelist *start;
8311 struct nodelist **lpp;
8316 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8317 (*lpp)->n = copynode(lp->n);
8319 lpp = &(*lpp)->next;
8326 copynode(union node *n)
8333 funcblock = (char *) funcblock + nodesize[n->type];
8337 new->ncmd.redirect = copynode(n->ncmd.redirect);
8338 new->ncmd.args = copynode(n->ncmd.args);
8339 new->ncmd.assign = copynode(n->ncmd.assign);
8342 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8343 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8348 new->nredir.redirect = copynode(n->nredir.redirect);
8349 new->nredir.n = copynode(n->nredir.n);
8356 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8357 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8360 new->nif.elsepart = copynode(n->nif.elsepart);
8361 new->nif.ifpart = copynode(n->nif.ifpart);
8362 new->nif.test = copynode(n->nif.test);
8365 new->nfor.var = nodeckstrdup(n->nfor.var);
8366 new->nfor.body = copynode(n->nfor.body);
8367 new->nfor.args = copynode(n->nfor.args);
8370 new->ncase.cases = copynode(n->ncase.cases);
8371 new->ncase.expr = copynode(n->ncase.expr);
8374 new->nclist.body = copynode(n->nclist.body);
8375 new->nclist.pattern = copynode(n->nclist.pattern);
8376 new->nclist.next = copynode(n->nclist.next);
8380 new->narg.backquote = copynodelist(n->narg.backquote);
8381 new->narg.text = nodeckstrdup(n->narg.text);
8382 new->narg.next = copynode(n->narg.next);
8385 #if ENABLE_ASH_BASH_COMPAT
8392 new->nfile.fname = copynode(n->nfile.fname);
8393 new->nfile.fd = n->nfile.fd;
8394 new->nfile.next = copynode(n->nfile.next);
8398 new->ndup.vname = copynode(n->ndup.vname);
8399 new->ndup.dupfd = n->ndup.dupfd;
8400 new->ndup.fd = n->ndup.fd;
8401 new->ndup.next = copynode(n->ndup.next);
8405 new->nhere.doc = copynode(n->nhere.doc);
8406 new->nhere.fd = n->nhere.fd;
8407 new->nhere.next = copynode(n->nhere.next);
8410 new->nnot.com = copynode(n->nnot.com);
8413 new->type = n->type;
8418 * Make a copy of a parse tree.
8420 static struct funcnode *
8421 copyfunc(union node *n)
8426 /*funcstringsize = 0;*/
8427 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8428 f = ckzalloc(blocksize /* + funcstringsize */);
8429 funcblock = (char *) f + offsetof(struct funcnode, n);
8430 funcstring_end = (char *) f + blocksize;
8432 /* f->count = 0; - ckzalloc did it */
8437 * Define a shell function.
8440 defun(union node *func)
8442 struct cmdentry entry;
8445 entry.cmdtype = CMDFUNCTION;
8446 entry.u.func = copyfunc(func);
8447 addcmdentry(func->narg.text, &entry);
8451 /* Reasons for skipping commands (see comment on breakcmd routine) */
8452 #define SKIPBREAK (1 << 0)
8453 #define SKIPCONT (1 << 1)
8454 #define SKIPFUNC (1 << 2)
8455 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8456 static int skipcount; /* number of levels to skip */
8457 static int funcnest; /* depth of function calls */
8458 static int loopnest; /* current loop nesting level */
8460 /* Forward decl way out to parsing code - dotrap needs it */
8461 static int evalstring(char *s, int flags);
8463 /* Called to execute a trap.
8464 * Single callsite - at the end of evaltree().
8465 * If we return non-zero, evaltree raises EXEXIT exception.
8467 * Perhaps we should avoid entering new trap handlers
8468 * while we are executing a trap handler. [is it a TODO?]
8475 uint8_t last_status;
8480 last_status = exitstatus;
8484 TRACE(("dotrap entered\n"));
8485 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8497 /* non-trapped SIGINT is handled separately by raise_interrupt,
8498 * don't upset it by resetting gotsig[SIGINT-1] */
8499 if (sig == SIGINT && !p)
8502 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8508 exitstatus = last_status;
8509 TRACE(("dotrap returns\n"));
8512 /* forward declarations - evaluation is fairly recursive business... */
8513 static int evalloop(union node *, int);
8514 static int evalfor(union node *, int);
8515 static int evalcase(union node *, int);
8516 static int evalsubshell(union node *, int);
8517 static void expredir(union node *);
8518 static int evalpipe(union node *, int);
8519 static int evalcommand(union node *, int);
8520 static int evalbltin(const struct builtincmd *, int, char **, int);
8521 static void prehash(union node *);
8524 * Evaluate a parse tree. The value is left in the global variable
8528 evaltree(union node *n, int flags)
8531 int (*evalfn)(union node *, int);
8535 TRACE(("evaltree(NULL) called\n"));
8538 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8545 out1fmt("Node type = %d\n", n->type);
8550 status = !evaltree(n->nnot.com, EV_TESTED);
8553 expredir(n->nredir.redirect);
8554 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8556 status = evaltree(n->nredir.n, flags & EV_TESTED);
8558 if (n->nredir.redirect)
8559 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8562 evalfn = evalcommand;
8564 if (eflag && !(flags & EV_TESTED))
8576 evalfn = evalsubshell;
8589 #error NAND + 1 != NOR
8591 #if NOR + 1 != NSEMI
8592 #error NOR + 1 != NSEMI
8594 unsigned is_or = n->type - NAND;
8597 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8599 if ((!status) == is_or || evalskip)
8605 status = evalfn(n, flags);
8609 status = evaltree(n->nif.test, EV_TESTED);
8616 if (n->nif.elsepart) {
8617 n = n->nif.elsepart;
8624 /* Not necessary. To test it:
8625 * "false; f() { qwerty; }; echo $?" should print 0.
8629 exitstatus = status;
8633 /* Order of checks below is important:
8634 * signal handlers trigger before exit caused by "set -e".
8638 if (checkexit & status)
8639 raise_exception(EXEXIT);
8640 if (flags & EV_EXIT)
8641 raise_exception(EXEXIT);
8643 TRACE(("leaving evaltree (no interrupts)\n"));
8647 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8650 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8655 int skip = evalskip;
8662 if (--skipcount <= 0) {
8673 evalloop(union node *n, int flags)
8684 i = evaltree(n->nbinary.ch1, EV_TESTED);
8686 if (skip == SKIPFUNC)
8690 if (n->type != NWHILE)
8694 status = evaltree(n->nbinary.ch2, flags);
8696 } while (!(skip & ~SKIPCONT));
8703 evalfor(union node *n, int flags)
8705 struct arglist arglist;
8708 struct stackmark smark;
8711 setstackmark(&smark);
8712 arglist.list = NULL;
8713 arglist.lastp = &arglist.list;
8714 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8715 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8717 *arglist.lastp = NULL;
8721 for (sp = arglist.list; sp; sp = sp->next) {
8722 setvar0(n->nfor.var, sp->text);
8723 status = evaltree(n->nfor.body, flags);
8724 if (skiploop() & ~SKIPCONT)
8728 popstackmark(&smark);
8734 evalcase(union node *n, int flags)
8738 struct arglist arglist;
8739 struct stackmark smark;
8742 setstackmark(&smark);
8743 arglist.list = NULL;
8744 arglist.lastp = &arglist.list;
8745 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8746 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8747 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8748 if (casematch(patp, arglist.list->text)) {
8749 /* Ensure body is non-empty as otherwise
8750 * EV_EXIT may prevent us from setting the
8753 if (evalskip == 0 && cp->nclist.body) {
8754 status = evaltree(cp->nclist.body, flags);
8761 popstackmark(&smark);
8767 * Kick off a subshell to evaluate a tree.
8770 evalsubshell(union node *n, int flags)
8773 int backgnd = (n->type == NBACKGND);
8776 expredir(n->nredir.redirect);
8777 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8780 jp = makejob(/*n,*/ 1);
8781 if (forkshell(jp, n, backgnd) == 0) {
8786 flags &= ~EV_TESTED;
8788 redirect(n->nredir.redirect, 0);
8789 evaltreenr(n->nredir.n, flags);
8795 status = waitforjob(jp);
8801 * Compute the names of the files in a redirection list.
8803 static void fixredir(union node *, const char *, int);
8805 expredir(union node *n)
8809 for (redir = n; redir; redir = redir->nfile.next) {
8813 fn.lastp = &fn.list;
8814 switch (redir->type) {
8818 #if ENABLE_ASH_BASH_COMPAT
8823 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8824 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8825 #if ENABLE_ASH_BASH_COMPAT
8829 // By the design of stack allocator, the loop of this kind:
8830 // while true; do while true; do break; done </dev/null; done
8831 // will look like a memory leak: ash plans to free expfname's
8832 // of "/dev/null" as soon as it finishes running the loop
8833 // (in this case, never).
8834 // This "fix" is wrong:
8835 if (redir->nfile.expfname)
8836 stunalloc(redir->nfile.expfname);
8837 // It results in corrupted state of stacked allocations.
8839 redir->nfile.expfname = fn.list->text;
8842 case NTOFD: /* >& */
8843 if (redir->ndup.vname) {
8844 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8845 if (fn.list == NULL)
8846 ash_msg_and_raise_error("redir error");
8847 #if ENABLE_ASH_BASH_COMPAT
8848 //FIXME: we used expandarg with different args!
8849 if (!isdigit_str9(fn.list->text)) {
8850 /* >&file, not >&fd */
8851 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8852 ash_msg_and_raise_error("redir error");
8854 goto store_expfname;
8857 fixredir(redir, fn.list->text, 1);
8865 * Evaluate a pipeline. All the processes in the pipeline are children
8866 * of the process creating the pipeline. (This differs from some versions
8867 * of the shell, which make the last process in a pipeline the parent
8871 evalpipe(union node *n, int flags)
8874 struct nodelist *lp;
8880 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8882 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8886 jp = makejob(/*n,*/ pipelen);
8888 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8892 if (pipe(pip) < 0) {
8894 ash_msg_and_raise_error("pipe call failed");
8897 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8911 evaltreenr(lp->n, flags);
8918 /* Don't want to trigger debugging */
8922 if (n->npipe.pipe_backgnd == 0) {
8923 status = waitforjob(jp);
8924 TRACE(("evalpipe: job done exit status %d\n", status));
8932 * Controls whether the shell is interactive or not.
8935 setinteractive(int on)
8937 static smallint is_interactive;
8939 if (++on == is_interactive)
8941 is_interactive = on;
8945 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8946 if (is_interactive > 1) {
8947 /* Looks like they want an interactive shell */
8948 static smallint did_banner;
8951 /* note: ash and hush share this string */
8952 out1fmt("\n\n%s %s\n"
8953 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8956 "built-in shell (ash)"
8970 setinteractive(iflag);
8972 #if ENABLE_FEATURE_EDITING_VI
8974 line_input_state->flags |= VI_MODE;
8976 line_input_state->flags &= ~VI_MODE;
8978 viflag = 0; /* forcibly keep the option off */
8982 static struct localvar *localvars;
8985 * Called after a function returns.
8986 * Interrupts must be off.
8991 struct localvar *lvp;
8994 while ((lvp = localvars) != NULL) {
8995 localvars = lvp->next;
8997 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
8998 if (vp == NULL) { /* $- saved */
8999 memcpy(optlist, lvp->text, sizeof(optlist));
9000 free((char*)lvp->text);
9002 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9003 unsetvar(vp->var_text);
9006 vp->var_func(var_end(lvp->text));
9007 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9008 free((char*)vp->var_text);
9009 vp->flags = lvp->flags;
9010 vp->var_text = lvp->text;
9017 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9019 volatile struct shparam saveparam;
9020 struct localvar *volatile savelocalvars;
9021 struct jmploc *volatile savehandler;
9022 struct jmploc jmploc;
9025 saveparam = shellparam;
9026 savelocalvars = localvars;
9027 savehandler = exception_handler;
9028 e = setjmp(jmploc.loc);
9033 exception_handler = &jmploc;
9035 shellparam.malloced = 0;
9039 shellparam.nparam = argc - 1;
9040 shellparam.p = argv + 1;
9041 #if ENABLE_ASH_GETOPTS
9042 shellparam.optind = 1;
9043 shellparam.optoff = -1;
9045 evaltree(func->n.narg.next, flags & EV_TESTED);
9051 localvars = savelocalvars;
9052 freeparam(&shellparam);
9053 shellparam = saveparam;
9054 exception_handler = savehandler;
9056 evalskip &= ~SKIPFUNC;
9061 * Make a variable a local variable. When a variable is made local, it's
9062 * value and flags are saved in a localvar structure. The saved values
9063 * will be restored when the shell function returns. We handle the name
9064 * "-" as a special case: it makes changes to "set +-options" local
9065 * (options will be restored on return from the function).
9070 struct localvar *lvp;
9073 char *eq = strchr(name, '=');
9076 /* Cater for duplicate "local". Examples:
9077 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9078 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9082 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9086 * it's a duplicate "local VAR" declaration, do nothing
9093 lvp = ckzalloc(sizeof(*lvp));
9094 if (LONE_DASH(name)) {
9096 p = ckmalloc(sizeof(optlist));
9097 lvp->text = memcpy(p, optlist, sizeof(optlist));
9100 vpp = hashvar(name);
9101 vp = *findvar(vpp, name);
9103 /* variable did not exist yet */
9105 setvareq(name, VSTRFIXED);
9107 setvar(name, NULL, VSTRFIXED);
9108 vp = *vpp; /* the new variable */
9109 lvp->flags = VUNSET;
9111 lvp->text = vp->var_text;
9112 lvp->flags = vp->flags;
9113 /* make sure neither "struct var" nor string gets freed
9114 * during (un)setting:
9116 vp->flags |= VSTRFIXED|VTEXTFIXED;
9120 /* "local VAR" unsets VAR: */
9121 setvar0(name, NULL);
9125 lvp->next = localvars;
9131 * The "local" command.
9133 static int FAST_FUNC
9134 localcmd(int argc UNUSED_PARAM, char **argv)
9139 ash_msg_and_raise_error("not in a function");
9142 while ((name = *argv++) != NULL) {
9148 static int FAST_FUNC
9149 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9154 static int FAST_FUNC
9155 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9160 static int FAST_FUNC
9161 execcmd(int argc UNUSED_PARAM, char **argv)
9164 iflag = 0; /* exit on error */
9167 /* We should set up signals for "exec CMD"
9168 * the same way as for "CMD" without "exec".
9169 * But optschanged->setinteractive->setsignal
9170 * still thought we are a root shell. Therefore, for example,
9171 * SIGQUIT is still set to IGN. Fix it:
9175 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9176 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9177 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9179 shellexec(argv + 1, pathval(), 0);
9186 * The return command.
9188 static int FAST_FUNC
9189 returncmd(int argc UNUSED_PARAM, char **argv)
9192 * If called outside a function, do what ksh does;
9193 * skip the rest of the file.
9195 evalskip = SKIPFUNC;
9196 return argv[1] ? number(argv[1]) : exitstatus;
9199 /* Forward declarations for builtintab[] */
9200 static int breakcmd(int, char **) FAST_FUNC;
9201 static int dotcmd(int, char **) FAST_FUNC;
9202 static int evalcmd(int, char **, int) FAST_FUNC;
9203 static int exitcmd(int, char **) FAST_FUNC;
9204 static int exportcmd(int, char **) FAST_FUNC;
9205 #if ENABLE_ASH_GETOPTS
9206 static int getoptscmd(int, char **) FAST_FUNC;
9209 static int helpcmd(int, char **) FAST_FUNC;
9212 static int historycmd(int, char **) FAST_FUNC;
9214 #if ENABLE_SH_MATH_SUPPORT
9215 static int letcmd(int, char **) FAST_FUNC;
9217 static int readcmd(int, char **) FAST_FUNC;
9218 static int setcmd(int, char **) FAST_FUNC;
9219 static int shiftcmd(int, char **) FAST_FUNC;
9220 static int timescmd(int, char **) FAST_FUNC;
9221 static int trapcmd(int, char **) FAST_FUNC;
9222 static int umaskcmd(int, char **) FAST_FUNC;
9223 static int unsetcmd(int, char **) FAST_FUNC;
9224 static int ulimitcmd(int, char **) FAST_FUNC;
9226 #define BUILTIN_NOSPEC "0"
9227 #define BUILTIN_SPECIAL "1"
9228 #define BUILTIN_REGULAR "2"
9229 #define BUILTIN_SPEC_REG "3"
9230 #define BUILTIN_ASSIGN "4"
9231 #define BUILTIN_SPEC_ASSG "5"
9232 #define BUILTIN_REG_ASSG "6"
9233 #define BUILTIN_SPEC_REG_ASSG "7"
9235 /* Stubs for calling non-FAST_FUNC's */
9236 #if ENABLE_ASH_BUILTIN_ECHO
9237 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9239 #if ENABLE_ASH_BUILTIN_PRINTF
9240 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9242 #if ENABLE_ASH_BUILTIN_TEST
9243 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9246 /* Keep these in proper order since it is searched via bsearch() */
9247 static const struct builtincmd builtintab[] = {
9248 { BUILTIN_SPEC_REG "." , dotcmd },
9249 { BUILTIN_SPEC_REG ":" , truecmd },
9250 #if ENABLE_ASH_BUILTIN_TEST
9251 { BUILTIN_REGULAR "[" , testcmd },
9252 #if ENABLE_ASH_BASH_COMPAT
9253 { BUILTIN_REGULAR "[[" , testcmd },
9256 #if ENABLE_ASH_ALIAS
9257 { BUILTIN_REG_ASSG "alias" , aliascmd },
9260 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9262 { BUILTIN_SPEC_REG "break" , breakcmd },
9263 { BUILTIN_REGULAR "cd" , cdcmd },
9264 { BUILTIN_NOSPEC "chdir" , cdcmd },
9265 #if ENABLE_ASH_CMDCMD
9266 { BUILTIN_REGULAR "command" , commandcmd },
9268 { BUILTIN_SPEC_REG "continue", breakcmd },
9269 #if ENABLE_ASH_BUILTIN_ECHO
9270 { BUILTIN_REGULAR "echo" , echocmd },
9272 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9273 { BUILTIN_SPEC_REG "exec" , execcmd },
9274 { BUILTIN_SPEC_REG "exit" , exitcmd },
9275 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9276 { BUILTIN_REGULAR "false" , falsecmd },
9278 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9280 #if ENABLE_ASH_GETOPTS
9281 { BUILTIN_REGULAR "getopts" , getoptscmd },
9283 { BUILTIN_NOSPEC "hash" , hashcmd },
9285 { BUILTIN_NOSPEC "help" , helpcmd },
9288 { BUILTIN_NOSPEC "history" , historycmd },
9291 { BUILTIN_REGULAR "jobs" , jobscmd },
9292 { BUILTIN_REGULAR "kill" , killcmd },
9294 #if ENABLE_SH_MATH_SUPPORT
9295 { BUILTIN_NOSPEC "let" , letcmd },
9297 { BUILTIN_ASSIGN "local" , localcmd },
9298 #if ENABLE_ASH_BUILTIN_PRINTF
9299 { BUILTIN_REGULAR "printf" , printfcmd },
9301 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9302 { BUILTIN_REGULAR "read" , readcmd },
9303 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9304 { BUILTIN_SPEC_REG "return" , returncmd },
9305 { BUILTIN_SPEC_REG "set" , setcmd },
9306 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9307 #if ENABLE_ASH_BASH_COMPAT
9308 { BUILTIN_SPEC_REG "source" , dotcmd },
9310 #if ENABLE_ASH_BUILTIN_TEST
9311 { BUILTIN_REGULAR "test" , testcmd },
9313 { BUILTIN_SPEC_REG "times" , timescmd },
9314 { BUILTIN_SPEC_REG "trap" , trapcmd },
9315 { BUILTIN_REGULAR "true" , truecmd },
9316 { BUILTIN_NOSPEC "type" , typecmd },
9317 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9318 { BUILTIN_REGULAR "umask" , umaskcmd },
9319 #if ENABLE_ASH_ALIAS
9320 { BUILTIN_REGULAR "unalias" , unaliascmd },
9322 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9323 { BUILTIN_REGULAR "wait" , waitcmd },
9326 /* Should match the above table! */
9327 #define COMMANDCMD (builtintab + \
9329 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9330 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9331 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9332 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9333 /* break cd cddir */ 3)
9334 #define EVALCMD (COMMANDCMD + \
9335 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9336 /* continue */ 1 + \
9337 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9339 #define EXECCMD (EVALCMD + \
9343 * Search the table of builtin commands.
9346 pstrcmp1(const void *a, const void *b)
9348 return strcmp((char*)a, *(char**)b + 1);
9350 static struct builtincmd *
9351 find_builtin(const char *name)
9353 struct builtincmd *bp;
9356 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9363 * Execute a simple command.
9366 isassignment(const char *p)
9368 const char *q = endofname(p);
9373 static int FAST_FUNC
9374 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9376 /* Preserve exitstatus of a previous possible redirection
9377 * as POSIX mandates */
9378 return back_exitstatus;
9381 evalcommand(union node *cmd, int flags)
9383 static const struct builtincmd null_bltin = {
9384 "\0\0", bltincmd /* why three NULs? */
9386 struct stackmark smark;
9388 struct arglist arglist;
9389 struct arglist varlist;
9392 const struct strlist *sp;
9393 struct cmdentry cmdentry;
9400 struct builtincmd *bcmd;
9401 smallint cmd_is_exec;
9402 smallint pseudovarflag = 0;
9404 /* First expand the arguments. */
9405 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9406 setstackmark(&smark);
9407 back_exitstatus = 0;
9409 cmdentry.cmdtype = CMDBUILTIN;
9410 cmdentry.u.cmd = &null_bltin;
9411 varlist.lastp = &varlist.list;
9412 *varlist.lastp = NULL;
9413 arglist.lastp = &arglist.list;
9414 *arglist.lastp = NULL;
9417 if (cmd->ncmd.args) {
9418 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9419 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9422 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9423 struct strlist **spp;
9425 spp = arglist.lastp;
9426 if (pseudovarflag && isassignment(argp->narg.text))
9427 expandarg(argp, &arglist, EXP_VARTILDE);
9429 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9431 for (sp = *spp; sp; sp = sp->next)
9435 /* Reserve one extra spot at the front for shellexec. */
9436 nargv = stalloc(sizeof(char *) * (argc + 2));
9438 for (sp = arglist.list; sp; sp = sp->next) {
9439 TRACE(("evalcommand arg: %s\n", sp->text));
9440 *nargv++ = sp->text;
9445 if (iflag && funcnest == 0 && argc > 0)
9446 lastarg = nargv[-1];
9449 expredir(cmd->ncmd.redirect);
9450 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9452 path = vpath.var_text;
9453 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9454 struct strlist **spp;
9457 spp = varlist.lastp;
9458 expandarg(argp, &varlist, EXP_VARTILDE);
9461 * Modify the command lookup path, if a PATH= assignment
9465 if (varcmp(p, path) == 0)
9469 /* Print the command if xflag is set. */
9472 const char *p = " %s" + 1;
9474 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9476 for (n = 0; n < 2; n++) {
9478 fdprintf(preverrout_fd, p, sp->text);
9484 safe_write(preverrout_fd, "\n", 1);
9490 /* Now locate the command. */
9492 int cmd_flag = DO_ERR;
9493 #if ENABLE_ASH_CMDCMD
9494 const char *oldpath = path + 5;
9498 find_command(argv[0], &cmdentry, cmd_flag, path);
9499 if (cmdentry.cmdtype == CMDUNKNOWN) {
9500 flush_stdout_stderr();
9505 /* implement bltin and command here */
9506 if (cmdentry.cmdtype != CMDBUILTIN)
9509 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9510 if (cmdentry.u.cmd == EXECCMD)
9512 #if ENABLE_ASH_CMDCMD
9513 if (cmdentry.u.cmd == COMMANDCMD) {
9515 nargv = parse_command_args(argv, &path);
9518 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9519 * nargv => "PROG". path is updated if -p.
9521 argc -= nargv - argv;
9523 cmd_flag |= DO_NOFUNC;
9531 /* We have a redirection error. */
9533 raise_exception(EXERROR);
9535 exitstatus = status;
9539 /* Execute the command. */
9540 switch (cmdentry.cmdtype) {
9543 #if ENABLE_FEATURE_SH_NOFORK
9544 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9545 * around run_nofork_applet() call.
9546 * (2) Should this check also be done in forkshell()?
9547 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9549 /* find_command() encodes applet_no as (-2 - applet_no) */
9550 int applet_no = (- cmdentry.u.index - 2);
9551 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9552 listsetvar(varlist.list, VEXPORT|VSTACK);
9553 /* run <applet>_main() */
9554 status = run_nofork_applet(applet_no, argv);
9558 /* Can we avoid forking off? For example, very last command
9559 * in a script or a subshell does not need forking,
9560 * we can just exec it.
9562 if (!(flags & EV_EXIT) || may_have_traps) {
9563 /* No, forking off a child is necessary */
9565 jp = makejob(/*cmd,*/ 1);
9566 if (forkshell(jp, cmd, FORK_FG) != 0) {
9568 status = waitforjob(jp);
9570 TRACE(("forked child exited with %d\n", status));
9575 /* fall through to exec'ing external program */
9577 listsetvar(varlist.list, VEXPORT|VSTACK);
9578 shellexec(argv, path, cmdentry.u.index);
9582 cmdenviron = varlist.list;
9584 struct strlist *list = cmdenviron;
9586 if (spclbltin > 0 || argc == 0) {
9588 if (cmd_is_exec && argc > 1)
9591 listsetvar(list, i);
9593 /* Tight loop with builtins only:
9594 * "while kill -0 $child; do true; done"
9595 * will never exit even if $child died, unless we do this
9596 * to reap the zombie and make kill detect that it's gone: */
9597 dowait(DOWAIT_NONBLOCK, NULL);
9599 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9600 if (exception_type == EXERROR && spclbltin <= 0) {
9605 longjmp(exception_handler->loc, 1);
9610 listsetvar(varlist.list, 0);
9611 /* See above for the rationale */
9612 dowait(DOWAIT_NONBLOCK, NULL);
9613 if (evalfun(cmdentry.u.func, argc, argv, flags))
9616 status = exitstatus;
9621 if (cmd->ncmd.redirect)
9622 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9624 /* dsl: I think this is intended to be used to support
9625 * '_' in 'vi' command mode during line editing...
9626 * However I implemented that within libedit itself.
9628 setvar0("_", lastarg);
9630 popstackmark(&smark);
9636 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9638 char *volatile savecmdname;
9639 struct jmploc *volatile savehandler;
9640 struct jmploc jmploc;
9644 savecmdname = commandname;
9645 savehandler = exception_handler;
9646 i = setjmp(jmploc.loc);
9649 exception_handler = &jmploc;
9650 commandname = argv[0];
9652 optptr = NULL; /* initialize nextopt */
9654 status = evalcmd(argc, argv, flags);
9656 status = (*cmd->builtin)(argc, argv);
9657 flush_stdout_stderr();
9658 status |= ferror(stdout);
9659 exitstatus = status;
9662 commandname = savecmdname;
9663 exception_handler = savehandler;
9669 goodname(const char *p)
9671 return endofname(p)[0] == '\0';
9676 * Search for a command. This is called before we fork so that the
9677 * location of the command will be available in the parent as well as
9678 * the child. The check for "goodname" is an overly conservative
9679 * check that the name will not be subject to expansion.
9682 prehash(union node *n)
9684 struct cmdentry entry;
9686 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9687 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9691 /* ============ Builtin commands
9693 * Builtin commands whose functions are closely tied to evaluation
9694 * are implemented here.
9698 * Handle break and continue commands. Break, continue, and return are
9699 * all handled by setting the evalskip flag. The evaluation routines
9700 * above all check this flag, and if it is set they start skipping
9701 * commands rather than executing them. The variable skipcount is
9702 * the number of loops to break/continue, or the number of function
9703 * levels to return. (The latter is always 1.) It should probably
9704 * be an error to break out of more loops than exist, but it isn't
9705 * in the standard shell so we don't make it one here.
9707 static int FAST_FUNC
9708 breakcmd(int argc UNUSED_PARAM, char **argv)
9710 int n = argv[1] ? number(argv[1]) : 1;
9713 ash_msg_and_raise_error(msg_illnum, argv[1]);
9717 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9725 * This implements the input routines used by the parser.
9729 INPUT_PUSH_FILE = 1,
9730 INPUT_NOFILE_OK = 2,
9733 static smallint checkkwd;
9734 /* values of checkkwd variable */
9735 #define CHKALIAS 0x1
9740 * Push a string back onto the input at this current parsefile level.
9741 * We handle aliases this way.
9743 #if !ENABLE_ASH_ALIAS
9744 #define pushstring(s, ap) pushstring(s)
9747 pushstring(char *s, struct alias *ap)
9754 if (g_parsefile->strpush) {
9755 sp = ckzalloc(sizeof(*sp));
9756 sp->prev = g_parsefile->strpush;
9758 sp = &(g_parsefile->basestrpush);
9760 g_parsefile->strpush = sp;
9761 sp->prev_string = g_parsefile->next_to_pgetc;
9762 sp->prev_left_in_line = g_parsefile->left_in_line;
9763 sp->unget = g_parsefile->unget;
9764 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9765 #if ENABLE_ASH_ALIAS
9768 ap->flag |= ALIASINUSE;
9772 g_parsefile->next_to_pgetc = s;
9773 g_parsefile->left_in_line = len;
9774 g_parsefile->unget = 0;
9781 struct strpush *sp = g_parsefile->strpush;
9784 #if ENABLE_ASH_ALIAS
9786 if (g_parsefile->next_to_pgetc[-1] == ' '
9787 || g_parsefile->next_to_pgetc[-1] == '\t'
9789 checkkwd |= CHKALIAS;
9791 if (sp->string != sp->ap->val) {
9794 sp->ap->flag &= ~ALIASINUSE;
9795 if (sp->ap->flag & ALIASDEAD) {
9796 unalias(sp->ap->name);
9800 g_parsefile->next_to_pgetc = sp->prev_string;
9801 g_parsefile->left_in_line = sp->prev_left_in_line;
9802 g_parsefile->unget = sp->unget;
9803 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9804 g_parsefile->strpush = sp->prev;
9805 if (sp != &(g_parsefile->basestrpush))
9814 char *buf = g_parsefile->buf;
9816 g_parsefile->next_to_pgetc = buf;
9817 #if ENABLE_FEATURE_EDITING
9819 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9820 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9823 # if ENABLE_ASH_IDLE_TIMEOUT
9825 const char *tmout_var = lookupvar("TMOUT");
9827 timeout = atoi(tmout_var) * 1000;
9833 # if ENABLE_FEATURE_TAB_COMPLETION
9834 line_input_state->path_lookup = pathval();
9836 reinit_unicode_for_ash();
9837 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9839 /* Ctrl+C pressed */
9850 /* Ctrl+D pressed */
9853 # if ENABLE_ASH_IDLE_TIMEOUT
9854 else if (errno == EAGAIN && timeout > 0) {
9855 puts("\007timed out waiting for input: auto-logout");
9862 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9865 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9867 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9868 int flags = fcntl(0, F_GETFL);
9869 if (flags >= 0 && (flags & O_NONBLOCK)) {
9870 flags &= ~O_NONBLOCK;
9871 if (fcntl(0, F_SETFL, flags) >= 0) {
9872 out2str("sh: turning off NDELAY mode\n");
9883 * Refill the input buffer and return the next input character:
9885 * 1) If a string was pushed back on the input, pop it;
9886 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9887 * or we are reading from a string so we can't refill the buffer,
9889 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9890 * 4) Process input up to the next newline, deleting nul characters.
9892 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9893 #define pgetc_debug(...) ((void)0)
9894 static int pgetc(void);
9901 if (g_parsefile->strpush) {
9902 #if ENABLE_ASH_ALIAS
9903 if (g_parsefile->left_in_line == -1
9904 && g_parsefile->strpush->ap
9905 && g_parsefile->next_to_pgetc[-1] != ' '
9906 && g_parsefile->next_to_pgetc[-1] != '\t'
9908 pgetc_debug("preadbuffer PEOA");
9915 /* on both branches above g_parsefile->left_in_line < 0.
9916 * "pgetc" needs refilling.
9919 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9920 * pungetc() may increment it a few times.
9921 * Assuming it won't increment it to less than -90.
9923 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9924 pgetc_debug("preadbuffer PEOF1");
9925 /* even in failure keep left_in_line and next_to_pgetc
9926 * in lock step, for correct multi-layer pungetc.
9927 * left_in_line was decremented before preadbuffer(),
9928 * must inc next_to_pgetc: */
9929 g_parsefile->next_to_pgetc++;
9933 more = g_parsefile->left_in_buffer;
9935 flush_stdout_stderr();
9939 /* don't try reading again */
9940 g_parsefile->left_in_line = -99;
9941 pgetc_debug("preadbuffer PEOF2");
9942 g_parsefile->next_to_pgetc++;
9947 /* Find out where's the end of line.
9948 * Set g_parsefile->left_in_line
9949 * and g_parsefile->left_in_buffer acordingly.
9950 * NUL chars are deleted.
9952 q = g_parsefile->next_to_pgetc;
9960 memmove(q, q + 1, more);
9964 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9970 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9971 if (g_parsefile->left_in_line < 0)
9976 g_parsefile->left_in_buffer = more;
9981 out2str(g_parsefile->next_to_pgetc);
9985 pgetc_debug("preadbuffer at %d:%p'%s'",
9986 g_parsefile->left_in_line,
9987 g_parsefile->next_to_pgetc,
9988 g_parsefile->next_to_pgetc);
9989 return (unsigned char)*g_parsefile->next_to_pgetc++;
9995 g_parsefile->linno++;
9996 setprompt_if(doprompt, 2);
10001 g_parsefile->linno++;
10002 needprompt = doprompt;
10010 pgetc_debug("pgetc at %d:%p'%s'",
10011 g_parsefile->left_in_line,
10012 g_parsefile->next_to_pgetc,
10013 g_parsefile->next_to_pgetc);
10014 if (g_parsefile->unget)
10015 return g_parsefile->lastc[--g_parsefile->unget];
10017 if (--g_parsefile->left_in_line >= 0)
10018 c = (signed char)*g_parsefile->next_to_pgetc++;
10022 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10023 g_parsefile->lastc[0] = c;
10028 #if ENABLE_ASH_ALIAS
10030 pgetc_without_PEOA(void)
10034 pgetc_debug("pgetc at %d:%p'%s'",
10035 g_parsefile->left_in_line,
10036 g_parsefile->next_to_pgetc,
10037 g_parsefile->next_to_pgetc);
10039 } while (c == PEOA);
10043 # define pgetc_without_PEOA() pgetc()
10047 * Read a line from the script.
10050 pfgets(char *line, int len)
10056 while (--nleft > 0) {
10057 c = pgetc_without_PEOA();
10072 * Undo a call to pgetc. Only two characters may be pushed back.
10073 * PEOF may be pushed back.
10078 g_parsefile->unget++;
10081 /* This one eats backslash+newline */
10087 while ((c = pgetc()) == '\\') {
10088 if (pgetc() != '\n') {
10100 * To handle the "." command, a stack of input files is used. Pushfile
10101 * adds a new entry to the stack and popfile restores the previous level.
10106 struct parsefile *pf;
10108 pf = ckzalloc(sizeof(*pf));
10109 pf->prev = g_parsefile;
10111 /*pf->strpush = NULL; - ckzalloc did it */
10112 /*pf->basestrpush.prev = NULL;*/
10120 struct parsefile *pf = g_parsefile;
10123 if (pf->pf_fd >= 0)
10126 while (pf->strpush)
10128 g_parsefile = pf->prev;
10134 * Return to top level.
10139 while (g_parsefile != &basepf)
10144 * Close the file(s) that the shell is reading commands from. Called
10145 * after a fork is done.
10151 if (g_parsefile->pf_fd > 0) {
10152 close(g_parsefile->pf_fd);
10153 g_parsefile->pf_fd = 0;
10158 * Like setinputfile, but takes an open file descriptor. Call this with
10162 setinputfd(int fd, int push)
10166 g_parsefile->buf = NULL;
10168 g_parsefile->pf_fd = fd;
10169 if (g_parsefile->buf == NULL)
10170 g_parsefile->buf = ckmalloc(IBUFSIZ);
10171 g_parsefile->left_in_buffer = 0;
10172 g_parsefile->left_in_line = 0;
10173 g_parsefile->linno = 1;
10177 * Set the input to take input from a file. If push is set, push the
10178 * old input onto the stack first.
10181 setinputfile(const char *fname, int flags)
10186 fd = open(fname, O_RDONLY);
10188 if (flags & INPUT_NOFILE_OK)
10191 ash_msg_and_raise_error("can't open '%s'", fname);
10196 close_on_exec_on(fd);
10197 setinputfd(fd, flags & INPUT_PUSH_FILE);
10204 * Like setinputfile, but takes input from a string.
10207 setinputstring(char *string)
10211 g_parsefile->next_to_pgetc = string;
10212 g_parsefile->left_in_line = strlen(string);
10213 g_parsefile->buf = NULL;
10214 g_parsefile->linno = 1;
10220 * Routines to check for mail.
10223 #if ENABLE_ASH_MAIL
10225 /* Hash of mtimes of mailboxes */
10226 static unsigned mailtime_hash;
10227 /* Set if MAIL or MAILPATH is changed. */
10228 static smallint mail_var_path_changed;
10231 * Print appropriate message(s) if mail has arrived.
10232 * If mail_var_path_changed is set,
10233 * then the value of MAIL has mail_var_path_changed,
10234 * so we just update the values.
10243 struct stackmark smark;
10246 setstackmark(&smark);
10247 mpath = mpathset() ? mpathval() : mailval();
10250 p = path_advance(&mpath, nullstr);
10255 for (q = p; *q; q++)
10261 q[-1] = '\0'; /* delete trailing '/' */
10262 if (stat(p, &statb) < 0) {
10265 /* Very simplistic "hash": just a sum of all mtimes */
10266 new_hash += (unsigned)statb.st_mtime;
10268 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10269 if (mailtime_hash != 0)
10270 out2str("you have mail\n");
10271 mailtime_hash = new_hash;
10273 mail_var_path_changed = 0;
10274 popstackmark(&smark);
10277 static void FAST_FUNC
10278 changemail(const char *val UNUSED_PARAM)
10280 mail_var_path_changed = 1;
10283 #endif /* ASH_MAIL */
10286 /* ============ ??? */
10289 * Set the shell parameters.
10292 setparam(char **argv)
10298 for (nparam = 0; argv[nparam]; nparam++)
10300 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10302 *ap++ = ckstrdup(*argv++);
10305 freeparam(&shellparam);
10306 shellparam.malloced = 1;
10307 shellparam.nparam = nparam;
10308 shellparam.p = newparam;
10309 #if ENABLE_ASH_GETOPTS
10310 shellparam.optind = 1;
10311 shellparam.optoff = -1;
10316 * Process shell options. The global variable argptr contains a pointer
10317 * to the argument list; we advance it past the options.
10319 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10320 * For a non-interactive shell, an error condition encountered
10321 * by a special built-in ... shall cause the shell to write a diagnostic message
10322 * to standard error and exit as shown in the following table:
10323 * Error Special Built-In
10325 * Utility syntax error (option or operand error) Shall exit
10327 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10328 * we see that bash does not do that (set "finishes" with error code 1 instead,
10329 * and shell continues), and people rely on this behavior!
10331 * set -o barfoo 2>/dev/null
10334 * Oh well. Let's mimic that.
10337 plus_minus_o(char *name, int val)
10342 for (i = 0; i < NOPTS; i++) {
10343 if (strcmp(name, optnames(i)) == 0) {
10348 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10351 for (i = 0; i < NOPTS; i++) {
10353 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10355 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10361 setoption(int flag, int val)
10365 for (i = 0; i < NOPTS; i++) {
10366 if (optletters(i) == flag) {
10371 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10375 options(int cmdline)
10383 while ((p = *argptr) != NULL) {
10385 if (c != '-' && c != '+')
10388 val = 0; /* val = 0 if c == '+' */
10391 if (p[0] == '\0' || LONE_DASH(p)) {
10393 /* "-" means turn off -x and -v */
10396 /* "--" means reset params */
10397 else if (*argptr == NULL)
10400 break; /* "-" or "--" terminates options */
10403 /* first char was + or - */
10404 while ((c = *p++) != '\0') {
10405 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10406 if (c == 'c' && cmdline) {
10407 minusc = p; /* command is after shell args */
10408 } else if (c == 'o') {
10409 if (plus_minus_o(*argptr, val)) {
10410 /* it already printed err message */
10411 return 1; /* error */
10415 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10417 /* bash does not accept +-login, we also won't */
10418 } else if (cmdline && val && (c == '-')) { /* long options */
10419 if (strcmp(p, "login") == 0)
10431 * The shift builtin command.
10433 static int FAST_FUNC
10434 shiftcmd(int argc UNUSED_PARAM, char **argv)
10441 n = number(argv[1]);
10442 if (n > shellparam.nparam)
10443 n = 0; /* bash compat, was = shellparam.nparam; */
10445 shellparam.nparam -= n;
10446 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10447 if (shellparam.malloced)
10450 ap2 = shellparam.p;
10451 while ((*ap2++ = *ap1++) != NULL)
10453 #if ENABLE_ASH_GETOPTS
10454 shellparam.optind = 1;
10455 shellparam.optoff = -1;
10462 * POSIX requires that 'set' (but not export or readonly) output the
10463 * variables in lexicographic order - by the locale's collating order (sigh).
10464 * Maybe we could keep them in an ordered balanced binary tree
10465 * instead of hashed lists.
10466 * For now just roll 'em through qsort for printing...
10469 showvars(const char *sep_prefix, int on, int off)
10472 char **ep, **epend;
10474 ep = listvars(on, off, &epend);
10475 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10477 sep = *sep_prefix ? " " : sep_prefix;
10479 for (; ep < epend; ep++) {
10483 p = strchrnul(*ep, '=');
10486 q = single_quote(++p);
10487 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10493 * The set command builtin.
10495 static int FAST_FUNC
10496 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10501 return showvars(nullstr, 0, VUNSET);
10504 retval = options(/*cmdline:*/ 0);
10505 if (retval == 0) { /* if no parse error... */
10507 if (*argptr != NULL) {
10515 #if ENABLE_ASH_RANDOM_SUPPORT
10516 static void FAST_FUNC
10517 change_random(const char *value)
10521 if (value == NULL) {
10522 /* "get", generate */
10523 t = next_random(&random_gen);
10524 /* set without recursion */
10525 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10526 vrandom.flags &= ~VNOFUNC;
10529 t = strtoul(value, NULL, 10);
10530 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10535 #if ENABLE_ASH_GETOPTS
10537 getopts(char *optstr, char *optvar, char **optfirst)
10544 int ind = shellparam.optind;
10545 int off = shellparam.optoff;
10549 shellparam.optind = -1;
10550 optnext = optfirst + ind - 1;
10552 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10555 p = optnext[-1] + off;
10556 if (p == NULL || *p == '\0') {
10557 /* Current word is done, advance */
10559 if (p == NULL || *p != '-' || *++p == '\0') {
10566 if (LONE_DASH(p)) /* check for "--" */
10571 for (q = optstr; *q != c;) {
10573 if (optstr[0] == ':') {
10575 /*sbuf[1] = '\0'; - already is */
10576 setvar0("OPTARG", sbuf);
10578 fprintf(stderr, "Illegal option -%c\n", c);
10579 unsetvar("OPTARG");
10589 if (*p == '\0' && (p = *optnext) == NULL) {
10590 if (optstr[0] == ':') {
10592 /*sbuf[1] = '\0'; - already is */
10593 setvar0("OPTARG", sbuf);
10596 fprintf(stderr, "No arg for -%c option\n", c);
10597 unsetvar("OPTARG");
10605 setvar0("OPTARG", p);
10608 setvar0("OPTARG", nullstr);
10610 ind = optnext - optfirst + 1;
10611 setvar("OPTIND", itoa(ind), VNOFUNC);
10613 /*sbuf[1] = '\0'; - already is */
10614 setvar0(optvar, sbuf);
10616 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10617 shellparam.optind = ind;
10623 * The getopts builtin. Shellparam.optnext points to the next argument
10624 * to be processed. Shellparam.optptr points to the next character to
10625 * be processed in the current argument. If shellparam.optnext is NULL,
10626 * then it's the first time getopts has been called.
10628 static int FAST_FUNC
10629 getoptscmd(int argc, char **argv)
10634 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10636 optbase = shellparam.p;
10637 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10638 shellparam.optind = 1;
10639 shellparam.optoff = -1;
10642 optbase = &argv[3];
10643 if ((unsigned)shellparam.optind > argc - 2) {
10644 shellparam.optind = 1;
10645 shellparam.optoff = -1;
10649 return getopts(argv[1], argv[2], optbase);
10651 #endif /* ASH_GETOPTS */
10654 /* ============ Shell parser */
10657 struct heredoc *next; /* next here document in list */
10658 union node *here; /* redirection node */
10659 char *eofmark; /* string indicating end of input */
10660 smallint striptabs; /* if set, strip leading tabs */
10663 static smallint tokpushback; /* last token pushed back */
10664 static smallint quoteflag; /* set if (part of) last token was quoted */
10665 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10666 static struct heredoc *heredoclist; /* list of here documents to read */
10667 static char *wordtext; /* text of last word returned by readtoken */
10668 static struct nodelist *backquotelist;
10669 static union node *redirnode;
10670 static struct heredoc *heredoc;
10672 static const char *
10673 tokname(char *buf, int tok)
10676 return tokname_array[tok];
10677 sprintf(buf, "\"%s\"", tokname_array[tok]);
10681 /* raise_error_unexpected_syntax:
10682 * Called when an unexpected token is read during the parse. The argument
10683 * is the token that is expected, or -1 if more than one type of token can
10684 * occur at this point.
10686 static void raise_error_unexpected_syntax(int) NORETURN;
10688 raise_error_unexpected_syntax(int token)
10694 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10696 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10697 raise_error_syntax(msg);
10701 #define EOFMARKLEN 79
10703 /* parsing is heavily cross-recursive, need these forward decls */
10704 static union node *andor(void);
10705 static union node *pipeline(void);
10706 static union node *parse_command(void);
10707 static void parseheredoc(void);
10708 static int peektoken(void);
10709 static int readtoken(void);
10711 static union node *
10714 union node *n1, *n2, *n3;
10719 switch (peektoken()) {
10727 if (!n1 && (nlflag & 1))
10733 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10734 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10740 if (tok == TBACKGND) {
10741 if (n2->type == NPIPE) {
10742 n2->npipe.pipe_backgnd = 1;
10744 if (n2->type != NREDIR) {
10745 n3 = stzalloc(sizeof(struct nredir));
10747 /*n3->nredir.redirect = NULL; - stzalloc did it */
10750 n2->type = NBACKGND;
10756 n3 = stzalloc(sizeof(struct nbinary));
10758 n3->nbinary.ch1 = n1;
10759 n3->nbinary.ch2 = n2;
10772 raise_error_unexpected_syntax(-1);
10779 static union node *
10782 union node *n1, *n2, *n3;
10790 } else if (t == TOR) {
10796 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10798 n3 = stzalloc(sizeof(struct nbinary));
10800 n3->nbinary.ch1 = n1;
10801 n3->nbinary.ch2 = n2;
10806 static union node *
10809 union node *n1, *n2, *pipenode;
10810 struct nodelist *lp, *prev;
10814 TRACE(("pipeline: entered\n"));
10815 if (readtoken() == TNOT) {
10817 checkkwd = CHKKWD | CHKALIAS;
10820 n1 = parse_command();
10821 if (readtoken() == TPIPE) {
10822 pipenode = stzalloc(sizeof(struct npipe));
10823 pipenode->type = NPIPE;
10824 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10825 lp = stzalloc(sizeof(struct nodelist));
10826 pipenode->npipe.cmdlist = lp;
10830 lp = stzalloc(sizeof(struct nodelist));
10831 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10832 lp->n = parse_command();
10834 } while (readtoken() == TPIPE);
10840 n2 = stzalloc(sizeof(struct nnot));
10848 static union node *
10853 n = stzalloc(sizeof(struct narg));
10855 /*n->narg.next = NULL; - stzalloc did it */
10856 n->narg.text = wordtext;
10857 n->narg.backquote = backquotelist;
10862 fixredir(union node *n, const char *text, int err)
10866 TRACE(("Fix redir %s %d\n", text, err));
10868 n->ndup.vname = NULL;
10870 fd = bb_strtou(text, NULL, 10);
10871 if (!errno && fd >= 0)
10872 n->ndup.dupfd = fd;
10873 else if (LONE_DASH(text))
10874 n->ndup.dupfd = -1;
10877 raise_error_syntax("bad fd number");
10878 n->ndup.vname = makename();
10883 * Returns true if the text contains nothing to expand (no dollar signs
10887 noexpand(const char *text)
10891 while ((c = *text++) != '\0') {
10892 if (c == CTLQUOTEMARK)
10896 else if (SIT(c, BASESYNTAX) == CCTL)
10905 union node *n = redirnode;
10907 if (readtoken() != TWORD)
10908 raise_error_unexpected_syntax(-1);
10909 if (n->type == NHERE) {
10910 struct heredoc *here = heredoc;
10914 if (quoteflag == 0)
10916 TRACE(("Here document %d\n", n->type));
10917 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10918 raise_error_syntax("illegal eof marker for << redirection");
10919 rmescapes(wordtext, 0);
10920 here->eofmark = wordtext;
10922 if (heredoclist == NULL)
10923 heredoclist = here;
10925 for (p = heredoclist; p->next; p = p->next)
10929 } else if (n->type == NTOFD || n->type == NFROMFD) {
10930 fixredir(n, wordtext, 0);
10932 n->nfile.fname = makename();
10936 static union node *
10939 union node *args, **app;
10940 union node *n = NULL;
10941 union node *vars, **vpp;
10942 union node **rpp, *redir;
10944 #if ENABLE_ASH_BASH_COMPAT
10945 smallint double_brackets_flag = 0;
10946 smallint function_flag = 0;
10956 savecheckkwd = CHKALIAS;
10959 checkkwd = savecheckkwd;
10962 #if ENABLE_ASH_BASH_COMPAT
10964 if (peektoken() != TWORD)
10965 raise_error_unexpected_syntax(TWORD);
10968 case TAND: /* "&&" */
10969 case TOR: /* "||" */
10970 if (!double_brackets_flag) {
10974 wordtext = (char *) (t == TAND ? "-a" : "-o");
10977 n = stzalloc(sizeof(struct narg));
10979 /*n->narg.next = NULL; - stzalloc did it */
10980 n->narg.text = wordtext;
10981 #if ENABLE_ASH_BASH_COMPAT
10982 if (strcmp("[[", wordtext) == 0)
10983 double_brackets_flag = 1;
10984 else if (strcmp("]]", wordtext) == 0)
10985 double_brackets_flag = 0;
10987 n->narg.backquote = backquotelist;
10988 if (savecheckkwd && isassignment(wordtext)) {
10990 vpp = &n->narg.next;
10993 app = &n->narg.next;
10996 #if ENABLE_ASH_BASH_COMPAT
10997 if (function_flag) {
10998 checkkwd = CHKNL | CHKKWD;
10999 switch (peektoken()) {
11011 if (strcmp("[[", wordtext) == 0)
11015 raise_error_unexpected_syntax(-1);
11021 *rpp = n = redirnode;
11022 rpp = &n->nfile.next;
11023 parsefname(); /* read name of redirection file */
11026 IF_ASH_BASH_COMPAT(do_func:)
11027 if (args && app == &args->narg.next
11030 struct builtincmd *bcmd;
11033 /* We have a function */
11034 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11035 raise_error_unexpected_syntax(TRP);
11036 name = n->narg.text;
11037 if (!goodname(name)
11038 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11040 raise_error_syntax("bad function name");
11043 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11044 n->narg.next = parse_command();
11047 IF_ASH_BASH_COMPAT(function_flag = 0;)
11058 n = stzalloc(sizeof(struct ncmd));
11060 n->ncmd.args = args;
11061 n->ncmd.assign = vars;
11062 n->ncmd.redirect = redir;
11066 static union node *
11067 parse_command(void)
11069 union node *n1, *n2;
11070 union node *ap, **app;
11071 union node *cp, **cpp;
11072 union node *redir, **rpp;
11079 switch (readtoken()) {
11081 raise_error_unexpected_syntax(-1);
11084 n1 = stzalloc(sizeof(struct nif));
11086 n1->nif.test = list(0);
11087 if (readtoken() != TTHEN)
11088 raise_error_unexpected_syntax(TTHEN);
11089 n1->nif.ifpart = list(0);
11091 while (readtoken() == TELIF) {
11092 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11093 n2 = n2->nif.elsepart;
11095 n2->nif.test = list(0);
11096 if (readtoken() != TTHEN)
11097 raise_error_unexpected_syntax(TTHEN);
11098 n2->nif.ifpart = list(0);
11100 if (lasttoken == TELSE)
11101 n2->nif.elsepart = list(0);
11103 n2->nif.elsepart = NULL;
11111 n1 = stzalloc(sizeof(struct nbinary));
11112 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11113 n1->nbinary.ch1 = list(0);
11116 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11117 got == TWORD ? wordtext : ""));
11118 raise_error_unexpected_syntax(TDO);
11120 n1->nbinary.ch2 = list(0);
11125 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11126 raise_error_syntax("bad for loop variable");
11127 n1 = stzalloc(sizeof(struct nfor));
11129 n1->nfor.var = wordtext;
11130 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11131 if (readtoken() == TIN) {
11133 while (readtoken() == TWORD) {
11134 n2 = stzalloc(sizeof(struct narg));
11136 /*n2->narg.next = NULL; - stzalloc did it */
11137 n2->narg.text = wordtext;
11138 n2->narg.backquote = backquotelist;
11140 app = &n2->narg.next;
11143 n1->nfor.args = ap;
11144 if (lasttoken != TNL && lasttoken != TSEMI)
11145 raise_error_unexpected_syntax(-1);
11147 n2 = stzalloc(sizeof(struct narg));
11149 /*n2->narg.next = NULL; - stzalloc did it */
11150 n2->narg.text = (char *)dolatstr;
11151 /*n2->narg.backquote = NULL;*/
11152 n1->nfor.args = n2;
11154 * Newline or semicolon here is optional (but note
11155 * that the original Bourne shell only allowed NL).
11157 if (lasttoken != TSEMI)
11160 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11161 if (readtoken() != TDO)
11162 raise_error_unexpected_syntax(TDO);
11163 n1->nfor.body = list(0);
11167 n1 = stzalloc(sizeof(struct ncase));
11169 if (readtoken() != TWORD)
11170 raise_error_unexpected_syntax(TWORD);
11171 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11173 /*n2->narg.next = NULL; - stzalloc did it */
11174 n2->narg.text = wordtext;
11175 n2->narg.backquote = backquotelist;
11176 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11177 if (readtoken() != TIN)
11178 raise_error_unexpected_syntax(TIN);
11179 cpp = &n1->ncase.cases;
11181 checkkwd = CHKNL | CHKKWD;
11183 while (t != TESAC) {
11184 if (lasttoken == TLP)
11186 *cpp = cp = stzalloc(sizeof(struct nclist));
11188 app = &cp->nclist.pattern;
11190 *app = ap = stzalloc(sizeof(struct narg));
11192 /*ap->narg.next = NULL; - stzalloc did it */
11193 ap->narg.text = wordtext;
11194 ap->narg.backquote = backquotelist;
11195 if (readtoken() != TPIPE)
11197 app = &ap->narg.next;
11200 //ap->narg.next = NULL;
11201 if (lasttoken != TRP)
11202 raise_error_unexpected_syntax(TRP);
11203 cp->nclist.body = list(2);
11205 cpp = &cp->nclist.next;
11207 checkkwd = CHKNL | CHKKWD;
11211 raise_error_unexpected_syntax(TENDCASE);
11218 n1 = stzalloc(sizeof(struct nredir));
11219 n1->type = NSUBSHELL;
11220 n1->nredir.n = list(0);
11221 /*n1->nredir.redirect = NULL; - stzalloc did it */
11228 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11232 return simplecmd();
11235 if (readtoken() != t)
11236 raise_error_unexpected_syntax(t);
11239 /* Now check for redirection which may follow command */
11240 checkkwd = CHKKWD | CHKALIAS;
11242 while (readtoken() == TREDIR) {
11243 *rpp = n2 = redirnode;
11244 rpp = &n2->nfile.next;
11250 if (n1->type != NSUBSHELL) {
11251 n2 = stzalloc(sizeof(struct nredir));
11256 n1->nredir.redirect = redir;
11261 #if ENABLE_ASH_BASH_COMPAT
11263 decode_dollar_squote(void)
11265 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11271 p = strchr(C_escapes, c);
11276 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11280 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11282 } else if (c == 'x') { /* \xHH */
11286 } while (isxdigit(c) && --cnt);
11288 if (cnt == 3) { /* \x but next char is "bad" */
11292 } else { /* simple seq like \\ or \t */
11297 c = bb_process_escape_sequence((void*)&p);
11298 } else { /* unrecognized "\z": print both chars unless ' or " */
11299 if (c != '\'' && c != '"') {
11301 c |= 0x100; /* "please encode \, then me" */
11309 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11310 * is not NULL, read a here document. In the latter case, eofmark is the
11311 * word which marks the end of the document and striptabs is true if
11312 * leading tabs should be stripped from the document. The argument c
11313 * is the first character of the input token or document.
11315 * Because C does not have internal subroutines, I have simulated them
11316 * using goto's to implement the subroutine linkage. The following macros
11317 * will run code that appears at the end of readtoken1.
11319 #define CHECKEND() {goto checkend; checkend_return:;}
11320 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11321 #define PARSESUB() {goto parsesub; parsesub_return:;}
11322 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11323 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11324 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11326 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11328 /* NB: syntax parameter fits into smallint */
11329 /* c parameter is an unsigned char or PEOF or PEOA */
11332 char line[EOFMARKLEN + 1];
11333 struct nodelist *bqlist;
11337 smallint prevsyntax; /* syntax before arithmetic */
11338 #if ENABLE_ASH_EXPAND_PRMT
11339 smallint pssyntax; /* we are expanding a prompt string */
11341 int varnest; /* levels of variables expansion */
11342 int arinest; /* levels of arithmetic expansion */
11343 int parenlevel; /* levels of parens in arithmetic */
11344 int dqvarnest; /* levels of variables expansion within double quotes */
11346 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11348 startlinno = g_parsefile->linno;
11352 #if ENABLE_ASH_EXPAND_PRMT
11353 pssyntax = (syntax == PSSYNTAX);
11357 dblquote = (syntax == DQSYNTAX);
11363 STARTSTACKSTR(out);
11365 /* For each line, until end of word */
11366 CHECKEND(); /* set c to PEOF if at end of here document */
11367 for (;;) { /* until end of line or end of word */
11368 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11369 switch (SIT(c, syntax)) {
11370 case CNL: /* '\n' */
11371 if (syntax == BASESYNTAX)
11372 goto endword; /* exit outer loop */
11376 goto loop; /* continue outer loop */
11381 #if ENABLE_ASH_BASH_COMPAT
11382 if (c == '\\' && bash_dollar_squote) {
11383 c = decode_dollar_squote();
11385 /* skip $'\000', $'\x00' (like bash) */
11389 /* Unknown escape. Encode as '\z' */
11390 c = (unsigned char)c;
11391 if (eofmark == NULL || dblquote)
11392 USTPUTC(CTLESC, out);
11393 USTPUTC('\\', out);
11397 if (eofmark == NULL || dblquote)
11398 USTPUTC(CTLESC, out);
11401 case CBACK: /* backslash */
11402 c = pgetc_without_PEOA();
11404 USTPUTC(CTLESC, out);
11405 USTPUTC('\\', out);
11407 } else if (c == '\n') {
11410 #if ENABLE_ASH_EXPAND_PRMT
11411 if (c == '$' && pssyntax) {
11412 USTPUTC(CTLESC, out);
11413 USTPUTC('\\', out);
11416 /* Backslash is retained if we are in "str" and next char isn't special */
11421 && (c != '"' || eofmark != NULL)
11423 USTPUTC('\\', out);
11425 USTPUTC(CTLESC, out);
11433 if (eofmark == NULL) {
11434 USTPUTC(CTLQUOTEMARK, out);
11442 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11443 if (eofmark != NULL && varnest == 0) {
11446 if (dqvarnest == 0) {
11447 syntax = BASESYNTAX;
11454 case CVAR: /* '$' */
11455 PARSESUB(); /* parse substitution */
11457 case CENDVAR: /* '}' */
11460 if (dqvarnest > 0) {
11467 #if ENABLE_SH_MATH_SUPPORT
11468 case CLP: /* '(' in arithmetic */
11472 case CRP: /* ')' in arithmetic */
11473 if (parenlevel > 0) {
11476 if (pgetc_eatbnl() == ')') {
11478 if (--arinest == 0) {
11479 syntax = prevsyntax;
11483 * unbalanced parens
11484 * (don't 2nd guess - no error)
11492 case CBQUOTE: /* '`' */
11496 goto endword; /* exit outer loop */
11500 if (varnest == 0) {
11501 #if ENABLE_ASH_BASH_COMPAT
11503 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11504 if (pgetc() == '>')
11505 c = 0x100 + '>'; /* flag &> */
11509 goto endword; /* exit outer loop */
11511 IF_ASH_ALIAS(if (c != PEOA))
11518 #if ENABLE_SH_MATH_SUPPORT
11519 if (syntax == ARISYNTAX)
11520 raise_error_syntax("missing '))'");
11522 if (syntax != BASESYNTAX && eofmark == NULL)
11523 raise_error_syntax("unterminated quoted string");
11524 if (varnest != 0) {
11525 startlinno = g_parsefile->linno;
11527 raise_error_syntax("missing '}'");
11529 USTPUTC('\0', out);
11530 len = out - (char *)stackblock();
11531 out = stackblock();
11532 if (eofmark == NULL) {
11533 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11536 if (isdigit_str9(out)) {
11537 PARSEREDIR(); /* passed as params: out, c */
11538 lasttoken = TREDIR;
11541 /* else: non-number X seen, interpret it
11542 * as "NNNX>file" = "NNNX >file" */
11546 quoteflag = quotef;
11547 backquotelist = bqlist;
11548 grabstackblock(len);
11552 /* end of readtoken routine */
11555 * Check to see whether we are at the end of the here document. When this
11556 * is called, c is set to the first character of the next input line. If
11557 * we are at the end of the here document, this routine sets the c to PEOF.
11561 #if ENABLE_ASH_ALIAS
11563 c = pgetc_without_PEOA();
11566 while (c == '\t') {
11567 c = pgetc_without_PEOA();
11570 if (c == *eofmark) {
11571 if (pfgets(line, sizeof(line)) != NULL) {
11576 for (q = eofmark + 1;; p++, q++) {
11580 if (!*q || cc != *q)
11587 pushstring(line, NULL);
11592 goto checkend_return;
11596 * Parse a redirection operator. The variable "out" points to a string
11597 * specifying the fd to be redirected. The variable "c" contains the
11598 * first character of the redirection operator.
11601 /* out is already checked to be a valid number or "" */
11602 int fd = (*out == '\0' ? -1 : atoi(out));
11605 np = stzalloc(sizeof(struct nfile));
11610 np->type = NAPPEND;
11612 np->type = NCLOBBER;
11615 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11621 #if ENABLE_ASH_BASH_COMPAT
11622 else if (c == 0x100 + '>') { /* this flags &> redirection */
11624 pgetc(); /* this is '>', no need to check */
11628 else { /* c == '<' */
11629 /*np->nfile.fd = 0; - stzalloc did it */
11633 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11634 np = stzalloc(sizeof(struct nhere));
11635 /*np->nfile.fd = 0; - stzalloc did it */
11638 heredoc = stzalloc(sizeof(struct heredoc));
11639 heredoc->here = np;
11642 heredoc->striptabs = 1;
11644 /*heredoc->striptabs = 0; - stzalloc did it */
11650 np->type = NFROMFD;
11654 np->type = NFROMTO;
11666 goto parseredir_return;
11670 * Parse a substitution. At this point, we have read the dollar sign
11671 * and nothing else.
11674 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11675 * (assuming ascii char codes, as the original implementation did) */
11676 #define is_special(c) \
11677 (((unsigned)(c) - 33 < 32) \
11678 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11680 unsigned char subtype;
11683 c = pgetc_eatbnl();
11684 if (c > 255 /* PEOA or PEOF */
11685 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11687 #if ENABLE_ASH_BASH_COMPAT
11688 if (syntax != DQSYNTAX && c == '\'')
11689 bash_dollar_squote = 1;
11694 } else if (c == '(') {
11695 /* $(command) or $((arith)) */
11696 if (pgetc_eatbnl() == '(') {
11697 #if ENABLE_SH_MATH_SUPPORT
11700 raise_error_syntax("you disabled math support for $((arith)) syntax");
11707 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11708 USTPUTC(CTLVAR, out);
11709 typeloc = out - (char *)stackblock();
11711 subtype = VSNORMAL;
11713 c = pgetc_eatbnl();
11718 /* $[{[#]]NAME[}] */
11721 c = pgetc_eatbnl();
11722 } while (is_in_name(c));
11723 } else if (isdigit(c)) {
11724 /* $[{[#]]NUM[}] */
11727 c = pgetc_eatbnl();
11728 } while (isdigit(c));
11729 } else if (is_special(c)) {
11730 /* $[{[#]]<specialchar>[}] */
11733 c = pgetc_eatbnl();
11734 if (!subtype && cc == '#') {
11735 subtype = VSLENGTH;
11736 if (c == '_' || isalnum(c))
11739 c = pgetc_eatbnl();
11740 if (cc == '}' || c != '}') {
11751 if (c != '}' && subtype == VSLENGTH) {
11752 /* ${#VAR didn't end with } */
11756 if (subtype == 0) {
11757 static const char types[] ALIGN1 = "}-+?=";
11758 /* ${VAR...} but not $VAR or ${#VAR} */
11759 /* c == first char after VAR */
11762 c = pgetc_eatbnl();
11763 #if ENABLE_ASH_BASH_COMPAT
11764 /* This check is only needed to not misinterpret
11765 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11768 if (!strchr(types, c)) {
11769 subtype = VSSUBSTR;
11771 break; /* "goto badsub" is bigger (!) */
11777 const char *p = strchr(types, c);
11780 subtype |= p - types + VSNORMAL;
11786 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11787 c = pgetc_eatbnl();
11793 #if ENABLE_ASH_BASH_COMPAT
11795 /* ${v/[/]pattern/repl} */
11796 //TODO: encode pattern and repl separately.
11797 // Currently ${v/$var_with_slash/repl} is horribly broken
11798 subtype = VSREPLACE;
11799 c = pgetc_eatbnl();
11802 subtype++; /* VSREPLACEALL */
11810 ((unsigned char *)stackblock())[typeloc] = subtype;
11811 if (subtype != VSNORMAL) {
11818 goto parsesub_return;
11822 * Called to parse command substitutions. Newstyle is set if the command
11823 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11824 * list of commands (passed by reference), and savelen is the number of
11825 * characters on the top of the stack which must be preserved.
11828 struct nodelist **nlpp;
11832 smallint saveprompt = 0;
11835 savelen = out - (char *)stackblock();
11838 * FIXME: this can allocate very large block on stack and SEGV.
11840 * echo "..<100kbytes>..`true` $(true) `true` ..."
11841 * allocates 100kb for every command subst. With about
11842 * a hundred command substitutions stack overflows.
11843 * With larger prepended string, SEGV happens sooner.
11845 str = alloca(savelen);
11846 memcpy(str, stackblock(), savelen);
11850 /* We must read until the closing backquote, giving special
11851 * treatment to some slashes, and then push the string and
11852 * reread it as input, interpreting it normally.
11858 STARTSTACKSTR(pout);
11862 setprompt_if(needprompt, 2);
11873 * If eating a newline, avoid putting
11874 * the newline into the new character
11875 * stream (via the STPUTC after the
11880 if (pc != '\\' && pc != '`' && pc != '$'
11881 && (!dblquote || pc != '"')
11883 STPUTC('\\', pout);
11885 if (pc <= 255 /* not PEOA or PEOF */) {
11891 IF_ASH_ALIAS(case PEOA:)
11892 startlinno = g_parsefile->linno;
11893 raise_error_syntax("EOF in backquote substitution");
11905 STPUTC('\0', pout);
11906 psavelen = pout - (char *)stackblock();
11907 if (psavelen > 0) {
11908 pstr = grabstackstr(pout);
11909 setinputstring(pstr);
11914 nlpp = &(*nlpp)->next;
11915 *nlpp = stzalloc(sizeof(**nlpp));
11916 /* (*nlpp)->next = NULL; - stzalloc did it */
11919 saveprompt = doprompt;
11926 doprompt = saveprompt;
11927 else if (readtoken() != TRP)
11928 raise_error_unexpected_syntax(TRP);
11933 * Start reading from old file again, ignoring any pushed back
11934 * tokens left from the backquote parsing
11939 while (stackblocksize() <= savelen)
11941 STARTSTACKSTR(out);
11943 memcpy(out, str, savelen);
11944 STADJUST(savelen, out);
11946 USTPUTC(CTLBACKQ, out);
11948 goto parsebackq_oldreturn;
11949 goto parsebackq_newreturn;
11952 #if ENABLE_SH_MATH_SUPPORT
11954 * Parse an arithmetic expansion (indicate start of one and set state)
11957 if (++arinest == 1) {
11958 prevsyntax = syntax;
11959 syntax = ARISYNTAX;
11961 USTPUTC(CTLARI, out);
11962 goto parsearith_return;
11965 } /* end of readtoken */
11968 * Read the next input token.
11969 * If the token is a word, we set backquotelist to the list of cmds in
11970 * backquotes. We set quoteflag to true if any part of the word was
11972 * If the token is TREDIR, then we set redirnode to a structure containing
11974 * In all cases, the variable startlinno is set to the number of the line
11975 * on which the token starts.
11977 * [Change comment: here documents and internal procedures]
11978 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11979 * word parsing code into a separate routine. In this case, readtoken
11980 * doesn't need to have any internal procedures, but parseword does.
11981 * We could also make parseoperator in essence the main routine, and
11982 * have parseword (readtoken1?) handle both words and redirection.]
11984 #define NEW_xxreadtoken
11985 #ifdef NEW_xxreadtoken
11986 /* singles must be first! */
11987 static const char xxreadtoken_chars[7] ALIGN1 = {
11988 '\n', '(', ')', /* singles */
11989 '&', '|', ';', /* doubles */
11993 #define xxreadtoken_singles 3
11994 #define xxreadtoken_doubles 3
11996 static const char xxreadtoken_tokens[] ALIGN1 = {
11997 TNL, TLP, TRP, /* only single occurrence allowed */
11998 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11999 TEOF, /* corresponds to trailing nul */
12000 TAND, TOR, TENDCASE /* if double occurrence */
12012 setprompt_if(needprompt, 2);
12013 startlinno = g_parsefile->linno;
12014 for (;;) { /* until token or start of word found */
12016 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12020 while ((c = pgetc()) != '\n' && c != PEOF)
12023 } else if (c == '\\') {
12024 if (pgetc() != '\n') {
12026 break; /* return readtoken1(...) */
12032 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12038 p = strchr(xxreadtoken_chars, c);
12040 break; /* return readtoken1(...) */
12042 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12044 if (cc == c) { /* double occurrence? */
12045 p += xxreadtoken_doubles + 1;
12048 #if ENABLE_ASH_BASH_COMPAT
12049 if (c == '&' && cc == '>') /* &> */
12050 break; /* return readtoken1(...) */
12055 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12060 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12062 #else /* old xxreadtoken */
12063 #define RETURN(token) return lasttoken = token
12073 setprompt_if(needprompt, 2);
12074 startlinno = g_parsefile->linno;
12075 for (;;) { /* until token or start of word found */
12078 case ' ': case '\t':
12079 IF_ASH_ALIAS(case PEOA:)
12082 while ((c = pgetc()) != '\n' && c != PEOF)
12087 if (pgetc() == '\n') {
12099 if (pgetc() == '&')
12104 if (pgetc() == '|')
12109 if (pgetc() == ';')
12122 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12125 #endif /* old xxreadtoken */
12131 int kwd = checkkwd;
12133 smallint alreadyseen = tokpushback;
12136 #if ENABLE_ASH_ALIAS
12152 if (t != TWORD || quoteflag) {
12157 * check for keywords
12159 if (kwd & CHKKWD) {
12160 const char *const *pp;
12162 pp = findkwd(wordtext);
12164 lasttoken = t = pp - tokname_array;
12165 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12170 if (checkkwd & CHKALIAS) {
12171 #if ENABLE_ASH_ALIAS
12173 ap = lookupalias(wordtext, 1);
12176 pushstring(ap->val, ap);
12186 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12188 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12204 * Read and parse a command. Returns NODE_EOF on end of file.
12205 * (NULL is a valid parse tree indicating a blank line.)
12207 static union node *
12208 parsecmd(int interact)
12213 doprompt = interact;
12214 setprompt_if(doprompt, doprompt);
12220 * Input any here documents.
12225 struct heredoc *here;
12228 here = heredoclist;
12229 heredoclist = NULL;
12232 setprompt_if(needprompt, 2);
12233 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12234 here->eofmark, here->striptabs);
12235 n = stzalloc(sizeof(struct narg));
12236 n->narg.type = NARG;
12237 /*n->narg.next = NULL; - stzalloc did it */
12238 n->narg.text = wordtext;
12239 n->narg.backquote = backquotelist;
12240 here->here->nhere.doc = n;
12247 * called by editline -- any expansions to the prompt should be added here.
12249 #if ENABLE_ASH_EXPAND_PRMT
12250 static const char *
12251 expandstr(const char *ps)
12256 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12257 * and token processing _can_ alter it (delete NULs etc). */
12258 setinputstring((char *)ps);
12260 saveprompt = doprompt;
12262 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12263 doprompt = saveprompt;
12267 n.narg.type = NARG;
12268 n.narg.next = NULL;
12269 n.narg.text = wordtext;
12270 n.narg.backquote = backquotelist;
12272 expandarg(&n, NULL, EXP_QUOTED);
12273 return stackblock();
12278 * Execute a command or commands contained in a string.
12281 evalstring(char *s, int flags)
12284 struct stackmark smark;
12289 setstackmark(&smark);
12292 while ((n = parsecmd(0)) != NODE_EOF) {
12295 i = evaltree(n, flags);
12298 popstackmark(&smark);
12302 popstackmark(&smark);
12310 * The eval command.
12312 static int FAST_FUNC
12313 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12322 STARTSTACKSTR(concat);
12324 concat = stack_putstr(p, concat);
12328 STPUTC(' ', concat);
12330 STPUTC('\0', concat);
12331 p = grabstackstr(concat);
12333 return evalstring(p, flags & EV_TESTED);
12339 * Read and execute commands.
12340 * "Top" is nonzero for the top level command loop;
12341 * it turns on prompting if the shell is interactive.
12347 struct stackmark smark;
12352 TRACE(("cmdloop(%d) called\n", top));
12356 setstackmark(&smark);
12359 showjobs(SHOW_CHANGED|SHOW_STDERR);
12362 if (iflag && top) {
12366 n = parsecmd(inter);
12368 if (DEBUG > 2 && debug && (n != NODE_EOF))
12371 if (n == NODE_EOF) {
12372 if (!top || numeof >= 50)
12374 if (!stoppedjobs()) {
12377 out2str("\nUse \"exit\" to leave shell.\n");
12380 } else if (nflag == 0) {
12383 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12386 i = evaltree(n, 0);
12390 popstackmark(&smark);
12394 evalskip &= ~SKIPFUNC;
12402 * Take commands from a file. To be compatible we should do a path
12403 * search for the file, which is necessary to find sub-commands.
12406 find_dot_file(char *name)
12409 const char *path = pathval();
12412 /* don't try this for absolute or relative paths */
12413 if (strchr(name, '/'))
12416 /* IIRC standards do not say whether . is to be searched.
12417 * And it is even smaller this way, making it unconditional for now:
12419 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12424 while ((fullname = path_advance(&path, name)) != NULL) {
12426 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12428 * Don't bother freeing here, since it will
12429 * be freed by the caller.
12433 if (fullname != name)
12434 stunalloc(fullname);
12437 /* not found in the PATH */
12438 ash_msg_and_raise_error("%s: not found", name);
12442 static int FAST_FUNC
12443 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12445 /* "false; . empty_file; echo $?" should print 0, not 1: */
12449 struct strlist *sp;
12450 volatile struct shparam saveparam;
12452 for (sp = cmdenviron; sp; sp = sp->next)
12453 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12455 nextopt(nullstr); /* handle possible "--" */
12459 /* bash says: "bash: .: filename argument required" */
12460 return 2; /* bash compat */
12463 /* This aborts if file isn't found, which is POSIXly correct.
12464 * bash returns exitcode 1 instead.
12466 fullname = find_dot_file(argv[0]);
12468 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12470 saveparam = shellparam;
12471 shellparam.malloced = 0;
12475 shellparam.nparam = argc;
12476 shellparam.p = argv;
12479 /* This aborts if file can't be opened, which is POSIXly correct.
12480 * bash returns exitcode 1 instead.
12482 setinputfile(fullname, INPUT_PUSH_FILE);
12483 commandname = fullname;
12484 status = cmdloop(0);
12488 freeparam(&shellparam);
12489 shellparam = saveparam;
12495 static int FAST_FUNC
12496 exitcmd(int argc UNUSED_PARAM, char **argv)
12501 exitstatus = number(argv[1]);
12502 raise_exception(EXEXIT);
12507 * Read a file containing shell functions.
12510 readcmdfile(char *name)
12512 setinputfile(name, INPUT_PUSH_FILE);
12518 /* ============ find_command inplementation */
12521 * Resolve a command name. If you change this routine, you may have to
12522 * change the shellexec routine as well.
12525 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12527 struct tblentry *cmdp;
12534 struct builtincmd *bcmd;
12536 /* If name contains a slash, don't use PATH or hash table */
12537 if (strchr(name, '/') != NULL) {
12538 entry->u.index = -1;
12539 if (act & DO_ABS) {
12540 while (stat(name, &statb) < 0) {
12542 if (errno == EINTR)
12545 entry->cmdtype = CMDUNKNOWN;
12549 entry->cmdtype = CMDNORMAL;
12553 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12555 updatetbl = (path == pathval());
12558 if (strstr(path, "%builtin") != NULL)
12559 act |= DO_ALTBLTIN;
12562 /* If name is in the table, check answer will be ok */
12563 cmdp = cmdlookup(name, 0);
12564 if (cmdp != NULL) {
12567 switch (cmdp->cmdtype) {
12585 } else if (cmdp->rehash == 0)
12586 /* if not invalidated by cd, we're done */
12590 /* If %builtin not in path, check for builtin next */
12591 bcmd = find_builtin(name);
12593 if (IS_BUILTIN_REGULAR(bcmd))
12594 goto builtin_success;
12595 if (act & DO_ALTPATH) {
12596 if (!(act & DO_ALTBLTIN))
12597 goto builtin_success;
12598 } else if (builtinloc <= 0) {
12599 goto builtin_success;
12603 #if ENABLE_FEATURE_SH_STANDALONE
12605 int applet_no = find_applet_by_name(name);
12606 if (applet_no >= 0) {
12607 entry->cmdtype = CMDNORMAL;
12608 entry->u.index = -2 - applet_no;
12614 /* We have to search path. */
12615 prev = -1; /* where to start */
12616 if (cmdp && cmdp->rehash) { /* doing a rehash */
12617 if (cmdp->cmdtype == CMDBUILTIN)
12620 prev = cmdp->param.index;
12626 while ((fullname = path_advance(&path, name)) != NULL) {
12627 stunalloc(fullname);
12628 /* NB: code below will still use fullname
12629 * despite it being "unallocated" */
12632 if (prefix(pathopt, "builtin")) {
12634 goto builtin_success;
12637 if ((act & DO_NOFUNC)
12638 || !prefix(pathopt, "func")
12639 ) { /* ignore unimplemented options */
12643 /* if rehash, don't redo absolute path names */
12644 if (fullname[0] == '/' && idx <= prev) {
12647 TRACE(("searchexec \"%s\": no change\n", name));
12650 while (stat(fullname, &statb) < 0) {
12652 if (errno == EINTR)
12655 if (errno != ENOENT && errno != ENOTDIR)
12659 e = EACCES; /* if we fail, this will be the error */
12660 if (!S_ISREG(statb.st_mode))
12662 if (pathopt) { /* this is a %func directory */
12663 stalloc(strlen(fullname) + 1);
12664 /* NB: stalloc will return space pointed by fullname
12665 * (because we don't have any intervening allocations
12666 * between stunalloc above and this stalloc) */
12667 readcmdfile(fullname);
12668 cmdp = cmdlookup(name, 0);
12669 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12670 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12671 stunalloc(fullname);
12674 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12676 entry->cmdtype = CMDNORMAL;
12677 entry->u.index = idx;
12681 cmdp = cmdlookup(name, 1);
12682 cmdp->cmdtype = CMDNORMAL;
12683 cmdp->param.index = idx;
12688 /* We failed. If there was an entry for this command, delete it */
12689 if (cmdp && updatetbl)
12690 delete_cmd_entry();
12692 ash_msg("%s: %s", name, errmsg(e, "not found"));
12693 entry->cmdtype = CMDUNKNOWN;
12698 entry->cmdtype = CMDBUILTIN;
12699 entry->u.cmd = bcmd;
12703 cmdp = cmdlookup(name, 1);
12704 cmdp->cmdtype = CMDBUILTIN;
12705 cmdp->param.cmd = bcmd;
12709 entry->cmdtype = cmdp->cmdtype;
12710 entry->u = cmdp->param;
12715 * The trap builtin.
12717 static int FAST_FUNC
12718 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12722 int signo, exitcode;
12727 for (signo = 0; signo < NSIG; signo++) {
12728 char *tr = trap_ptr[signo];
12730 /* note: bash adds "SIG", but only if invoked
12731 * as "bash". If called as "sh", or if set -o posix,
12732 * then it prints short signal names.
12733 * We are printing short names: */
12734 out1fmt("trap -- %s %s\n",
12736 get_signame(signo));
12737 /* trap_ptr != trap only if we are in special-cased `trap` code.
12738 * In this case, we will exit very soon, no need to free(). */
12739 /* if (trap_ptr != trap && tp[0]) */
12744 if (trap_ptr != trap) {
12757 signo = get_signum(*ap);
12759 /* Mimic bash message exactly */
12760 ash_msg("%s: invalid signal specification", *ap);
12766 if (LONE_DASH(action))
12769 if (action[0]) /* not NULL and not "" and not "-" */
12770 may_have_traps = 1;
12771 action = ckstrdup(action);
12775 trap[signo] = action;
12786 /* ============ Builtins */
12788 #if ENABLE_ASH_HELP
12789 static int FAST_FUNC
12790 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12796 "Built-in commands:\n"
12797 "------------------\n");
12798 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12799 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12800 builtintab[i].name + 1);
12806 # if ENABLE_FEATURE_SH_STANDALONE
12808 const char *a = applet_names;
12810 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12815 while (*a++ != '\0')
12820 newline_and_flush(stdout);
12821 return EXIT_SUCCESS;
12826 static int FAST_FUNC
12827 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12829 show_history(line_input_state);
12830 return EXIT_SUCCESS;
12835 * The export and readonly commands.
12837 static int FAST_FUNC
12838 exportcmd(int argc UNUSED_PARAM, char **argv)
12848 /* "readonly" in bash accepts, but ignores -n.
12849 * We do the same: it saves a conditional in nextopt's param.
12852 while ((opt = nextopt("np")) != '\0') {
12854 flag_off = VEXPORT;
12857 if (argv[0][0] == 'r') {
12859 flag_off = 0; /* readonly ignores -n */
12861 flag_off = ~flag_off;
12863 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12869 p = strchr(name, '=');
12873 vp = *findvar(hashvar(name), name);
12875 vp->flags = ((vp->flags | flag) & flag_off);
12879 setvar(name, p, (flag & flag_off));
12880 } while ((name = *++aptr) != NULL);
12885 /* No arguments. Show the list of exported or readonly vars.
12888 showvars(argv[0], flag, 0);
12893 * Delete a function if it exists.
12896 unsetfunc(const char *name)
12898 struct tblentry *cmdp;
12900 cmdp = cmdlookup(name, 0);
12901 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12902 delete_cmd_entry();
12906 * The unset builtin command. We unset the function before we unset the
12907 * variable to allow a function to be unset when there is a readonly variable
12908 * with the same name.
12910 static int FAST_FUNC
12911 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12918 while ((i = nextopt("vf")) != 0) {
12922 for (ap = argptr; *ap; ap++) {
12935 static const unsigned char timescmd_str[] ALIGN1 = {
12936 ' ', offsetof(struct tms, tms_utime),
12937 '\n', offsetof(struct tms, tms_stime),
12938 ' ', offsetof(struct tms, tms_cutime),
12939 '\n', offsetof(struct tms, tms_cstime),
12942 static int FAST_FUNC
12943 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12945 unsigned long clk_tck, s, t;
12946 const unsigned char *p;
12949 clk_tck = bb_clk_tck();
12954 t = *(clock_t *)(((char *) &buf) + p[1]);
12957 out1fmt("%lum%lu.%03lus%c",
12959 (t * 1000) / clk_tck,
12967 #if ENABLE_SH_MATH_SUPPORT
12969 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12970 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12972 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12974 static int FAST_FUNC
12975 letcmd(int argc UNUSED_PARAM, char **argv)
12981 ash_msg_and_raise_error("expression expected");
12983 i = ash_arith(*argv);
12991 * The read builtin. Options:
12992 * -r Do not interpret '\' specially
12993 * -s Turn off echo (tty only)
12994 * -n NCHARS Read NCHARS max
12995 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12996 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12997 * -u FD Read from given FD instead of fd 0
12998 * This uses unbuffered input, which may be avoidable in some cases.
12999 * TODO: bash also has:
13000 * -a ARRAY Read into array[0],[1],etc
13001 * -d DELIM End on DELIM char, not newline
13002 * -e Use line editing (tty only)
13004 static int FAST_FUNC
13005 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13007 char *opt_n = NULL;
13008 char *opt_p = NULL;
13009 char *opt_t = NULL;
13010 char *opt_u = NULL;
13011 int read_flags = 0;
13015 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13024 read_flags |= BUILTIN_READ_SILENT;
13030 read_flags |= BUILTIN_READ_RAW;
13040 /* "read -s" needs to save/restore termios, can't allow ^C
13041 * to jump out of it.
13044 r = shell_builtin_read(setvar0,
13046 bltinlookup("IFS"), /* can be NULL */
13055 if ((uintptr_t)r > 1)
13056 ash_msg_and_raise_error(r);
13058 return (uintptr_t)r;
13061 static int FAST_FUNC
13062 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13064 static const char permuser[3] ALIGN1 = "ogu";
13067 int symbolic_mode = 0;
13069 while (nextopt("S") != '\0') {
13078 if (*argptr == NULL) {
13079 if (symbolic_mode) {
13080 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13087 *p++ = permuser[i];
13089 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13090 if (!(mask & 0400)) *p++ = 'r';
13091 if (!(mask & 0200)) *p++ = 'w';
13092 if (!(mask & 0100)) *p++ = 'x';
13100 out1fmt("%04o\n", mask);
13103 char *modestr = *argptr;
13104 /* numeric umasks are taken as-is */
13105 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13106 if (!isdigit(modestr[0]))
13108 mask = bb_parse_mode(modestr, mask);
13109 if ((unsigned)mask > 0777) {
13110 ash_msg_and_raise_error("illegal mode: %s", modestr);
13112 if (!isdigit(modestr[0]))
13119 static int FAST_FUNC
13120 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13122 return shell_builtin_ulimit(argv);
13125 /* ============ main() and helpers */
13128 * Called to exit the shell.
13137 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13138 save_history(line_input_state);
13140 status = exitstatus;
13141 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13142 if (setjmp(loc.loc)) {
13143 if (exception_type == EXEXIT)
13144 status = exitstatus;
13147 exception_handler = &loc;
13153 /*free(p); - we'll exit soon */
13156 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13157 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13160 flush_stdout_stderr();
13168 /* we will never free this */
13169 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13171 sigmode[SIGCHLD - 1] = S_DFL;
13172 setsignal(SIGCHLD);
13174 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13175 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13177 signal(SIGHUP, SIG_DFL);
13182 struct stat st1, st2;
13185 for (envp = environ; envp && *envp; envp++) {
13186 p = endofname(*envp);
13187 if (p != *envp && *p == '=') {
13188 setvareq(*envp, VEXPORT|VTEXTFIXED);
13192 setvareq((char*)defoptindvar, VTEXTFIXED);
13194 setvar0("PPID", utoa(getppid()));
13195 #if ENABLE_ASH_BASH_COMPAT
13196 p = lookupvar("SHLVL");
13197 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13198 if (!lookupvar("HOSTNAME")) {
13199 struct utsname uts;
13201 setvar0("HOSTNAME", uts.nodename);
13204 p = lookupvar("PWD");
13206 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13207 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13217 //usage:#define ash_trivial_usage
13218 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13219 //usage:#define ash_full_usage "\n\n"
13220 //usage: "Unix shell interpreter"
13222 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13223 //usage:# define sh_trivial_usage ash_trivial_usage
13224 //usage:# define sh_full_usage ash_full_usage
13226 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13227 //usage:# define bash_trivial_usage ash_trivial_usage
13228 //usage:# define bash_full_usage ash_full_usage
13232 * Process the shell command line arguments.
13235 procargs(char **argv)
13238 const char *xminusc;
13243 /* if (xargv[0]) - mmm, this is always true! */
13245 for (i = 0; i < NOPTS; i++)
13248 if (options(/*cmdline:*/ 1)) {
13249 /* it already printed err message */
13250 raise_exception(EXERROR);
13254 if (*xargv == NULL) {
13256 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13259 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13263 for (i = 0; i < NOPTS; i++)
13264 if (optlist[i] == 2)
13269 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13274 } else if (!sflag) {
13275 setinputfile(*xargv, 0);
13278 commandname = arg0;
13281 shellparam.p = xargv;
13282 #if ENABLE_ASH_GETOPTS
13283 shellparam.optind = 1;
13284 shellparam.optoff = -1;
13286 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13288 shellparam.nparam++;
13295 * Read /etc/profile, ~/.profile, $ENV.
13298 read_profile(const char *name)
13300 name = expandstr(name);
13301 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13308 * This routine is called when an error or an interrupt occurs in an
13309 * interactive shell and control is returned to the main command loop.
13310 * (In dash, this function is auto-generated by build machinery).
13319 /* from expand.c: */
13322 /* from input.c: */
13323 g_parsefile->left_in_buffer = 0;
13324 g_parsefile->left_in_line = 0; /* clear input buffer */
13327 /* from redir.c: */
13329 popredir(/*drop:*/ 0, /*restore:*/ 0);
13333 static short profile_buf[16384];
13334 extern int etext();
13338 * Main routine. We initialize things, parse the arguments, execute
13339 * profiles if we're a login shell, and then call cmdloop to execute
13340 * commands. The setjmp call sets up the location to jump to when an
13341 * exception occurs. When an exception occurs the variable "state"
13342 * is used to figure out how far we had gotten.
13344 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13345 int ash_main(int argc UNUSED_PARAM, char **argv)
13347 volatile smallint state;
13348 struct jmploc jmploc;
13349 struct stackmark smark;
13351 /* Initialize global data */
13355 #if ENABLE_ASH_ALIAS
13361 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13364 #if ENABLE_FEATURE_EDITING
13365 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13368 if (setjmp(jmploc.loc)) {
13374 e = exception_type;
13376 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13380 newline_and_flush(stderr);
13383 popstackmark(&smark);
13384 FORCE_INT_ON; /* enable interrupts */
13393 exception_handler = &jmploc;
13396 TRACE(("Shell args: "));
13397 trace_puts_args(argv);
13399 rootpid = getpid();
13402 setstackmark(&smark);
13405 if (argv[0] && argv[0][0] == '-')
13411 read_profile("/etc/profile");
13414 hp = lookupvar("HOME");
13416 read_profile("$HOME/.profile");
13422 getuid() == geteuid() && getgid() == getegid() &&
13426 const char *shinit = lookupvar("ENV");
13427 if (shinit != NULL && *shinit != '\0')
13428 read_profile(shinit);
13430 popstackmark(&smark);
13434 /* evalstring pushes parsefile stack.
13435 * Ensure we don't falsely claim that 0 (stdin)
13436 * is one of stacked source fds.
13437 * Testcase: ash -c 'exec 1>&0' must not complain. */
13438 // if (!sflag) g_parsefile->pf_fd = -1;
13439 // ^^ not necessary since now we special-case fd 0
13440 // in is_hidden_fd() to not be considered "hidden fd"
13441 evalstring(minusc, 0);
13444 if (sflag || minusc == NULL) {
13445 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13447 const char *hp = lookupvar("HISTFILE");
13449 hp = lookupvar("HOME");
13451 hp = concat_path_file(hp, ".ash_history");
13452 setvar0("HISTFILE", hp);
13454 hp = lookupvar("HISTFILE");
13458 line_input_state->hist_file = hp;
13459 # if ENABLE_FEATURE_SH_HISTFILESIZE
13460 hp = lookupvar("HISTFILESIZE");
13461 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13465 state4: /* XXX ??? - why isn't this before the "if" statement */
13473 extern void _mcleanup(void);
13477 TRACE(("End of main reached\n"));
13484 * Copyright (c) 1989, 1991, 1993, 1994
13485 * The Regents of the University of California. All rights reserved.
13487 * This code is derived from software contributed to Berkeley by
13488 * Kenneth Almquist.
13490 * Redistribution and use in source and binary forms, with or without
13491 * modification, are permitted provided that the following conditions
13493 * 1. Redistributions of source code must retain the above copyright
13494 * notice, this list of conditions and the following disclaimer.
13495 * 2. Redistributions in binary form must reproduce the above copyright
13496 * notice, this list of conditions and the following disclaimer in the
13497 * documentation and/or other materials provided with the distribution.
13498 * 3. Neither the name of the University nor the names of its contributors
13499 * may be used to endorse or promote products derived from this software
13500 * without specific prior written permission.
13502 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13503 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13504 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13505 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13506 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13507 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13508 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13509 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13510 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13511 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF