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 */
35 #define DEBUG_INTONOFF 0
39 #define JOBS ENABLE_ASH_JOB_CONTROL
43 #include <sys/times.h>
44 #include <sys/utsname.h> /* for setting $HOSTNAME */
46 #include "busybox.h" /* for applet_names */
48 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
49 /* Bionic at least up to version 24 has no glob() */
50 # undef ENABLE_ASH_INTERNAL_GLOB
51 # define ENABLE_ASH_INTERNAL_GLOB 1
54 #if !ENABLE_ASH_INTERNAL_GLOB
59 #include "shell_common.h"
60 #if ENABLE_SH_MATH_SUPPORT
63 #if ENABLE_ASH_RANDOM_SUPPORT
66 # define CLEAR_RANDOM_T(rnd) ((void)0)
69 #include "NUM_APPLETS.h"
71 /* STANDALONE does not make sense, and won't compile */
72 # undef CONFIG_FEATURE_SH_STANDALONE
73 # undef ENABLE_FEATURE_SH_STANDALONE
74 # undef IF_FEATURE_SH_STANDALONE
75 # undef IF_NOT_FEATURE_SH_STANDALONE
76 # define ENABLE_FEATURE_SH_STANDALONE 0
77 # define IF_FEATURE_SH_STANDALONE(...)
78 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
82 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
86 # error "Do not even bother, ash will not run on NOMMU machine"
92 //config: depends on !NOMMU
94 //config: Tha 'ash' shell adds about 60k in the default configuration and is
95 //config: the most complete and most pedantically correct shell included with
96 //config: busybox. This shell is actually a derivative of the Debian 'dash'
97 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
98 //config: (written by Kenneth Almquist) from NetBSD.
100 //config:config ASH_OPTIMIZE_FOR_SIZE
101 //config: bool "Optimize for size instead of speed"
103 //config: depends on ASH
105 //config: Compile ash for reduced size at the price of speed.
107 //config:config ASH_INTERNAL_GLOB
108 //config: bool "Use internal glob() implementation"
110 //config: depends on ASH
112 //config: Do not use glob() function from libc, use internal implementation.
113 //config: Use this if you are getting "glob.h: No such file or directory"
114 //config: or similar build errors.
116 //config:config ASH_RANDOM_SUPPORT
117 //config: bool "Pseudorandom generator and $RANDOM variable"
119 //config: depends on ASH
121 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
122 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
123 //config: You can reset the generator by using a specified start value.
124 //config: After "unset RANDOM" the generator will switch off and this
125 //config: variable will no longer have special treatment.
127 //config:config ASH_EXPAND_PRMT
128 //config: bool "Expand prompt string"
130 //config: depends on ASH
132 //config: "PS#" may contain volatile content, such as backquote commands.
133 //config: This option recreates the prompt string from the environment
134 //config: variable each time it is displayed.
136 //config:config ASH_BASH_COMPAT
137 //config: bool "bash-compatible extensions"
139 //config: depends on ASH
141 //config: Enable bash-compatible extensions.
143 //config:config ASH_IDLE_TIMEOUT
144 //config: bool "Idle timeout variable"
146 //config: depends on ASH
148 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
150 //config:config ASH_JOB_CONTROL
151 //config: bool "Job control"
153 //config: depends on ASH
155 //config: Enable job control in the ash shell.
157 //config:config ASH_ALIAS
158 //config: bool "Alias support"
160 //config: depends on ASH
162 //config: Enable alias support in the ash shell.
164 //config:config ASH_GETOPTS
165 //config: bool "Builtin getopt to parse positional parameters"
167 //config: depends on ASH
169 //config: Enable support for getopts builtin in ash.
171 //config:config ASH_BUILTIN_ECHO
172 //config: bool "Builtin version of 'echo'"
174 //config: depends on ASH
176 //config: Enable support for echo builtin in ash.
178 //config:config ASH_BUILTIN_PRINTF
179 //config: bool "Builtin version of 'printf'"
181 //config: depends on ASH
183 //config: Enable support for printf builtin in ash.
185 //config:config ASH_BUILTIN_TEST
186 //config: bool "Builtin version of 'test'"
188 //config: depends on ASH
190 //config: Enable support for test builtin in ash.
192 //config:config ASH_HELP
193 //config: bool "help builtin"
195 //config: depends on ASH
197 //config: Enable help builtin in ash.
199 //config:config ASH_CMDCMD
200 //config: bool "'command' command to override shell builtins"
202 //config: depends on ASH
204 //config: Enable support for the ash 'command' builtin, which allows
205 //config: you to run the specified command with the specified arguments,
206 //config: even when there is an ash builtin command with the same name.
208 //config:config ASH_MAIL
209 //config: bool "Check for new mail on interactive shells"
211 //config: depends on ASH
213 //config: Enable "check for new mail" function in the ash shell.
216 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
217 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
218 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
220 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
221 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
224 /* ============ Hash table sizes. Configurable. */
228 #define CMDTABLESIZE 31 /* should be prime */
231 /* ============ Shell options */
233 static const char *const optletters_optnames[] = {
248 #if ENABLE_ASH_BASH_COMPAT
257 #define optletters(n) optletters_optnames[n][0]
258 #define optnames(n) (optletters_optnames[n] + 1)
260 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
263 /* ============ Misc data */
265 #define msg_illnum "Illegal number: %s"
268 * We enclose jmp_buf in a structure so that we can declare pointers to
269 * jump locations. The global variable handler contains the location to
270 * jump to when an exception occurs, and the global variable exception_type
271 * contains a code identifying the exception. To implement nested
272 * exception handlers, the user should save the value of handler on entry
273 * to an inner scope, set handler to point to a jmploc structure for the
274 * inner scope, and restore handler on exit from the scope.
280 struct globals_misc {
281 uint8_t exitstatus; /* exit status of last command */
282 uint8_t back_exitstatus;/* exit status of backquoted command */
283 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
284 int rootpid; /* pid of main shell */
285 /* shell level: 0 for the main shell, 1 for its children, and so on */
287 #define rootshell (!shlvl)
288 char *minusc; /* argument to -c option */
290 char *curdir; // = nullstr; /* current working directory */
291 char *physdir; // = nullstr; /* physical working directory */
293 char *arg0; /* value of $0 */
295 struct jmploc *exception_handler;
297 volatile int suppress_int; /* counter */
298 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
299 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
300 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
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. :-))
447 # define INT_OFF do { \
448 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
453 # define INT_OFF do { \
460 * Called to raise an exception. Since C doesn't include exceptions, we
461 * just do a longjmp to the exception handler. The type of exception is
462 * stored in the global variable "exception_type".
464 static void raise_exception(int) NORETURN;
466 raise_exception(int e)
469 if (exception_handler == NULL)
474 longjmp(exception_handler->loc, 1);
477 #define raise_exception(e) do { \
478 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
479 raise_exception(e); \
484 * Called when a SIGINT is received. (If the user specifies
485 * that SIGINT is to be trapped or ignored using the trap builtin, then
486 * this routine is not called.) Suppressint is nonzero when interrupts
487 * are held using the INT_OFF macro. (The test for iflag is just
488 * defensive programming.)
490 static void raise_interrupt(void) NORETURN;
492 raise_interrupt(void)
495 /* Signal is not automatically unmasked after it is raised,
496 * do it ourself - unmask all signals */
497 sigprocmask_allsigs(SIG_UNBLOCK);
498 /* pending_sig = 0; - now done in signal_handler() */
500 if (!(rootshell && iflag)) {
501 /* Kill ourself with SIGINT */
502 signal(SIGINT, SIG_DFL);
505 /* bash: ^C even on empty command line sets $? */
506 exitstatus = SIGINT + 128;
507 raise_exception(EXINT);
511 #define raise_interrupt() do { \
512 TRACE(("raising interrupt on line %d\n", __LINE__)); \
517 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
521 if (--suppress_int == 0 && pending_int) {
526 # define INT_ON do { \
527 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
531 # define INT_ON int_on()
533 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
541 #define FORCE_INT_ON force_int_on()
543 #define SAVE_INT(v) ((v) = suppress_int)
545 #define RESTORE_INT(v) do { \
547 suppress_int = (v); \
548 if (suppress_int == 0 && pending_int) \
553 /* ============ Stdout/stderr output */
556 outstr(const char *p, FILE *file)
564 flush_stdout_stderr(void)
571 /* Was called outcslow(c,FILE*), but c was always '\n' */
573 newline_and_flush(FILE *dest)
581 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
583 out1fmt(const char *fmt, ...)
590 r = vprintf(fmt, ap);
596 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
598 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
605 ret = vsnprintf(outbuf, length, fmt, ap);
612 out1str(const char *p)
618 out2str(const char *p)
621 flush_stdout_stderr();
625 /* ============ Parser structures */
627 /* control characters in argument strings */
628 #define CTL_FIRST CTLESC
629 #define CTLESC ((unsigned char)'\201') /* escape next character */
630 #define CTLVAR ((unsigned char)'\202') /* variable defn */
631 #define CTLENDVAR ((unsigned char)'\203')
632 #define CTLBACKQ ((unsigned char)'\204')
633 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
634 #define CTLENDARI ((unsigned char)'\207')
635 #define CTLQUOTEMARK ((unsigned char)'\210')
636 #define CTL_LAST CTLQUOTEMARK
638 /* variable substitution byte (follows CTLVAR) */
639 #define VSTYPE 0x0f /* type of variable substitution */
640 #define VSNUL 0x10 /* colon--treat the empty string as unset */
642 /* values of VSTYPE field */
643 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
644 #define VSMINUS 0x2 /* ${var-text} */
645 #define VSPLUS 0x3 /* ${var+text} */
646 #define VSQUESTION 0x4 /* ${var?message} */
647 #define VSASSIGN 0x5 /* ${var=text} */
648 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
649 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
650 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
651 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
652 #define VSLENGTH 0xa /* ${#var} */
653 #if ENABLE_ASH_BASH_COMPAT
654 #define VSSUBSTR 0xc /* ${var:position:length} */
655 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
656 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
659 static const char dolatstr[] ALIGN1 = {
660 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
662 #define DOLATSTRLEN 6
681 #if ENABLE_ASH_BASH_COMPAT
698 smallint type; /* Nxxxx */
701 union node *redirect;
706 smallint pipe_backgnd;
707 struct nodelist *cmdlist;
713 union node *redirect;
726 union node *elsepart;
753 struct nodelist *backquote;
756 /* nfile and ndup layout must match!
757 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
758 * that it is actually NTO2 (>&file), and change its type.
775 char *_unused_expfname;
794 struct nredir nredir;
795 struct nbinary nbinary;
799 struct nclist nclist;
808 * NODE_EOF is returned by parsecmd when it encounters an end of file.
809 * It must be distinct from NULL.
811 #define NODE_EOF ((union node *) -1L)
814 struct nodelist *next;
827 freefunc(struct funcnode *f)
829 if (f && --f->count < 0)
834 /* ============ Debugging output */
838 static FILE *tracefile;
841 trace_printf(const char *fmt, ...)
848 fprintf(tracefile, "%u ", (int) time(NULL));
850 fprintf(tracefile, "[%u] ", (int) getpid());
852 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
854 vfprintf(tracefile, fmt, va);
859 trace_vprintf(const char *fmt, va_list va)
863 vfprintf(tracefile, fmt, va);
864 fprintf(tracefile, "\n");
868 trace_puts(const char *s)
876 trace_puts_quoted(char *s)
883 putc('"', tracefile);
884 for (p = s; *p; p++) {
885 switch ((unsigned char)*p) {
886 case '\n': c = 'n'; goto backslash;
887 case '\t': c = 't'; goto backslash;
888 case '\r': c = 'r'; goto backslash;
889 case '\"': c = '\"'; goto backslash;
890 case '\\': c = '\\'; goto backslash;
891 case CTLESC: c = 'e'; goto backslash;
892 case CTLVAR: c = 'v'; goto backslash;
893 case CTLBACKQ: c = 'q'; goto backslash;
895 putc('\\', tracefile);
899 if (*p >= ' ' && *p <= '~')
902 putc('\\', tracefile);
903 putc((*p >> 6) & 03, tracefile);
904 putc((*p >> 3) & 07, tracefile);
905 putc(*p & 07, tracefile);
910 putc('"', tracefile);
914 trace_puts_args(char **ap)
921 trace_puts_quoted(*ap);
923 putc('\n', tracefile);
926 putc(' ', tracefile);
941 /* leave open because libedit might be using it */
944 strcpy(s, "./trace");
946 if (!freopen(s, "a", tracefile)) {
947 fprintf(stderr, "Can't re-open %s\n", s);
952 tracefile = fopen(s, "a");
953 if (tracefile == NULL) {
954 fprintf(stderr, "Can't open %s\n", s);
960 flags = fcntl(fileno(tracefile), F_GETFL);
962 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
964 setlinebuf(tracefile);
965 fputs("\nTracing started.\n", tracefile);
969 indent(int amount, char *pfx, FILE *fp)
973 for (i = 0; i < amount; i++) {
974 if (pfx && i == amount - 1)
980 /* little circular references here... */
981 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
984 sharg(union node *arg, FILE *fp)
987 struct nodelist *bqlist;
988 unsigned char subtype;
990 if (arg->type != NARG) {
991 out1fmt("<node type %d>\n", arg->type);
994 bqlist = arg->narg.backquote;
995 for (p = arg->narg.text; *p; p++) {
996 switch ((unsigned char)*p) {
1005 if (subtype == VSLENGTH)
1013 if (subtype & VSNUL)
1016 switch (subtype & VSTYPE) {
1042 case VSTRIMRIGHTMAX:
1049 out1fmt("<subtype %d>", subtype);
1058 shtree(bqlist->n, -1, NULL, fp);
1069 shcmd(union node *cmd, FILE *fp)
1077 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1083 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1087 switch (np->nfile.type) {
1088 case NTO: s = ">>"+1; dftfd = 1; break;
1089 case NCLOBBER: s = ">|"; dftfd = 1; break;
1090 case NAPPEND: s = ">>"; dftfd = 1; break;
1091 #if ENABLE_ASH_BASH_COMPAT
1094 case NTOFD: s = ">&"; dftfd = 1; break;
1095 case NFROM: s = "<"; break;
1096 case NFROMFD: s = "<&"; break;
1097 case NFROMTO: s = "<>"; break;
1098 default: s = "*error*"; break;
1100 if (np->nfile.fd != dftfd)
1101 fprintf(fp, "%d", np->nfile.fd);
1103 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1104 fprintf(fp, "%d", np->ndup.dupfd);
1106 sharg(np->nfile.fname, fp);
1113 shtree(union node *n, int ind, char *pfx, FILE *fp)
1115 struct nodelist *lp;
1121 indent(ind, pfx, fp);
1123 if (n == NODE_EOF) {
1138 shtree(n->nbinary.ch1, ind, NULL, fp);
1141 shtree(n->nbinary.ch2, ind, NULL, fp);
1149 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1150 shtree(lp->n, 0, NULL, fp);
1154 if (n->npipe.pipe_backgnd)
1160 fprintf(fp, "<node type %d>", n->type);
1168 showtree(union node *n)
1170 trace_puts("showtree called\n");
1171 shtree(n, 1, NULL, stderr);
1177 /* ============ Parser data */
1180 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1183 struct strlist *next;
1190 struct strpush *prev; /* preceding string on stack */
1192 int prev_left_in_line;
1193 #if ENABLE_ASH_ALIAS
1194 struct alias *ap; /* if push was associated with an alias */
1196 char *string; /* remember the string since it may change */
1198 /* Remember last two characters for pungetc. */
1201 /* Number of outstanding calls to pungetc. */
1206 struct parsefile *prev; /* preceding file on stack */
1207 int linno; /* current line */
1208 int pf_fd; /* file descriptor (or -1 if string) */
1209 int left_in_line; /* number of chars left in this line */
1210 int left_in_buffer; /* number of chars left in this buffer past the line */
1211 char *next_to_pgetc; /* next char in buffer */
1212 char *buf; /* input buffer */
1213 struct strpush *strpush; /* for pushing strings at this level */
1214 struct strpush basestrpush; /* so pushing one is fast */
1216 /* Remember last two characters for pungetc. */
1219 /* Number of outstanding calls to pungetc. */
1223 static struct parsefile basepf; /* top level input file */
1224 static struct parsefile *g_parsefile = &basepf; /* current input file */
1225 static int startlinno; /* line # where last token started */
1226 static char *commandname; /* currently executing command */
1227 static struct strlist *cmdenviron; /* environment for builtin command */
1230 /* ============ Message printing */
1233 ash_vmsg(const char *msg, va_list ap)
1235 fprintf(stderr, "%s: ", arg0);
1237 if (strcmp(arg0, commandname))
1238 fprintf(stderr, "%s: ", commandname);
1239 if (!iflag || g_parsefile->pf_fd > 0)
1240 fprintf(stderr, "line %d: ", startlinno);
1242 vfprintf(stderr, msg, ap);
1243 newline_and_flush(stderr);
1247 * Exverror is called to raise the error exception. If the second argument
1248 * is not NULL then error prints an error message using printf style
1249 * formatting. It then raises the error exception.
1251 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1253 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1257 TRACE(("ash_vmsg_and_raise(%d):", cond));
1260 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1265 flush_stdout_stderr();
1266 raise_exception(cond);
1270 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1272 ash_msg_and_raise_error(const char *msg, ...)
1277 ash_vmsg_and_raise(EXERROR, msg, ap);
1282 static void raise_error_syntax(const char *) NORETURN;
1284 raise_error_syntax(const char *msg)
1286 ash_msg_and_raise_error("syntax error: %s", msg);
1290 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1292 ash_msg_and_raise(int cond, const char *msg, ...)
1297 ash_vmsg_and_raise(cond, msg, ap);
1303 * error/warning routines for external builtins
1306 ash_msg(const char *fmt, ...)
1316 * Return a string describing an error. The returned string may be a
1317 * pointer to a static buffer that will be overwritten on the next call.
1318 * Action describes the operation that got the error.
1321 errmsg(int e, const char *em)
1323 if (e == ENOENT || e == ENOTDIR) {
1330 /* ============ Memory allocation */
1333 /* I consider these wrappers nearly useless:
1334 * ok, they return you to nearest exception handler, but
1335 * how much memory do you leak in the process, making
1336 * memory starvation worse?
1339 ckrealloc(void * p, size_t nbytes)
1341 p = realloc(p, nbytes);
1343 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1348 ckmalloc(size_t nbytes)
1350 return ckrealloc(NULL, nbytes);
1354 ckzalloc(size_t nbytes)
1356 return memset(ckmalloc(nbytes), 0, nbytes);
1360 ckstrdup(const char *s)
1362 char *p = strdup(s);
1364 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1368 /* Using bbox equivalents. They exit if out of memory */
1369 # define ckrealloc xrealloc
1370 # define ckmalloc xmalloc
1371 # define ckzalloc xzalloc
1372 # define ckstrdup xstrdup
1376 * It appears that grabstackstr() will barf with such alignments
1377 * because stalloc() will return a string allocated in a new stackblock.
1379 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1381 /* Most machines require the value returned from malloc to be aligned
1382 * in some way. The following macro will get this right
1383 * on many machines. */
1384 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1385 /* Minimum size of a block */
1386 MINSIZE = SHELL_ALIGN(504),
1389 struct stack_block {
1390 struct stack_block *prev;
1391 char space[MINSIZE];
1395 struct stack_block *stackp;
1401 struct globals_memstack {
1402 struct stack_block *g_stackp; // = &stackbase;
1403 char *g_stacknxt; // = stackbase.space;
1404 char *sstrend; // = stackbase.space + MINSIZE;
1405 size_t g_stacknleft; // = MINSIZE;
1406 struct stack_block stackbase;
1408 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1409 #define G_memstack (*ash_ptr_to_globals_memstack)
1410 #define g_stackp (G_memstack.g_stackp )
1411 #define g_stacknxt (G_memstack.g_stacknxt )
1412 #define sstrend (G_memstack.sstrend )
1413 #define g_stacknleft (G_memstack.g_stacknleft)
1414 #define stackbase (G_memstack.stackbase )
1415 #define INIT_G_memstack() do { \
1416 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1418 g_stackp = &stackbase; \
1419 g_stacknxt = stackbase.space; \
1420 g_stacknleft = MINSIZE; \
1421 sstrend = stackbase.space + MINSIZE; \
1425 #define stackblock() ((void *)g_stacknxt)
1426 #define stackblocksize() g_stacknleft
1429 * Parse trees for commands are allocated in lifo order, so we use a stack
1430 * to make this more efficient, and also to avoid all sorts of exception
1431 * handling code to handle interrupts in the middle of a parse.
1433 * The size 504 was chosen because the Ultrix malloc handles that size
1437 stalloc(size_t nbytes)
1442 aligned = SHELL_ALIGN(nbytes);
1443 if (aligned > g_stacknleft) {
1446 struct stack_block *sp;
1448 blocksize = aligned;
1449 if (blocksize < MINSIZE)
1450 blocksize = MINSIZE;
1451 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1452 if (len < blocksize)
1453 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1456 sp->prev = g_stackp;
1457 g_stacknxt = sp->space;
1458 g_stacknleft = blocksize;
1459 sstrend = g_stacknxt + blocksize;
1464 g_stacknxt += aligned;
1465 g_stacknleft -= aligned;
1470 stzalloc(size_t nbytes)
1472 return memset(stalloc(nbytes), 0, nbytes);
1479 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1480 write(STDERR_FILENO, "stunalloc\n", 10);
1484 g_stacknleft += g_stacknxt - (char *)p;
1489 * Like strdup but works with the ash stack.
1492 sstrdup(const char *p)
1494 size_t len = strlen(p) + 1;
1495 return memcpy(stalloc(len), p, len);
1499 grabstackblock(size_t len)
1505 pushstackmark(struct stackmark *mark, size_t len)
1507 mark->stackp = g_stackp;
1508 mark->stacknxt = g_stacknxt;
1509 mark->stacknleft = g_stacknleft;
1510 grabstackblock(len);
1514 setstackmark(struct stackmark *mark)
1516 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1520 popstackmark(struct stackmark *mark)
1522 struct stack_block *sp;
1528 while (g_stackp != mark->stackp) {
1530 g_stackp = sp->prev;
1533 g_stacknxt = mark->stacknxt;
1534 g_stacknleft = mark->stacknleft;
1535 sstrend = mark->stacknxt + mark->stacknleft;
1540 * When the parser reads in a string, it wants to stick the string on the
1541 * stack and only adjust the stack pointer when it knows how big the
1542 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1543 * of space on top of the stack and stackblocklen returns the length of
1544 * this block. Growstackblock will grow this space by at least one byte,
1545 * possibly moving it (like realloc). Grabstackblock actually allocates the
1546 * part of the block that has been used.
1549 growstackblock(void)
1553 newlen = g_stacknleft * 2;
1554 if (newlen < g_stacknleft)
1555 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1559 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1560 struct stack_block *sp;
1561 struct stack_block *prevstackp;
1566 prevstackp = sp->prev;
1567 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1568 sp = ckrealloc(sp, grosslen);
1569 sp->prev = prevstackp;
1571 g_stacknxt = sp->space;
1572 g_stacknleft = newlen;
1573 sstrend = sp->space + newlen;
1576 char *oldspace = g_stacknxt;
1577 size_t oldlen = g_stacknleft;
1578 char *p = stalloc(newlen);
1580 /* free the space we just allocated */
1581 g_stacknxt = memcpy(p, oldspace, oldlen);
1582 g_stacknleft += newlen;
1587 * The following routines are somewhat easier to use than the above.
1588 * The user declares a variable of type STACKSTR, which may be declared
1589 * to be a register. The macro STARTSTACKSTR initializes things. Then
1590 * the user uses the macro STPUTC to add characters to the string. In
1591 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1592 * grown as necessary. When the user is done, she can just leave the
1593 * string there and refer to it using stackblock(). Or she can allocate
1594 * the space for it using grabstackstr(). If it is necessary to allow
1595 * someone else to use the stack temporarily and then continue to grow
1596 * the string, the user should use grabstack to allocate the space, and
1597 * then call ungrabstr(p) to return to the previous mode of operation.
1599 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1600 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1601 * is space for at least one character.
1606 size_t len = stackblocksize();
1608 return (char *)stackblock() + len;
1612 * Called from CHECKSTRSPACE.
1615 makestrspace(size_t newlen, char *p)
1617 size_t len = p - g_stacknxt;
1623 size = stackblocksize();
1625 if (nleft >= newlen)
1629 return (char *)stackblock() + len;
1633 stack_nputstr(const char *s, size_t n, char *p)
1635 p = makestrspace(n, p);
1636 p = (char *)memcpy(p, s, n) + n;
1641 stack_putstr(const char *s, char *p)
1643 return stack_nputstr(s, strlen(s), p);
1647 _STPUTC(int c, char *p)
1655 #define STARTSTACKSTR(p) ((p) = stackblock())
1656 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1657 #define CHECKSTRSPACE(n, p) do { \
1660 size_t m = sstrend - q; \
1662 (p) = makestrspace(l, q); \
1664 #define USTPUTC(c, p) (*(p)++ = (c))
1665 #define STACKSTRNUL(p) do { \
1666 if ((p) == sstrend) \
1667 (p) = growstackstr(); \
1670 #define STUNPUTC(p) (--(p))
1671 #define STTOPC(p) ((p)[-1])
1672 #define STADJUST(amount, p) ((p) += (amount))
1674 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1675 #define ungrabstackstr(s, p) stunalloc(s)
1676 #define stackstrend() ((void *)sstrend)
1679 /* ============ String helpers */
1682 * prefix -- see if pfx is a prefix of string.
1685 prefix(const char *string, const char *pfx)
1688 if (*pfx++ != *string++)
1691 return (char *) string;
1695 * Check for a valid number. This should be elsewhere.
1698 is_number(const char *p)
1703 } while (*++p != '\0');
1708 * Convert a string of digits to an integer, printing an error message on
1712 number(const char *s)
1715 ash_msg_and_raise_error(msg_illnum, s);
1720 * Produce a possibly single quoted string suitable as input to the shell.
1721 * The return string is allocated on the stack.
1724 single_quote(const char *s)
1734 len = strchrnul(s, '\'') - s;
1736 q = p = makestrspace(len + 3, p);
1739 q = (char *)memcpy(q, s, len) + len;
1748 do len++; while (*++s == '\'');
1750 q = p = makestrspace(len + 3, p);
1753 q = (char *)memcpy(q, s - len, len) + len;
1761 return stackblock();
1765 /* ============ nextopt */
1767 static char **argptr; /* argument list for builtin commands */
1768 static char *optionarg; /* set by nextopt (like getopt) */
1769 static char *optptr; /* used by nextopt */
1772 * XXX - should get rid of. Have all builtins use getopt(3).
1773 * The library getopt must have the BSD extension static variable
1774 * "optreset", otherwise it can't be used within the shell safely.
1776 * Standard option processing (a la getopt) for builtin routines.
1777 * The only argument that is passed to nextopt is the option string;
1778 * the other arguments are unnecessary. It returns the character,
1779 * or '\0' on end of input.
1782 nextopt(const char *optstring)
1789 if (p == NULL || *p == '\0') {
1790 /* We ate entire "-param", take next one */
1796 if (*++p == '\0') /* just "-" ? */
1799 if (LONE_DASH(p)) /* "--" ? */
1801 /* p => next "-param" */
1803 /* p => some option char in the middle of a "-param" */
1805 for (q = optstring; *q != c;) {
1807 ash_msg_and_raise_error("illegal option -%c", c);
1815 ash_msg_and_raise_error("no arg for -%c option", c);
1825 /* ============ Shell variables */
1828 * The parsefile structure pointed to by the global variable parsefile
1829 * contains information about the current file being read.
1832 int nparam; /* # of positional parameters (without $0) */
1833 #if ENABLE_ASH_GETOPTS
1834 int optind; /* next parameter to be processed by getopts */
1835 int optoff; /* used by getopts */
1837 unsigned char malloced; /* if parameter list dynamically allocated */
1838 char **p; /* parameter list */
1842 * Free the list of positional parameters.
1845 freeparam(volatile struct shparam *param)
1847 if (param->malloced) {
1849 ap = ap1 = param->p;
1856 #if ENABLE_ASH_GETOPTS
1857 static void FAST_FUNC getoptsreset(const char *value);
1861 struct var *next; /* next entry in hash list */
1862 int flags; /* flags are defined above */
1863 const char *var_text; /* name=value */
1864 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1865 /* the variable gets set/unset */
1869 struct localvar *next; /* next local variable in list */
1870 struct var *vp; /* the variable that was made local */
1871 int flags; /* saved flags */
1872 const char *text; /* saved text */
1876 #define VEXPORT 0x01 /* variable is exported */
1877 #define VREADONLY 0x02 /* variable cannot be modified */
1878 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1879 #define VTEXTFIXED 0x08 /* text is statically allocated */
1880 #define VSTACK 0x10 /* text is allocated on the stack */
1881 #define VUNSET 0x20 /* the variable is not set */
1882 #define VNOFUNC 0x40 /* don't call the callback function */
1883 #define VNOSET 0x80 /* do not set variable - just readonly test */
1884 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1885 #if ENABLE_ASH_RANDOM_SUPPORT
1886 # define VDYNAMIC 0x200 /* dynamic variable */
1892 /* Need to be before varinit_data[] */
1893 #if ENABLE_LOCALE_SUPPORT
1894 static void FAST_FUNC
1895 change_lc_all(const char *value)
1897 if (value && *value != '\0')
1898 setlocale(LC_ALL, value);
1900 static void FAST_FUNC
1901 change_lc_ctype(const char *value)
1903 if (value && *value != '\0')
1904 setlocale(LC_CTYPE, value);
1908 static void chkmail(void);
1909 static void changemail(const char *var_value) FAST_FUNC;
1911 # define chkmail() ((void)0)
1913 static void changepath(const char *) FAST_FUNC;
1914 #if ENABLE_ASH_RANDOM_SUPPORT
1915 static void change_random(const char *) FAST_FUNC;
1918 static const struct {
1920 const char *var_text;
1921 void (*var_func)(const char *) FAST_FUNC;
1922 } varinit_data[] = {
1924 * Note: VEXPORT would not work correctly here for NOFORK applets:
1925 * some environment strings may be constant.
1927 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1929 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1930 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1932 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1933 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1934 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1935 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1936 #if ENABLE_ASH_GETOPTS
1937 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1939 #if ENABLE_ASH_RANDOM_SUPPORT
1940 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1942 #if ENABLE_LOCALE_SUPPORT
1943 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1944 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1946 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1947 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1953 struct globals_var {
1954 struct shparam shellparam; /* $@ current positional parameters */
1955 struct redirtab *redirlist;
1956 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1957 struct var *vartab[VTABSIZE];
1958 struct var varinit[ARRAY_SIZE(varinit_data)];
1960 extern struct globals_var *const ash_ptr_to_globals_var;
1961 #define G_var (*ash_ptr_to_globals_var)
1962 #define shellparam (G_var.shellparam )
1963 //#define redirlist (G_var.redirlist )
1964 #define preverrout_fd (G_var.preverrout_fd)
1965 #define vartab (G_var.vartab )
1966 #define varinit (G_var.varinit )
1967 #define INIT_G_var() do { \
1969 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1971 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1972 varinit[i].flags = varinit_data[i].flags; \
1973 varinit[i].var_text = varinit_data[i].var_text; \
1974 varinit[i].var_func = varinit_data[i].var_func; \
1978 #define vifs varinit[0]
1980 # define vmail (&vifs)[1]
1981 # define vmpath (&vmail)[1]
1982 # define vpath (&vmpath)[1]
1984 # define vpath (&vifs)[1]
1986 #define vps1 (&vpath)[1]
1987 #define vps2 (&vps1)[1]
1988 #define vps4 (&vps2)[1]
1989 #if ENABLE_ASH_GETOPTS
1990 # define voptind (&vps4)[1]
1991 # if ENABLE_ASH_RANDOM_SUPPORT
1992 # define vrandom (&voptind)[1]
1995 # if ENABLE_ASH_RANDOM_SUPPORT
1996 # define vrandom (&vps4)[1]
2001 * The following macros access the values of the above variables.
2002 * They have to skip over the name. They return the null string
2003 * for unset variables.
2005 #define ifsval() (vifs.var_text + 4)
2006 #define ifsset() ((vifs.flags & VUNSET) == 0)
2008 # define mailval() (vmail.var_text + 5)
2009 # define mpathval() (vmpath.var_text + 9)
2010 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2012 #define pathval() (vpath.var_text + 5)
2013 #define ps1val() (vps1.var_text + 4)
2014 #define ps2val() (vps2.var_text + 4)
2015 #define ps4val() (vps4.var_text + 4)
2016 #if ENABLE_ASH_GETOPTS
2017 # define optindval() (voptind.var_text + 7)
2020 #if ENABLE_ASH_GETOPTS
2021 static void FAST_FUNC
2022 getoptsreset(const char *value)
2024 shellparam.optind = number(value) ?: 1;
2025 shellparam.optoff = -1;
2030 * Compares two strings up to the first = or '\0'. The first
2031 * string must be terminated by '='; the second may be terminated by
2032 * either '=' or '\0'.
2035 varcmp(const char *p, const char *q)
2039 while ((c = *p) == (d = *q)) {
2040 if (c == '\0' || c == '=')
2054 * Find the appropriate entry in the hash table from the name.
2056 static struct var **
2057 hashvar(const char *p)
2061 hashval = ((unsigned char) *p) << 4;
2062 while (*p && *p != '=')
2063 hashval += (unsigned char) *p++;
2064 return &vartab[hashval % VTABSIZE];
2068 vpcmp(const void *a, const void *b)
2070 return varcmp(*(const char **)a, *(const char **)b);
2074 * This routine initializes the builtin variables.
2084 * PS1 depends on uid
2086 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2087 vps1.var_text = "PS1=\\w \\$ ";
2090 vps1.var_text = "PS1=# ";
2093 end = vp + ARRAY_SIZE(varinit);
2095 vpp = hashvar(vp->var_text);
2098 } while (++vp < end);
2101 static struct var **
2102 findvar(struct var **vpp, const char *name)
2104 for (; *vpp; vpp = &(*vpp)->next) {
2105 if (varcmp((*vpp)->var_text, name) == 0) {
2113 * Find the value of a variable. Returns NULL if not set.
2115 static const char* FAST_FUNC
2116 lookupvar(const char *name)
2120 v = *findvar(hashvar(name), name);
2122 #if ENABLE_ASH_RANDOM_SUPPORT
2124 * Dynamic variables are implemented roughly the same way they are
2125 * in bash. Namely, they're "special" so long as they aren't unset.
2126 * As soon as they're unset, they're no longer dynamic, and dynamic
2127 * lookup will no longer happen at that point. -- PFM.
2129 if (v->flags & VDYNAMIC)
2132 if (!(v->flags & VUNSET))
2133 return var_end(v->var_text);
2139 reinit_unicode_for_ash(void)
2141 /* Unicode support should be activated even if LANG is set
2142 * _during_ shell execution, not only if it was set when
2143 * shell was started. Therefore, re-check LANG every time:
2145 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2146 || ENABLE_UNICODE_USING_LOCALE
2148 const char *s = lookupvar("LC_ALL");
2149 if (!s) s = lookupvar("LC_CTYPE");
2150 if (!s) s = lookupvar("LANG");
2156 * Search the environment of a builtin command.
2159 bltinlookup(const char *name)
2163 for (sp = cmdenviron; sp; sp = sp->next) {
2164 if (varcmp(sp->text, name) == 0)
2165 return var_end(sp->text);
2167 return lookupvar(name);
2171 * Same as setvar except that the variable and value are passed in
2172 * the first argument as name=value. Since the first argument will
2173 * be actually stored in the table, it should not be a string that
2175 * Called with interrupts off.
2178 setvareq(char *s, int flags)
2180 struct var *vp, **vpp;
2183 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2184 vp = *findvar(vpp, s);
2186 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2189 if (flags & VNOSAVE)
2193 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2199 if (vp->var_func && !(flags & VNOFUNC))
2200 vp->var_func(var_end(s));
2202 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2203 free((char*)vp->var_text);
2205 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2207 /* variable s is not found */
2210 vp = ckzalloc(sizeof(*vp));
2212 /*vp->func = NULL; - ckzalloc did it */
2215 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2222 * Set the value of a variable. The flags argument is ored with the
2223 * flags of the variable. If val is NULL, the variable is unset.
2226 setvar(const char *name, const char *val, int flags)
2234 q = endofname(name);
2235 p = strchrnul(q, '=');
2237 if (!namelen || p != q)
2238 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2243 vallen = strlen(val);
2247 nameeq = ckmalloc(namelen + vallen + 2);
2248 p = memcpy(nameeq, name, namelen) + namelen;
2251 p = memcpy(p, val, vallen) + vallen;
2254 setvareq(nameeq, flags | VNOSAVE);
2258 static void FAST_FUNC
2259 setvar0(const char *name, const char *val)
2261 setvar(name, val, 0);
2265 * Unset the specified variable.
2268 unsetvar(const char *s)
2274 vpp = findvar(hashvar(s), s);
2278 int flags = vp->flags;
2281 if (flags & VREADONLY)
2283 #if ENABLE_ASH_RANDOM_SUPPORT
2284 vp->flags &= ~VDYNAMIC;
2288 if ((flags & VSTRFIXED) == 0) {
2290 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2291 free((char*)vp->var_text);
2297 vp->flags &= ~VEXPORT;
2307 * Process a linked list of variable assignments.
2310 listsetvar(struct strlist *list_set_var, int flags)
2312 struct strlist *lp = list_set_var;
2318 setvareq(lp->text, flags);
2325 * Generate a list of variables satisfying the given conditions.
2328 listvars(int on, int off, char ***end)
2339 for (vp = *vpp; vp; vp = vp->next) {
2340 if ((vp->flags & mask) == on) {
2341 if (ep == stackstrend())
2342 ep = growstackstr();
2343 *ep++ = (char*)vp->var_text;
2346 } while (++vpp < vartab + VTABSIZE);
2347 if (ep == stackstrend())
2348 ep = growstackstr();
2352 return grabstackstr(ep);
2356 /* ============ Path search helper
2358 * The variable path (passed by reference) should be set to the start
2359 * of the path before the first call; path_advance will update
2360 * this value as it proceeds. Successive calls to path_advance will return
2361 * the possible path expansions in sequence. If an option (indicated by
2362 * a percent sign) appears in the path entry then the global variable
2363 * pathopt will be set to point to it; otherwise pathopt will be set to
2366 static const char *pathopt; /* set by path_advance */
2369 path_advance(const char **path, const char *name)
2379 for (p = start; *p && *p != ':' && *p != '%'; p++)
2381 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2382 while (stackblocksize() < len)
2386 memcpy(q, start, p - start);
2394 while (*p && *p != ':')
2401 return stalloc(len);
2405 /* ============ Prompt */
2407 static smallint doprompt; /* if set, prompt the user */
2408 static smallint needprompt; /* true if interactive and at start of line */
2410 #if ENABLE_FEATURE_EDITING
2411 static line_input_t *line_input_state;
2412 static const char *cmdedit_prompt;
2414 putprompt(const char *s)
2416 if (ENABLE_ASH_EXPAND_PRMT) {
2417 free((char*)cmdedit_prompt);
2418 cmdedit_prompt = ckstrdup(s);
2425 putprompt(const char *s)
2431 #if ENABLE_ASH_EXPAND_PRMT
2432 /* expandstr() needs parsing machinery, so it is far away ahead... */
2433 static const char *expandstr(const char *ps);
2435 #define expandstr(s) s
2439 setprompt_if(smallint do_set, int whichprompt)
2442 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2449 switch (whichprompt) {
2459 #if ENABLE_ASH_EXPAND_PRMT
2460 pushstackmark(&smark, stackblocksize());
2462 putprompt(expandstr(prompt));
2463 #if ENABLE_ASH_EXPAND_PRMT
2464 popstackmark(&smark);
2469 /* ============ The cd and pwd commands */
2471 #define CD_PHYSICAL 1
2481 while ((i = nextopt("LP")) != '\0') {
2483 flags ^= CD_PHYSICAL;
2492 * Update curdir (the name of the current directory) in response to a
2496 updatepwd(const char *dir)
2503 cdcomppath = sstrdup(dir);
2506 if (curdir == nullstr)
2508 new = stack_putstr(curdir, new);
2510 new = makestrspace(strlen(dir) + 2, new);
2511 lim = (char *)stackblock() + 1;
2515 if (new > lim && *lim == '/')
2520 if (dir[1] == '/' && dir[2] != '/') {
2526 p = strtok(cdcomppath, "/");
2530 if (p[1] == '.' && p[2] == '\0') {
2542 new = stack_putstr(p, new);
2545 p = strtok(NULL, "/");
2550 return stackblock();
2554 * Find out what the current directory is. If we already know the current
2555 * directory, this routine returns immediately.
2560 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2561 return dir ? dir : nullstr;
2565 setpwd(const char *val, int setold)
2569 oldcur = dir = curdir;
2572 setvar("OLDPWD", oldcur, VEXPORT);
2575 if (physdir != nullstr) {
2576 if (physdir != oldcur)
2580 if (oldcur == val || !val) {
2586 dir = ckstrdup(val);
2587 if (oldcur != dir && oldcur != nullstr) {
2592 setvar("PWD", dir, VEXPORT);
2595 static void hashcd(void);
2598 * Actually do the chdir. We also call hashcd to let other routines
2599 * know that the current directory has changed.
2602 docd(const char *dest, int flags)
2604 const char *dir = NULL;
2607 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2610 if (!(flags & CD_PHYSICAL)) {
2611 dir = updatepwd(dest);
2625 static int FAST_FUNC
2626 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2638 dest = bltinlookup("HOME");
2639 else if (LONE_DASH(dest)) {
2640 dest = bltinlookup("OLDPWD");
2662 path = bltinlookup("CDPATH");
2665 p = path_advance(&path, dest);
2666 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2670 if (!docd(p, flags))
2681 ash_msg_and_raise_error("can't cd to %s", dest);
2684 if (flags & CD_PRINT)
2685 out1fmt("%s\n", curdir);
2689 static int FAST_FUNC
2690 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2693 const char *dir = curdir;
2697 if (physdir == nullstr)
2701 out1fmt("%s\n", dir);
2706 /* ============ ... */
2709 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2711 /* Syntax classes */
2712 #define CWORD 0 /* character is nothing special */
2713 #define CNL 1 /* newline character */
2714 #define CBACK 2 /* a backslash character */
2715 #define CSQUOTE 3 /* single quote */
2716 #define CDQUOTE 4 /* double quote */
2717 #define CENDQUOTE 5 /* a terminating quote */
2718 #define CBQUOTE 6 /* backwards single quote */
2719 #define CVAR 7 /* a dollar sign */
2720 #define CENDVAR 8 /* a '}' character */
2721 #define CLP 9 /* a left paren in arithmetic */
2722 #define CRP 10 /* a right paren in arithmetic */
2723 #define CENDFILE 11 /* end of file */
2724 #define CCTL 12 /* like CWORD, except it must be escaped */
2725 #define CSPCL 13 /* these terminate a word */
2726 #define CIGN 14 /* character should be ignored */
2729 #if ENABLE_ASH_ALIAS
2733 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2735 #if ENABLE_SH_MATH_SUPPORT
2736 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2738 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2740 static const uint16_t S_I_T[] ALIGN2 = {
2741 #if ENABLE_ASH_ALIAS
2742 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2744 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2745 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2746 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2747 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2748 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2749 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2750 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2751 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2752 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2753 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2754 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2755 #if !USE_SIT_FUNCTION
2756 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2757 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2758 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2762 /* Constants below must match table above */
2764 #if ENABLE_ASH_ALIAS
2765 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2767 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2768 CNL_CNL_CNL_CNL , /* 2 */
2769 CWORD_CCTL_CCTL_CWORD , /* 3 */
2770 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2771 CVAR_CVAR_CWORD_CVAR , /* 5 */
2772 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2773 CSPCL_CWORD_CWORD_CLP , /* 7 */
2774 CSPCL_CWORD_CWORD_CRP , /* 8 */
2775 CBACK_CBACK_CCTL_CBACK , /* 9 */
2776 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2777 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2778 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2779 CWORD_CWORD_CWORD_CWORD , /* 13 */
2780 CCTL_CCTL_CCTL_CCTL , /* 14 */
2783 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2784 * caller must ensure proper cast on it if c is *char_ptr!
2786 /* Values for syntax param */
2787 #define BASESYNTAX 0 /* not in quotes */
2788 #define DQSYNTAX 1 /* in double quotes */
2789 #define SQSYNTAX 2 /* in single quotes */
2790 #define ARISYNTAX 3 /* in arithmetic */
2791 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2793 #if USE_SIT_FUNCTION
2796 SIT(int c, int syntax)
2798 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2799 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2801 * This causes '/' to be prepended with CTLESC in dquoted string,
2802 * making "./file"* treated incorrectly because we feed
2803 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2804 * The "homegrown" glob implementation is okay with that,
2805 * but glibc one isn't. With '/' always treated as CWORD,
2808 # if ENABLE_ASH_ALIAS
2809 static const uint8_t syntax_index_table[] ALIGN1 = {
2810 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2811 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2812 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2816 static const uint8_t syntax_index_table[] ALIGN1 = {
2817 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2818 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2819 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2828 # if ENABLE_ASH_ALIAS
2834 /* Cast is purely for paranoia here,
2835 * just in case someone passed signed char to us */
2836 if ((unsigned char)c >= CTL_FIRST
2837 && (unsigned char)c <= CTL_LAST
2841 s = strchrnul(spec_symbls, c);
2844 indx = syntax_index_table[s - spec_symbls];
2846 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2849 #else /* !USE_SIT_FUNCTION */
2851 static const uint8_t syntax_index_table[] ALIGN1 = {
2852 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2853 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2863 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2864 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2886 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2887 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2888 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2890 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2892 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2893 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2894 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2895 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2896 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2897 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2898 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2899 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2900 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2901 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2914 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2915 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2918 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2946 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2947 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2951 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2979 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2980 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2981 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2982 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2984 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2985 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2986 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2987 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2988 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2989 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2990 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2991 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3110 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3111 # if ENABLE_ASH_ALIAS
3112 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3116 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3118 #endif /* !USE_SIT_FUNCTION */
3121 /* ============ Alias handling */
3123 #if ENABLE_ASH_ALIAS
3125 #define ALIASINUSE 1
3136 static struct alias **atab; // [ATABSIZE];
3137 #define INIT_G_alias() do { \
3138 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3142 static struct alias **
3143 __lookupalias(const char *name)
3145 unsigned int hashval;
3152 ch = (unsigned char)*p;
3156 ch = (unsigned char)*++p;
3158 app = &atab[hashval % ATABSIZE];
3160 for (; *app; app = &(*app)->next) {
3161 if (strcmp(name, (*app)->name) == 0) {
3169 static struct alias *
3170 lookupalias(const char *name, int check)
3172 struct alias *ap = *__lookupalias(name);
3174 if (check && ap && (ap->flag & ALIASINUSE))
3179 static struct alias *
3180 freealias(struct alias *ap)
3184 if (ap->flag & ALIASINUSE) {
3185 ap->flag |= ALIASDEAD;
3197 setalias(const char *name, const char *val)
3199 struct alias *ap, **app;
3201 app = __lookupalias(name);
3205 if (!(ap->flag & ALIASINUSE)) {
3208 ap->val = ckstrdup(val);
3209 ap->flag &= ~ALIASDEAD;
3212 ap = ckzalloc(sizeof(struct alias));
3213 ap->name = ckstrdup(name);
3214 ap->val = ckstrdup(val);
3215 /*ap->flag = 0; - ckzalloc did it */
3216 /*ap->next = NULL;*/
3223 unalias(const char *name)
3227 app = __lookupalias(name);
3231 *app = freealias(*app);
3242 struct alias *ap, **app;
3246 for (i = 0; i < ATABSIZE; i++) {
3248 for (ap = *app; ap; ap = *app) {
3249 *app = freealias(*app);
3259 printalias(const struct alias *ap)
3261 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3265 * TODO - sort output
3267 static int FAST_FUNC
3268 aliascmd(int argc UNUSED_PARAM, char **argv)
3277 for (i = 0; i < ATABSIZE; i++) {
3278 for (ap = atab[i]; ap; ap = ap->next) {
3284 while ((n = *++argv) != NULL) {
3285 v = strchr(n+1, '=');
3286 if (v == NULL) { /* n+1: funny ksh stuff */
3287 ap = *__lookupalias(n);
3289 fprintf(stderr, "%s: %s not found\n", "alias", n);
3302 static int FAST_FUNC
3303 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3307 while ((i = nextopt("a")) != '\0') {
3313 for (i = 0; *argptr; argptr++) {
3314 if (unalias(*argptr)) {
3315 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3323 #endif /* ASH_ALIAS */
3326 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3329 #define FORK_NOJOB 2
3331 /* mode flags for showjob(s) */
3332 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3333 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3334 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3335 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3338 * A job structure contains information about a job. A job is either a
3339 * single process or a set of processes contained in a pipeline. In the
3340 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3344 pid_t ps_pid; /* process id */
3345 int ps_status; /* last process status from wait() */
3346 char *ps_cmd; /* text of command being run */
3350 struct procstat ps0; /* status of process */
3351 struct procstat *ps; /* status or processes when more than one */
3353 int stopstatus; /* status of a stopped job */
3356 nprocs: 16, /* number of processes */
3358 #define JOBRUNNING 0 /* at least one proc running */
3359 #define JOBSTOPPED 1 /* all procs are stopped */
3360 #define JOBDONE 2 /* all procs are completed */
3362 sigint: 1, /* job was killed by SIGINT */
3363 jobctl: 1, /* job running under job control */
3365 waited: 1, /* true if this entry has been waited for */
3366 used: 1, /* true if this entry is in used */
3367 changed: 1; /* true if status has changed */
3368 struct job *prev_job; /* previous job */
3371 static struct job *makejob(/*union node *,*/ int);
3372 static int forkshell(struct job *, union node *, int);
3373 static int waitforjob(struct job *);
3376 enum { doing_jobctl = 0 };
3377 #define setjobctl(on) do {} while (0)
3379 static smallint doing_jobctl; //references:8
3380 static void setjobctl(int);
3387 ignoresig(int signo)
3389 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3390 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3391 /* No, need to do it */
3392 signal(signo, SIG_IGN);
3394 sigmode[signo - 1] = S_HARD_IGN;
3398 * Only one usage site - in setsignal()
3401 signal_handler(int signo)
3403 if (signo == SIGCHLD) {
3409 gotsig[signo - 1] = 1;
3410 pending_sig = signo;
3412 if (signo == SIGINT && !trap[SIGINT]) {
3413 if (!suppress_int) {
3415 raise_interrupt(); /* does not return */
3422 * Set the signal handler for the specified signal. The routine figures
3423 * out what it should be set to.
3426 setsignal(int signo)
3429 char cur_act, new_act;
3430 struct sigaction act;
3434 if (t != NULL) { /* trap for this sig is set */
3436 if (t[0] == '\0') /* trap is "": ignore this sig */
3440 if (rootshell && new_act == S_DFL) {
3443 if (iflag || minusc || sflag == 0)
3452 * "In all cases, bash ignores SIGQUIT. Non-builtin
3453 * commands run by bash have signal handlers
3454 * set to the values inherited by the shell
3455 * from its parent". */
3471 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3472 //whereas we have to restore it to what shell got on entry
3473 //from the parent. See comment above
3475 if (signo == SIGCHLD)
3478 t = &sigmode[signo - 1];
3481 /* current setting is not yet known */
3482 if (sigaction(signo, NULL, &act)) {
3483 /* pretend it worked; maybe we should give a warning,
3484 * but other shells don't. We don't alter sigmode,
3485 * so we retry every time.
3486 * btw, in Linux it never fails. --vda */
3489 if (act.sa_handler == SIG_IGN) {
3490 cur_act = S_HARD_IGN;
3492 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3494 cur_act = S_IGN; /* don't hard ignore these */
3498 if (cur_act == S_HARD_IGN || cur_act == new_act)
3501 act.sa_handler = SIG_DFL;
3504 act.sa_handler = signal_handler;
3507 act.sa_handler = SIG_IGN;
3511 /* flags and mask matter only if !DFL and !IGN, but we do it
3512 * for all cases for more deterministic behavior:
3515 sigfillset(&act.sa_mask);
3517 sigaction_set(signo, &act);
3522 /* mode flags for set_curjob */
3523 #define CUR_DELETE 2
3524 #define CUR_RUNNING 1
3525 #define CUR_STOPPED 0
3528 /* pgrp of shell on invocation */
3529 static int initialpgrp; //references:2
3530 static int ttyfd = -1; //5
3533 static struct job *jobtab; //5
3535 static unsigned njobs; //4
3537 static struct job *curjob; //lots
3538 /* number of presumed living untracked jobs */
3539 static int jobless; //4
3542 set_curjob(struct job *jp, unsigned mode)
3545 struct job **jpp, **curp;
3547 /* first remove from list */
3548 jpp = curp = &curjob;
3553 jpp = &jp1->prev_job;
3555 *jpp = jp1->prev_job;
3557 /* Then re-insert in correct position */
3565 /* job being deleted */
3568 /* newly created job or backgrounded job,
3569 * put after all stopped jobs.
3574 if (!jp1 || jp1->state != JOBSTOPPED)
3577 jpp = &jp1->prev_job;
3583 /* newly stopped job - becomes curjob */
3584 jp->prev_job = *jpp;
3592 jobno(const struct job *jp)
3594 return jp - jobtab + 1;
3599 * Convert a job name to a job structure.
3602 #define getjob(name, getctl) getjob(name)
3605 getjob(const char *name, int getctl)
3609 const char *err_msg = "%s: no such job";
3613 char *(*match)(const char *, const char *);
3628 if (c == '+' || c == '%') {
3630 err_msg = "No current job";
3636 err_msg = "No previous job";
3646 if (num > 0 && num <= njobs) {
3647 jp = jobtab + num - 1;
3662 if (match(jp->ps[0].ps_cmd, p)) {
3666 err_msg = "%s: ambiguous";
3676 err_msg = "job %s not created under job control";
3677 if (getctl && jp->jobctl == 0)
3682 ash_msg_and_raise_error(err_msg, name);
3686 * Mark a job structure as unused.
3689 freejob(struct job *jp)
3691 struct procstat *ps;
3695 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3696 if (ps->ps_cmd != nullstr)
3699 if (jp->ps != &jp->ps0)
3702 set_curjob(jp, CUR_DELETE);
3708 xtcsetpgrp(int fd, pid_t pgrp)
3710 if (tcsetpgrp(fd, pgrp))
3711 ash_msg_and_raise_error("can't set tty process group (%m)");
3715 * Turn job control on and off.
3717 * Note: This code assumes that the third arg to ioctl is a character
3718 * pointer, which is true on Berkeley systems but not System V. Since
3719 * System V doesn't have job control yet, this isn't a problem now.
3721 * Called with interrupts off.
3729 if (on == doing_jobctl || rootshell == 0)
3733 ofd = fd = open(_PATH_TTY, O_RDWR);
3735 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3736 * That sometimes helps to acquire controlling tty.
3737 * Obviously, a workaround for bugs when someone
3738 * failed to provide a controlling tty to bash! :) */
3744 /* fd is a tty at this point */
3745 fd = fcntl(fd, F_DUPFD, 10);
3746 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3749 goto out; /* F_DUPFD failed */
3750 close_on_exec_on(fd);
3751 while (1) { /* while we are in the background */
3752 pgrp = tcgetpgrp(fd);
3755 ash_msg("can't access tty; job control turned off");
3759 if (pgrp == getpgrp())
3770 xtcsetpgrp(fd, pgrp);
3772 /* turning job control off */
3775 /* was xtcsetpgrp, but this can make exiting ash
3776 * loop forever if pty is already deleted */
3777 tcsetpgrp(fd, pgrp);
3791 static int FAST_FUNC
3792 killcmd(int argc, char **argv)
3794 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3797 if (argv[i][0] == '%') {
3799 * "kill %N" - job kill
3800 * Converting to pgrp / pid kill
3806 jp = getjob(argv[i], 0);
3808 * In jobs started under job control, we signal
3809 * entire process group by kill -PGRP_ID.
3810 * This happens, f.e., in interactive shell.
3812 * Otherwise, we signal each child via
3813 * kill PID1 PID2 PID3.
3815 * sh -c 'sleep 1|sleep 1 & kill %1'
3816 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3817 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3819 n = jp->nprocs; /* can't be 0 (I hope) */
3822 dst = alloca(n * sizeof(int)*4);
3824 for (j = 0; j < n; j++) {
3825 struct procstat *ps = &jp->ps[j];
3826 /* Skip non-running and not-stopped members
3827 * (i.e. dead members) of the job
3829 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3832 * kill_main has matching code to expect
3833 * leading space. Needed to not confuse
3834 * negative pids with "kill -SIGNAL_NO" syntax
3836 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3840 } while (argv[++i]);
3842 return kill_main(argc, argv);
3846 showpipe(struct job *jp /*, FILE *out*/)
3848 struct procstat *ps;
3849 struct procstat *psend;
3851 psend = jp->ps + jp->nprocs;
3852 for (ps = jp->ps + 1; ps < psend; ps++)
3853 printf(" | %s", ps->ps_cmd);
3854 newline_and_flush(stdout);
3855 flush_stdout_stderr();
3860 restartjob(struct job *jp, int mode)
3862 struct procstat *ps;
3868 if (jp->state == JOBDONE)
3870 jp->state = JOBRUNNING;
3871 pgid = jp->ps[0].ps_pid;
3872 if (mode == FORK_FG)
3873 xtcsetpgrp(ttyfd, pgid);
3874 killpg(pgid, SIGCONT);
3878 if (WIFSTOPPED(ps->ps_status)) {
3884 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3889 static int FAST_FUNC
3890 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3896 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3900 jp = getjob(*argv, 1);
3901 if (mode == FORK_BG) {
3902 set_curjob(jp, CUR_RUNNING);
3903 printf("[%d] ", jobno(jp));
3905 out1str(jp->ps[0].ps_cmd);
3906 showpipe(jp /*, stdout*/);
3907 retval = restartjob(jp, mode);
3908 } while (*argv && *++argv);
3914 sprint_status48(char *s, int status, int sigonly)
3920 if (!WIFEXITED(status)) {
3921 if (JOBS && WIFSTOPPED(status))
3922 st = WSTOPSIG(status);
3924 st = WTERMSIG(status);
3926 if (st == SIGINT || st == SIGPIPE)
3928 if (JOBS && WIFSTOPPED(status))
3932 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3933 col = fmtstr(s, 32, strsignal(st));
3934 if (WCOREDUMP(status)) {
3935 strcpy(s + col, " (core dumped)");
3936 col += sizeof(" (core dumped)")-1;
3938 } else if (!sigonly) {
3939 st = WEXITSTATUS(status);
3940 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3947 wait_block_or_sig(int *status)
3954 /* Poll all children for changes in their state */
3956 /* if job control is active, accept stopped processes too */
3957 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3959 break; /* Error (e.g. EINTR, ECHILD) or pid */
3961 /* Children exist, but none are ready. Sleep until interesting signal */
3964 sigprocmask(SIG_SETMASK, &mask, &mask);
3965 while (!got_sigchld && !pending_sig)
3967 sigprocmask(SIG_SETMASK, &mask, NULL);
3968 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3969 while (!got_sigchld && !pending_sig)
3973 /* If it was SIGCHLD, poll children again */
3974 } while (got_sigchld);
3979 #define DOWAIT_NONBLOCK 0
3980 #define DOWAIT_BLOCK 1
3981 #define DOWAIT_BLOCK_OR_SIG 2
3984 dowait(int block, struct job *job)
3989 struct job *thisjob = NULL;
3991 TRACE(("dowait(0x%x) called\n", block));
3993 /* It's wrong to call waitpid() outside of INT_OFF region:
3994 * signal can arrive just after syscall return and handler can
3995 * longjmp away, losing stop/exit notification processing.
3996 * Thus, for "jobs" builtin, and for waiting for a fg job,
3997 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
3999 * However, for "wait" builtin it is wrong to simply call waitpid()
4000 * in INT_OFF region: "wait" needs to wait for any running job
4001 * to change state, but should exit on any trap too.
4002 * In INT_OFF region, a signal just before syscall entry can set
4003 * pending_sig variables, but we can't check them, and we would
4004 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4006 * Because of this, we run inside INT_OFF, but use a special routine
4007 * which combines waitpid() and sigsuspend().
4008 * This is the reason why we need to have a handler for SIGCHLD:
4009 * SIG_DFL handler does not wake sigsuspend().
4012 if (block == DOWAIT_BLOCK_OR_SIG) {
4013 pid = wait_block_or_sig(&status);
4016 if (block == DOWAIT_NONBLOCK)
4017 wait_flags = WNOHANG;
4018 /* if job control is active, accept stopped processes too */
4020 wait_flags |= WUNTRACED;
4021 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4022 pid = waitpid(-1, &status, wait_flags);
4024 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4025 pid, status, errno, strerror(errno)));
4030 for (jp = curjob; jp; jp = jp->prev_job) {
4032 struct procstat *ps;
4033 struct procstat *psend;
4034 if (jp->state == JOBDONE)
4038 psend = ps + jp->nprocs;
4040 if (ps->ps_pid == pid) {
4041 TRACE(("Job %d: changing status of proc %d "
4042 "from 0x%x to 0x%x\n",
4043 jobno(jp), pid, ps->ps_status, status));
4044 ps->ps_status = status;
4047 if (ps->ps_status == -1)
4048 jobstate = JOBRUNNING;
4050 if (jobstate == JOBRUNNING)
4052 if (WIFSTOPPED(ps->ps_status)) {
4053 jp->stopstatus = ps->ps_status;
4054 jobstate = JOBSTOPPED;
4057 } while (++ps < psend);
4061 /* Found the job where one of its processes changed its state.
4062 * Is there at least one live and running process in this job? */
4063 if (jobstate != JOBRUNNING) {
4064 /* No. All live processes in the job are stopped
4065 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4067 thisjob->changed = 1;
4068 if (thisjob->state != jobstate) {
4069 TRACE(("Job %d: changing state from %d to %d\n",
4070 jobno(thisjob), thisjob->state, jobstate));
4071 thisjob->state = jobstate;
4073 if (jobstate == JOBSTOPPED)
4074 set_curjob(thisjob, CUR_STOPPED);
4080 /* The process wasn't found in job list */
4081 if (JOBS && !WIFSTOPPED(status))
4086 if (thisjob && thisjob == job) {
4090 len = sprint_status48(s, status, 1);
4102 showjob(struct job *jp, int mode)
4104 struct procstat *ps;
4105 struct procstat *psend;
4108 char s[16 + 16 + 48];
4109 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4113 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4114 /* just output process (group) id of pipeline */
4115 fprintf(out, "%d\n", ps->ps_pid);
4119 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4124 else if (curjob && jp == curjob->prev_job)
4127 if (mode & SHOW_PIDS)
4128 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4130 psend = ps + jp->nprocs;
4132 if (jp->state == JOBRUNNING) {
4133 strcpy(s + col, "Running");
4134 col += sizeof("Running") - 1;
4136 int status = psend[-1].ps_status;
4137 if (jp->state == JOBSTOPPED)
4138 status = jp->stopstatus;
4139 col += sprint_status48(s + col, status, 0);
4141 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4143 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4144 * or prints several "PID | <cmdN>" lines,
4145 * depending on SHOW_PIDS bit.
4146 * We do not print status of individual processes
4147 * between PID and <cmdN>. bash does it, but not very well:
4148 * first line shows overall job status, not process status,
4149 * making it impossible to know 1st process status.
4153 /* for each process */
4156 if (mode & SHOW_PIDS)
4157 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4159 fprintf(out, "%s%*c%s%s",
4161 33 - col >= 0 ? 33 - col : 0, ' ',
4162 ps == jp->ps ? "" : "| ",
4165 } while (++ps != psend);
4166 newline_and_flush(out);
4170 if (jp->state == JOBDONE) {
4171 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4177 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4178 * statuses have changed since the last call to showjobs.
4185 TRACE(("showjobs(0x%x) called\n", mode));
4187 /* Handle all finished jobs */
4188 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4191 for (jp = curjob; jp; jp = jp->prev_job) {
4192 if (!(mode & SHOW_CHANGED) || jp->changed) {
4198 static int FAST_FUNC
4199 jobscmd(int argc UNUSED_PARAM, char **argv)
4204 while ((m = nextopt("lp")) != '\0') {
4208 mode |= SHOW_ONLY_PGID;
4214 showjob(getjob(*argv, 0), mode);
4224 /* Called only on finished or stopped jobs (no members are running) */
4226 getstatus(struct job *job)
4230 struct procstat *ps;
4232 /* Fetch last member's status */
4233 ps = job->ps + job->nprocs - 1;
4234 status = ps->ps_status;
4236 /* "set -o pipefail" mode: use last _nonzero_ status */
4237 while (status == 0 && --ps >= job->ps)
4238 status = ps->ps_status;
4241 retval = WEXITSTATUS(status);
4242 if (!WIFEXITED(status)) {
4244 retval = WSTOPSIG(status);
4245 if (!WIFSTOPPED(status))
4248 /* XXX: limits number of signals */
4249 retval = WTERMSIG(status);
4251 if (retval == SIGINT)
4257 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4258 jobno(job), job->nprocs, status, retval));
4262 static int FAST_FUNC
4263 waitcmd(int argc UNUSED_PARAM, char **argv)
4274 /* wait for all jobs */
4278 if (!jp) /* no running procs */
4280 if (jp->state == JOBRUNNING)
4286 * "When bash is waiting for an asynchronous command via
4287 * the wait builtin, the reception of a signal for which a trap
4288 * has been set will cause the wait builtin to return immediately
4289 * with an exit status greater than 128, immediately after which
4290 * the trap is executed."
4292 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4293 /* if child sends us a signal *and immediately exits*,
4294 * dowait() returns pid > 0. Check this case,
4295 * not "if (dowait() < 0)"!
4304 if (**argv != '%') {
4305 pid_t pid = number(*argv);
4310 if (job->ps[job->nprocs - 1].ps_pid == pid)
4312 job = job->prev_job;
4315 job = getjob(*argv, 0);
4317 /* loop until process terminated or stopped */
4318 while (job->state == JOBRUNNING) {
4319 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4324 retval = getstatus(job);
4331 retval = 128 + pending_sig;
4340 struct job *jp, *jq;
4342 len = njobs * sizeof(*jp);
4344 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4346 offset = (char *)jp - (char *)jq;
4348 /* Relocate pointers */
4351 jq = (struct job *)((char *)jq + l);
4355 #define joff(p) ((struct job *)((char *)(p) + l))
4356 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4357 if (joff(jp)->ps == &jq->ps0)
4358 jmove(joff(jp)->ps);
4359 if (joff(jp)->prev_job)
4360 jmove(joff(jp)->prev_job);
4370 jp = (struct job *)((char *)jp + len);
4374 } while (--jq >= jp);
4379 * Return a new job structure.
4380 * Called with interrupts off.
4383 makejob(/*union node *node,*/ int nprocs)
4388 for (i = njobs, jp = jobtab; ; jp++) {
4395 if (jp->state != JOBDONE || !jp->waited)
4404 memset(jp, 0, sizeof(*jp));
4406 /* jp->jobctl is a bitfield.
4407 * "jp->jobctl |= jobctl" likely to give awful code */
4411 jp->prev_job = curjob;
4416 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4418 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4425 * Return a string identifying a command (to be printed by the
4428 static char *cmdnextc;
4431 cmdputs(const char *s)
4433 static const char vstype[VSTYPE + 1][3] = {
4434 "", "}", "-", "+", "?", "=",
4435 "%", "%%", "#", "##"
4436 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4439 const char *p, *str;
4443 unsigned char subtype = 0;
4447 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4449 while ((c = *p++) != '\0') {
4457 if ((subtype & VSTYPE) == VSLENGTH)
4463 str = "\"}" + !(quoted & 1);
4470 #if ENABLE_SH_MATH_SUPPORT
4485 if ((subtype & VSTYPE) != VSNORMAL)
4487 str = vstype[subtype & VSTYPE];
4488 if (subtype & VSNUL)
4497 /* These can only happen inside quotes */
4510 while ((c = *str++) != '\0') {
4513 } /* while *p++ not NUL */
4516 USTPUTC('"', nextc);
4522 /* cmdtxt() and cmdlist() call each other */
4523 static void cmdtxt(union node *n);
4526 cmdlist(union node *np, int sep)
4528 for (; np; np = np->narg.next) {
4532 if (sep && np->narg.next)
4538 cmdtxt(union node *n)
4541 struct nodelist *lp;
4552 lp = n->npipe.cmdlist;
4570 cmdtxt(n->nbinary.ch1);
4586 cmdtxt(n->nif.test);
4588 if (n->nif.elsepart) {
4589 cmdtxt(n->nif.ifpart);
4591 n = n->nif.elsepart;
4609 cmdtxt(n->nbinary.ch1);
4619 cmdputs(n->nfor.var);
4621 cmdlist(n->nfor.args, 1);
4626 cmdputs(n->narg.text);
4630 cmdlist(n->ncmd.args, 1);
4631 cmdlist(n->ncmd.redirect, 0);
4644 cmdputs(n->ncase.expr->narg.text);
4646 for (np = n->ncase.cases; np; np = np->nclist.next) {
4647 cmdtxt(np->nclist.pattern);
4649 cmdtxt(np->nclist.body);
4663 #if ENABLE_ASH_BASH_COMPAT
4678 cmdputs(utoa(n->nfile.fd));
4680 if (n->type == NTOFD || n->type == NFROMFD) {
4681 cmdputs(utoa(n->ndup.dupfd));
4690 commandtext(union node *n)
4694 STARTSTACKSTR(cmdnextc);
4696 name = stackblock();
4697 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4698 return ckstrdup(name);
4703 * Fork off a subshell. If we are doing job control, give the subshell its
4704 * own process group. Jp is a job structure that the job is to be added to.
4705 * N is the command that will be evaluated by the child. Both jp and n may
4706 * be NULL. The mode parameter can be one of the following:
4707 * FORK_FG - Fork off a foreground process.
4708 * FORK_BG - Fork off a background process.
4709 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4710 * process group even if job control is on.
4712 * When job control is turned off, background processes have their standard
4713 * input redirected to /dev/null (except for the second and later processes
4716 * Called with interrupts off.
4719 * Clear traps on a fork.
4727 for (tp = trap; tp < &trap[NSIG]; tp++) {
4728 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4729 if (trap_ptr == trap)
4731 /* else: it "belongs" to trap_ptr vector, don't free */
4733 if ((tp - trap) != 0)
4734 setsignal(tp - trap);
4741 /* Lives far away from here, needed for forkchild */
4742 static void closescript(void);
4744 /* Called after fork(), in child */
4745 /* jp and n are NULL when called by openhere() for heredoc support */
4746 static NOINLINE void
4747 forkchild(struct job *jp, union node *n, int mode)
4751 TRACE(("Child shell %d\n", getpid()));
4755 /* man bash: "Non-builtin commands run by bash have signal handlers
4756 * set to the values inherited by the shell from its parent".
4757 * Do we do it correctly? */
4761 if (mode == FORK_NOJOB /* is it `xxx` ? */
4762 && n && n->type == NCMD /* is it single cmd? */
4763 /* && n->ncmd.args->type == NARG - always true? */
4764 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4765 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4766 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4768 TRACE(("Trap hack\n"));
4769 /* Awful hack for `trap` or $(trap).
4771 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4772 * contains an example where "trap" is executed in a subshell:
4774 * save_traps=$(trap)
4776 * eval "$save_traps"
4778 * Standard does not say that "trap" in subshell shall print
4779 * parent shell's traps. It only says that its output
4780 * must have suitable form, but then, in the above example
4781 * (which is not supposed to be normative), it implies that.
4783 * bash (and probably other shell) does implement it
4784 * (traps are reset to defaults, but "trap" still shows them),
4785 * but as a result, "trap" logic is hopelessly messed up:
4788 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4789 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4790 * # true | trap <--- trap is in subshell - no output (ditto)
4791 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4792 * trap -- 'echo Ho' SIGWINCH
4793 * # echo `(trap)` <--- in subshell in subshell - output
4794 * trap -- 'echo Ho' SIGWINCH
4795 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4796 * trap -- 'echo Ho' SIGWINCH
4798 * The rules when to forget and when to not forget traps
4799 * get really complex and nonsensical.
4801 * Our solution: ONLY bare $(trap) or `trap` is special.
4803 /* Save trap handler strings for trap builtin to print */
4804 trap_ptr = xmemdup(trap, sizeof(trap));
4805 /* Fall through into clearing traps */
4809 /* do job control only in root shell */
4811 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4814 if (jp->nprocs == 0)
4817 pgrp = jp->ps[0].ps_pid;
4818 /* this can fail because we are doing it in the parent also */
4820 if (mode == FORK_FG)
4821 xtcsetpgrp(ttyfd, pgrp);
4826 if (mode == FORK_BG) {
4827 /* man bash: "When job control is not in effect,
4828 * asynchronous commands ignore SIGINT and SIGQUIT" */
4831 if (jp->nprocs == 0) {
4833 if (open(bb_dev_null, O_RDONLY) != 0)
4834 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4838 if (iflag) { /* why if iflag only? */
4843 * "In all cases, bash ignores SIGQUIT. Non-builtin
4844 * commands run by bash have signal handlers
4845 * set to the values inherited by the shell
4847 * Take care of the second rule: */
4851 if (n && n->type == NCMD
4852 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4854 TRACE(("Job hack\n"));
4855 /* "jobs": we do not want to clear job list for it,
4856 * instead we remove only _its_ own_ job from job list.
4857 * This makes "jobs .... | cat" more useful.
4863 for (jp = curjob; jp; jp = jp->prev_job)
4868 /* Called after fork(), in parent */
4870 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4873 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4875 TRACE(("In parent shell: child = %d\n", pid));
4877 /* jp is NULL when called by openhere() for heredoc support */
4878 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4884 if (mode != FORK_NOJOB && jp->jobctl) {
4887 if (jp->nprocs == 0)
4890 pgrp = jp->ps[0].ps_pid;
4891 /* This can fail because we are doing it in the child also */
4895 if (mode == FORK_BG) {
4896 backgndpid = pid; /* set $! */
4897 set_curjob(jp, CUR_RUNNING);
4900 struct procstat *ps = &jp->ps[jp->nprocs++];
4903 ps->ps_cmd = nullstr;
4905 if (doing_jobctl && n)
4906 ps->ps_cmd = commandtext(n);
4911 /* jp and n are NULL when called by openhere() for heredoc support */
4913 forkshell(struct job *jp, union node *n, int mode)
4917 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4920 TRACE(("Fork failed, errno=%d", errno));
4923 ash_msg_and_raise_error("can't fork");
4926 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4927 forkchild(jp, n, mode);
4929 forkparent(jp, n, mode, pid);
4935 * Wait for job to finish.
4937 * Under job control we have the problem that while a child process
4938 * is running interrupts generated by the user are sent to the child
4939 * but not to the shell. This means that an infinite loop started by
4940 * an interactive user may be hard to kill. With job control turned off,
4941 * an interactive user may place an interactive program inside a loop.
4942 * If the interactive program catches interrupts, the user doesn't want
4943 * these interrupts to also abort the loop. The approach we take here
4944 * is to have the shell ignore interrupt signals while waiting for a
4945 * foreground process to terminate, and then send itself an interrupt
4946 * signal if the child process was terminated by an interrupt signal.
4947 * Unfortunately, some programs want to do a bit of cleanup and then
4948 * exit on interrupt; unless these processes terminate themselves by
4949 * sending a signal to themselves (instead of calling exit) they will
4950 * confuse this approach.
4952 * Called with interrupts off.
4955 waitforjob(struct job *jp)
4959 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4962 while (jp->state == JOBRUNNING) {
4963 /* In non-interactive shells, we _can_ get
4964 * a keyboard signal here and be EINTRed,
4965 * but we just loop back, waiting for command to complete.
4968 * "If bash is waiting for a command to complete and receives
4969 * a signal for which a trap has been set, the trap
4970 * will not be executed until the command completes."
4972 * Reality is that even if trap is not set, bash
4973 * will not act on the signal until command completes.
4974 * Try this. sleep5intoff.c:
4975 * #include <signal.h>
4976 * #include <unistd.h>
4979 * sigemptyset(&set);
4980 * sigaddset(&set, SIGINT);
4981 * sigaddset(&set, SIGQUIT);
4982 * sigprocmask(SIG_BLOCK, &set, NULL);
4986 * $ bash -c './sleep5intoff; echo hi'
4987 * ^C^C^C^C <--- pressing ^C once a second
4989 * $ bash -c './sleep5intoff; echo hi'
4990 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4993 dowait(DOWAIT_BLOCK, jp);
5000 xtcsetpgrp(ttyfd, rootpid);
5002 * This is truly gross.
5003 * If we're doing job control, then we did a TIOCSPGRP which
5004 * caused us (the shell) to no longer be in the controlling
5005 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5006 * intuit from the subprocess exit status whether a SIGINT
5007 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5009 if (jp->sigint) /* TODO: do the same with all signals */
5010 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5012 if (jp->state == JOBDONE)
5019 * return 1 if there are stopped jobs, otherwise 0
5031 if (jp && jp->state == JOBSTOPPED) {
5032 out2str("You have stopped jobs.\n");
5042 * Code for dealing with input/output redirection.
5047 #define EMPTY -2 /* marks an unused slot in redirtab */
5048 #define CLOSED -3 /* marks a slot of previously-closed fd */
5051 * Open a file in noclobber mode.
5052 * The code was copied from bash.
5055 noclobberopen(const char *fname)
5058 struct stat finfo, finfo2;
5061 * If the file exists and is a regular file, return an error
5064 r = stat(fname, &finfo);
5065 if (r == 0 && S_ISREG(finfo.st_mode)) {
5071 * If the file was not present (r != 0), make sure we open it
5072 * exclusively so that if it is created before we open it, our open
5073 * will fail. Make sure that we do not truncate an existing file.
5074 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5075 * file was not a regular file, we leave O_EXCL off.
5078 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5079 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5081 /* If the open failed, return the file descriptor right away. */
5086 * OK, the open succeeded, but the file may have been changed from a
5087 * non-regular file to a regular file between the stat and the open.
5088 * We are assuming that the O_EXCL open handles the case where FILENAME
5089 * did not exist and is symlinked to an existing file between the stat
5094 * If we can open it and fstat the file descriptor, and neither check
5095 * revealed that it was a regular file, and the file has not been
5096 * replaced, return the file descriptor.
5098 if (fstat(fd, &finfo2) == 0
5099 && !S_ISREG(finfo2.st_mode)
5100 && finfo.st_dev == finfo2.st_dev
5101 && finfo.st_ino == finfo2.st_ino
5106 /* The file has been replaced. badness. */
5113 * Handle here documents. Normally we fork off a process to write the
5114 * data to a pipe. If the document is short, we can stuff the data in
5115 * the pipe without forking.
5117 /* openhere needs this forward reference */
5118 static void expandhere(union node *arg, int fd);
5120 openhere(union node *redir)
5126 ash_msg_and_raise_error("pipe call failed");
5127 if (redir->type == NHERE) {
5128 len = strlen(redir->nhere.doc->narg.text);
5129 if (len <= PIPE_BUF) {
5130 full_write(pip[1], redir->nhere.doc->narg.text, len);
5134 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5137 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5138 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5139 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5140 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5141 signal(SIGPIPE, SIG_DFL);
5142 if (redir->type == NHERE)
5143 full_write(pip[1], redir->nhere.doc->narg.text, len);
5145 expandhere(redir->nhere.doc, pip[1]);
5146 _exit(EXIT_SUCCESS);
5154 openredirect(union node *redir)
5159 switch (redir->nfile.type) {
5160 /* Can't happen, our single caller does this itself */
5166 return openhere(redir);
5169 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5170 * allocated space. Do it only when we know it is safe.
5172 fname = redir->nfile.expfname;
5174 switch (redir->nfile.type) {
5180 f = open(fname, O_RDONLY);
5185 f = open(fname, O_RDWR|O_CREAT, 0666);
5190 #if ENABLE_ASH_BASH_COMPAT
5193 /* Take care of noclobber mode. */
5195 f = noclobberopen(fname);
5202 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5207 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5215 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5217 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5221 * Copy a file descriptor to be >= 10. Throws exception on error.
5229 newfd = fcntl(from, F_DUPFD, 10);
5230 err = newfd < 0 ? errno : 0;
5233 ash_msg_and_raise_error("%d: %m", from);
5235 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5241 dup2_or_raise(int from, int to)
5245 newfd = (from != to) ? dup2(from, to) : to;
5247 /* Happens when source fd is not open: try "echo >&99" */
5248 ash_msg_and_raise_error("%d: %m", from);
5253 /* Struct def and variable are moved down to the first usage site */
5258 struct redirtab *next;
5260 struct two_fd_t two_fd[];
5262 #define redirlist (G_var.redirlist)
5264 COPYFD_RESTORE = (int)~(INT_MAX),
5268 need_to_remember(struct redirtab *rp, int fd)
5272 if (!rp) /* remembering was not requested */
5275 for (i = 0; i < rp->pair_count; i++) {
5276 if (rp->two_fd[i].orig == fd) {
5277 /* already remembered */
5284 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5286 is_hidden_fd(struct redirtab *rp, int fd)
5289 struct parsefile *pf;
5293 /* Check open scripts' fds */
5296 /* We skip pf_fd == 0 case because of the following case:
5297 * $ ash # running ash interactively
5299 * and in script.sh: "exec 9>&0".
5300 * Even though top-level pf_fd _is_ 0,
5301 * it's still ok to use it: "read" builtin uses it,
5302 * why should we cripple "exec" builtin?
5304 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5312 /* Check saved fds of redirects */
5313 fd |= COPYFD_RESTORE;
5314 for (i = 0; i < rp->pair_count; i++) {
5315 if (rp->two_fd[i].copy == fd) {
5323 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5324 * old file descriptors are stashed away so that the redirection can be
5325 * undone by calling popredir.
5327 /* flags passed to redirect */
5328 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5329 #define REDIR_SAVEFD2 03 /* set preverrout */
5331 redirect(union node *redir, int flags)
5333 struct redirtab *sv;
5338 int copied_fd2 = -1;
5347 if (flags & REDIR_PUSH) {
5348 union node *tmp = redir;
5351 #if ENABLE_ASH_BASH_COMPAT
5352 if (tmp->nfile.type == NTO2)
5355 tmp = tmp->nfile.next;
5357 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5358 sv->next = redirlist;
5359 sv->pair_count = sv_pos;
5361 while (sv_pos > 0) {
5363 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5369 fd = redir->nfile.fd;
5370 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5371 right_fd = redir->ndup.dupfd;
5372 //bb_error_msg("doing %d > %d", fd, right_fd);
5373 /* redirect from/to same file descriptor? */
5376 /* "echo >&10" and 10 is a fd opened to a sh script? */
5377 if (is_hidden_fd(sv, right_fd)) {
5378 errno = EBADF; /* as if it is closed */
5379 ash_msg_and_raise_error("%d: %m", right_fd);
5383 newfd = openredirect(redir); /* always >= 0 */
5385 /* Descriptor wasn't open before redirect.
5386 * Mark it for close in the future */
5387 if (need_to_remember(sv, fd)) {
5388 goto remember_to_close;
5393 #if ENABLE_ASH_BASH_COMPAT
5396 if (need_to_remember(sv, fd)) {
5397 /* Copy old descriptor */
5398 /* Careful to not accidentally "save"
5399 * to the same fd as right side fd in N>&M */
5400 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5401 i = fcntl(fd, F_DUPFD, minfd);
5402 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5403 * are closed in popredir() in the child, preventing them from leaking
5404 * into child. (popredir() also cleans up the mess in case of failures)
5409 /* Strange error (e.g. "too many files" EMFILE?) */
5413 ash_msg_and_raise_error("%d: %m", fd);
5416 /* EBADF: it is not open - good, remember to close it */
5419 } else { /* fd is open, save its copy */
5420 /* "exec fd>&-" should not close fds
5421 * which point to script file(s).
5422 * Force them to be restored afterwards */
5423 if (is_hidden_fd(sv, fd))
5424 i |= COPYFD_RESTORE;
5428 sv->two_fd[sv_pos].orig = fd;
5429 sv->two_fd[sv_pos].copy = i;
5433 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5434 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5435 /* Don't want to trigger debugging */
5439 dup2_or_raise(redir->ndup.dupfd, fd);
5441 } else if (fd != newfd) { /* move newfd to fd */
5442 dup2_or_raise(newfd, fd);
5443 #if ENABLE_ASH_BASH_COMPAT
5444 if (!(redir->nfile.type == NTO2 && fd == 2))
5448 #if ENABLE_ASH_BASH_COMPAT
5449 if (redir->nfile.type == NTO2 && fd == 1) {
5450 /* We already redirected it to fd 1, now copy it to 2 */
5456 } while ((redir = redir->nfile.next) != NULL);
5459 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5460 preverrout_fd = copied_fd2;
5464 * Undo the effects of the last redirection.
5467 popredir(int drop, int restore)
5469 struct redirtab *rp;
5472 if (redirlist == NULL)
5476 for (i = 0; i < rp->pair_count; i++) {
5477 int fd = rp->two_fd[i].orig;
5478 int copy = rp->two_fd[i].copy;
5479 if (copy == CLOSED) {
5484 if (copy != EMPTY) {
5485 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5486 copy &= ~COPYFD_RESTORE;
5488 dup2_or_raise(copy, fd);
5490 close(copy & ~COPYFD_RESTORE);
5493 redirlist = rp->next;
5499 * Undo all redirections. Called on error or interrupt.
5503 redirectsafe(union node *redir, int flags)
5506 volatile int saveint;
5507 struct jmploc *volatile savehandler = exception_handler;
5508 struct jmploc jmploc;
5511 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5512 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5514 exception_handler = &jmploc;
5515 redirect(redir, flags);
5517 exception_handler = savehandler;
5518 if (err && exception_type != EXERROR)
5519 longjmp(exception_handler->loc, 1);
5520 RESTORE_INT(saveint);
5525 /* ============ Routines to expand arguments to commands
5527 * We have to deal with backquotes, shell variables, and file metacharacters.
5530 #if ENABLE_SH_MATH_SUPPORT
5532 ash_arith(const char *s)
5534 arith_state_t math_state;
5537 math_state.lookupvar = lookupvar;
5538 math_state.setvar = setvar0;
5539 //math_state.endofname = endofname;
5542 result = arith(&math_state, s);
5543 if (math_state.errmsg)
5544 ash_msg_and_raise_error(math_state.errmsg);
5554 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5555 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5556 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5557 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5558 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5559 * POSIX says for this case:
5560 * Pathname expansion shall not be performed on the word by a
5561 * non-interactive shell; an interactive shell may perform it, but shall
5562 * do so only when the expansion would result in one word.
5563 * Currently, our code complies to the above rule by never globbing
5564 * redirection filenames.
5565 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5566 * (this means that on a typical Linux distro, bash almost always
5567 * performs globbing, and thus diverges from what we do).
5569 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5570 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5571 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5572 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5573 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5577 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5578 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5579 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5580 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5581 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5583 /* Add CTLESC when necessary. */
5584 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5585 /* Do not skip NUL characters. */
5586 #define QUOTES_KEEPNUL EXP_TILDE
5589 * Structure specifying which parts of the string should be searched
5590 * for IFS characters.
5593 struct ifsregion *next; /* next region in list */
5594 int begoff; /* offset of start of region */
5595 int endoff; /* offset of end of region */
5596 int nulonly; /* search for nul bytes only */
5600 struct strlist *list;
5601 struct strlist **lastp;
5604 /* output of current string */
5605 static char *expdest;
5606 /* list of back quote expressions */
5607 static struct nodelist *argbackq;
5608 /* first struct in list of ifs regions */
5609 static struct ifsregion ifsfirst;
5610 /* last struct in list */
5611 static struct ifsregion *ifslastp;
5612 /* holds expanded arg list */
5613 static struct arglist exparg;
5618 #if !ENABLE_SH_MATH_SUPPORT
5619 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5620 typedef long arith_t;
5621 # define ARITH_FMT "%ld"
5628 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5629 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5630 STADJUST(len, expdest);
5635 * Break the argument string into pieces based upon IFS and add the
5636 * strings to the argument list. The regions of the string to be
5637 * searched for IFS characters have been stored by recordregion.
5640 ifsbreakup(char *string, struct arglist *arglist)
5642 struct ifsregion *ifsp;
5647 const char *ifs, *realifs;
5652 if (ifslastp != NULL) {
5655 realifs = ifsset() ? ifsval() : defifs;
5658 p = string + ifsp->begoff;
5659 nulonly = ifsp->nulonly;
5660 ifs = nulonly ? nullstr : realifs;
5662 while (p < string + ifsp->endoff) {
5664 if ((unsigned char)*p == CTLESC)
5666 if (!strchr(ifs, *p)) {
5671 ifsspc = (strchr(defifs, *p) != NULL);
5672 /* Ignore IFS whitespace at start */
5673 if (q == start && ifsspc) {
5679 sp = stzalloc(sizeof(*sp));
5681 *arglist->lastp = sp;
5682 arglist->lastp = &sp->next;
5686 if (p >= string + ifsp->endoff) {
5690 if ((unsigned char)*p == CTLESC)
5692 if (strchr(ifs, *p) == NULL) {
5696 if (strchr(defifs, *p) == NULL) {
5711 } while (ifsp != NULL);
5720 sp = stzalloc(sizeof(*sp));
5722 *arglist->lastp = sp;
5723 arglist->lastp = &sp->next;
5729 struct ifsregion *p = ifsfirst.next;
5736 struct ifsregion *ifsp;
5741 ifsfirst.next = NULL;
5748 esclen(const char *start, const char *p)
5752 while (p > start && (unsigned char)*--p == CTLESC) {
5759 * Remove any CTLESC characters from a string.
5762 rmescapes(char *str, int flag)
5764 static const char qchars[] ALIGN1 = {
5765 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5769 unsigned protect_against_glob;
5771 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5773 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5779 if (flag & RMESCAPE_ALLOC) {
5780 size_t len = p - str;
5781 size_t fulllen = len + strlen(p) + 1;
5783 if (flag & RMESCAPE_GROW) {
5784 int strloc = str - (char *)stackblock();
5785 r = makestrspace(fulllen, expdest);
5786 /* p and str may be invalidated by makestrspace */
5787 str = (char *)stackblock() + strloc;
5789 } else if (flag & RMESCAPE_HEAP) {
5790 r = ckmalloc(fulllen);
5792 r = stalloc(fulllen);
5796 q = (char *)memcpy(q, str, len) + len;
5801 globbing = flag & RMESCAPE_GLOB;
5802 protect_against_glob = globbing;
5804 if ((unsigned char)*p == CTLQUOTEMARK) {
5805 // Note: both inquotes and protect_against_glob only affect whether
5806 inquotes = ~inquotes;
5808 protect_against_glob = globbing;
5811 if ((unsigned char)*p == CTLESC) {
5815 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5817 if (protect_against_glob) {
5820 } else if (*p == '\\' && !inquotes) {
5821 /* naked back slash */
5822 protect_against_glob = 0;
5825 #if ENABLE_ASH_BASH_COMPAT
5826 else if (*p == '/' && slash) {
5827 /* stop handling globbing and mark location of slash */
5828 globbing = slash = 0;
5832 protect_against_glob = globbing;
5837 if (flag & RMESCAPE_GROW) {
5839 STADJUST(q - r + 1, expdest);
5843 #define pmatch(a, b) !fnmatch((a), (b), 0)
5846 * Prepare a pattern for a expmeta (internal glob(3)) call.
5848 * Returns an stalloced string.
5851 preglob(const char *pattern, int flag)
5853 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5857 * Put a string on the stack.
5860 memtodest(const char *p, size_t len, int syntax, int quotes)
5867 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5870 unsigned char c = *p++;
5872 int n = SIT(c, syntax);
5873 if ((quotes & QUOTES_ESC)
5875 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5881 } else if (!(quotes & QUOTES_KEEPNUL))
5890 strtodest(const char *p, int syntax, int quotes)
5892 size_t len = strlen(p);
5893 memtodest(p, len, syntax, quotes);
5898 * Record the fact that we have to scan this region of the
5899 * string for IFS characters.
5902 recordregion(int start, int end, int nulonly)
5904 struct ifsregion *ifsp;
5906 if (ifslastp == NULL) {
5910 ifsp = ckzalloc(sizeof(*ifsp));
5911 /*ifsp->next = NULL; - ckzalloc did it */
5912 ifslastp->next = ifsp;
5916 ifslastp->begoff = start;
5917 ifslastp->endoff = end;
5918 ifslastp->nulonly = nulonly;
5922 removerecordregions(int endoff)
5924 if (ifslastp == NULL)
5927 if (ifsfirst.endoff > endoff) {
5928 while (ifsfirst.next) {
5929 struct ifsregion *ifsp;
5931 ifsp = ifsfirst.next->next;
5932 free(ifsfirst.next);
5933 ifsfirst.next = ifsp;
5936 if (ifsfirst.begoff > endoff) {
5939 ifslastp = &ifsfirst;
5940 ifsfirst.endoff = endoff;
5945 ifslastp = &ifsfirst;
5946 while (ifslastp->next && ifslastp->next->begoff < endoff)
5947 ifslastp = ifslastp->next;
5948 while (ifslastp->next) {
5949 struct ifsregion *ifsp;
5951 ifsp = ifslastp->next->next;
5952 free(ifslastp->next);
5953 ifslastp->next = ifsp;
5956 if (ifslastp->endoff > endoff)
5957 ifslastp->endoff = endoff;
5961 exptilde(char *startp, char *p, int flags)
5967 int quotes = flags & QUOTES_ESC;
5971 while ((c = *++p) != '\0') {
5978 if (flags & EXP_VARTILDE)
5988 if (*name == '\0') {
5989 home = lookupvar("HOME");
5991 pw = getpwnam(name);
5996 if (!home || !*home)
5999 strtodest(home, SQSYNTAX, quotes);
6007 * Execute a command inside back quotes. If it's a builtin command, we
6008 * want to save its output in a block obtained from malloc. Otherwise
6009 * we fork off a subprocess and get the output of the command via a pipe.
6010 * Should be called with interrupts off.
6012 struct backcmd { /* result of evalbackcmd */
6013 int fd; /* file descriptor to read from */
6014 int nleft; /* number of chars in buffer */
6015 char *buf; /* buffer */
6016 struct job *jp; /* job structure for command */
6019 /* These forward decls are needed to use "eval" code for backticks handling: */
6020 #define EV_EXIT 01 /* exit after evaluating tree */
6021 static int evaltree(union node *, int);
6023 static void FAST_FUNC
6024 evalbackcmd(union node *n, struct backcmd *result)
6038 ash_msg_and_raise_error("pipe call failed");
6039 jp = makejob(/*n,*/ 1);
6040 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6046 dup2_or_raise(pip[1], 1);
6049 /* TODO: eflag clearing makes the following not abort:
6050 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6051 * which is what bash does (unless it is in POSIX mode).
6052 * dash deleted "eflag = 0" line in the commit
6053 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6054 * [EVAL] Don't clear eflag in evalbackcmd
6055 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6059 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6064 result->fd = pip[0];
6068 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6069 result->fd, result->buf, result->nleft, result->jp));
6073 * Expand stuff in backwards quotes.
6076 expbackq(union node *cmd, int flag)
6084 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6085 struct stackmark smark;
6088 startloc = expdest - (char *)stackblock();
6089 pushstackmark(&smark, startloc);
6090 evalbackcmd(cmd, &in);
6091 popstackmark(&smark);
6098 memtodest(p, i, syntax, flag & QUOTES_ESC);
6102 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6103 TRACE(("expbackq: read returns %d\n", i));
6112 back_exitstatus = waitforjob(in.jp);
6116 /* Eat all trailing newlines */
6118 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6122 if (!(flag & EXP_QUOTED))
6123 recordregion(startloc, dest - (char *)stackblock(), 0);
6124 TRACE(("evalbackq: size:%d:'%.*s'\n",
6125 (int)((dest - (char *)stackblock()) - startloc),
6126 (int)((dest - (char *)stackblock()) - startloc),
6127 stackblock() + startloc));
6130 #if ENABLE_SH_MATH_SUPPORT
6132 * Expand arithmetic expression. Backup to start of expression,
6133 * evaluate, place result in (backed up) result, adjust string position.
6145 * This routine is slightly over-complicated for
6146 * efficiency. Next we scan backwards looking for the
6147 * start of arithmetic.
6149 start = stackblock();
6156 while ((unsigned char)*p != CTLARI) {
6160 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6165 esc = esclen(start, p);
6175 removerecordregions(begoff);
6179 if (flag & QUOTES_ESC)
6180 rmescapes(p + 1, 0);
6182 len = cvtnum(ash_arith(p + 1));
6184 if (!(flag & EXP_QUOTED))
6185 recordregion(begoff, begoff + len, 0);
6189 /* argstr needs it */
6190 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6193 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6194 * characters to allow for further processing. Otherwise treat
6195 * $@ like $* since no splitting will be performed.
6197 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6198 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6199 * for correct expansion of "B=$A" word.
6202 argstr(char *p, int flags, struct strlist *var_str_list)
6204 static const char spclchars[] ALIGN1 = {
6212 #if ENABLE_SH_MATH_SUPPORT
6217 const char *reject = spclchars;
6218 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6223 if (!(flags & EXP_VARTILDE)) {
6225 } else if (flags & EXP_VARTILDE2) {
6230 if (flags & EXP_TILDE) {
6233 flags &= ~EXP_TILDE;
6237 p = exptilde(p, q, flags);
6240 startloc = expdest - (char *)stackblock();
6244 length += strcspn(p + length, reject);
6248 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6250 /* c == '=' || c == ':' || c == CTLENDARI */
6256 expdest = stack_nputstr(p, length, expdest);
6257 newloc = expdest - (char *)stackblock();
6258 if (breakall && !inquotes && newloc > startloc) {
6259 recordregion(startloc, newloc, 0);
6270 if (flags & EXP_VARTILDE2) {
6274 flags |= EXP_VARTILDE2;
6279 * sort of a hack - expand tildes in variable
6280 * assignments (after the first '=' and after ':'s).
6289 case CTLENDVAR: /* ??? */
6292 inquotes ^= EXP_QUOTED;
6293 /* "$@" syntax adherence hack */
6294 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6295 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6299 if (flags & QUOTES_ESC) {
6310 * Quoted parameter expansion pattern: remove quote
6311 * unless inside inner quotes or we have a literal
6314 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6315 EXP_QPAT && *p != '\\')
6320 TRACE(("argstr: evalvar('%s')\n", p));
6321 p = evalvar(p, flags | inquotes, var_str_list);
6322 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6325 expbackq(argbackq->n, flags | inquotes);
6326 argbackq = argbackq->next;
6328 #if ENABLE_SH_MATH_SUPPORT
6331 expari(flags | inquotes);
6340 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6341 char *pattern, int quotes, int zero)
6350 const char *s = loc2;
6357 match = pmatch(pattern, s);
6362 if (quotes && (unsigned char)*loc == CTLESC)
6371 scanright(char *startp, char *rmesc, char *rmescend,
6372 char *pattern, int quotes, int match_at_start)
6374 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6375 int try2optimize = match_at_start;
6381 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6382 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6383 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6385 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6386 * and on each iteration they go back two/one char until they reach the beginning.
6387 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6389 /* TODO: document in what other circumstances we are called. */
6391 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6394 const char *s = loc2;
6395 if (match_at_start) {
6399 match = pmatch(pattern, s);
6400 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6404 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6406 /* Maybe we can optimize this:
6407 * if pattern ends with unescaped *, we can avoid checking
6408 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6409 * it wont match truncated "raw_value_of_" strings too.
6411 unsigned plen = strlen(pattern);
6412 /* Does it end with "*"? */
6413 if (plen != 0 && pattern[--plen] == '*') {
6414 /* "xxxx*" is not escaped */
6415 /* "xxx\*" is escaped */
6416 /* "xx\\*" is not escaped */
6417 /* "x\\\*" is escaped */
6419 while (plen != 0 && pattern[--plen] == '\\')
6422 break; /* ends with unescaped "*" */
6430 esc = esclen(startp, loc);
6441 static void varunset(const char *, const char *, const char *, int) NORETURN;
6443 varunset(const char *end, const char *var, const char *umsg, int varflags)
6449 msg = "parameter not set";
6451 if ((unsigned char)*end == CTLENDVAR) {
6452 if (varflags & VSNUL)
6458 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6462 subevalvar(char *p, char *varname, int strloc, int subtype,
6463 int startloc, int varflags, int flag, struct strlist *var_str_list)
6465 struct nodelist *saveargbackq = argbackq;
6466 int quotes = flag & QUOTES_ESC;
6469 char *rmesc, *rmescend;
6471 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6472 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6473 int amount, resetloc;
6474 IF_ASH_BASH_COMPAT(int workloc;)
6476 char *(*scan)(char*, char*, char*, char*, int, int);
6478 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6479 // p, varname, strloc, subtype, startloc, varflags, quotes);
6481 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6482 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6484 STPUTC('\0', expdest);
6485 argbackq = saveargbackq;
6486 startp = (char *)stackblock() + startloc;
6490 setvar0(varname, startp);
6491 amount = startp - expdest;
6492 STADJUST(amount, expdest);
6496 varunset(p, varname, startp, varflags);
6499 #if ENABLE_ASH_BASH_COMPAT
6501 //TODO: support more general format ${v:EXPR:EXPR},
6502 // where EXPR follows $(()) rules
6503 loc = str = stackblock() + strloc;
6504 /* Read POS in ${var:POS:LEN} */
6505 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6506 len = str - startp - 1;
6508 /* *loc != '\0', guaranteed by parser */
6512 /* Adjust the length by the number of escapes */
6513 for (ptr = startp; ptr < (str - 1); ptr++) {
6514 if ((unsigned char)*ptr == CTLESC) {
6522 if (*loc++ == ':') {
6526 /* Skip POS in ${var:POS:LEN} */
6528 while (*loc && *loc != ':') {
6530 * bash complains on: var=qwe; echo ${var:1a:123}
6532 ash_msg_and_raise_error(msg_illnum, str);
6536 if (*loc++ == ':') {
6541 /* ${VAR:$((-n)):l} starts n chars from the end */
6542 pos = orig_len + pos;
6544 if ((unsigned)pos >= orig_len) {
6545 /* apart from obvious ${VAR:999999:l},
6546 * covers ${VAR:$((-9999999)):l} - result is ""
6552 if (len > (orig_len - pos))
6553 len = orig_len - pos;
6555 for (str = startp; pos; str++, pos--) {
6556 if (quotes && (unsigned char)*str == CTLESC)
6559 for (loc = startp; len; len--) {
6560 if (quotes && (unsigned char)*str == CTLESC)
6565 amount = loc - expdest;
6566 STADJUST(amount, expdest);
6571 resetloc = expdest - (char *)stackblock();
6573 /* We'll comeback here if we grow the stack while handling
6574 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6575 * stack will need rebasing, and we'll need to remove our work
6578 IF_ASH_BASH_COMPAT(restart:)
6580 amount = expdest - ((char *)stackblock() + resetloc);
6581 STADJUST(-amount, expdest);
6582 startp = (char *)stackblock() + startloc;
6585 rmescend = (char *)stackblock() + strloc;
6587 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6588 if (rmesc != startp) {
6590 startp = (char *)stackblock() + startloc;
6594 str = (char *)stackblock() + strloc;
6596 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6597 * The result is a_\_z_c (not a\_\_z_c)!
6599 * The search pattern and replace string treat backslashes differently!
6600 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6601 * and string. It's only used on the first call.
6603 preglob(str, IF_ASH_BASH_COMPAT(
6604 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6605 RMESCAPE_SLASH :) 0);
6607 #if ENABLE_ASH_BASH_COMPAT
6608 workloc = expdest - (char *)stackblock();
6609 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6613 repl = strchr(str, CTLESC);
6619 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6621 /* If there's no pattern to match, return the expansion unmolested */
6630 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6631 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6633 /* No match, advance */
6634 char *restart_detect = stackblock();
6636 STPUTC(*idx, expdest);
6637 if (quotes && (unsigned char)*idx == CTLESC) {
6640 STPUTC(*idx, expdest);
6642 if (stackblock() != restart_detect)
6647 /* continue; - prone to quadratic behavior, smarter code: */
6650 if (str[0] == '*') {
6651 /* Pattern is "*foo". If "*foo" does not match "long_string",
6652 * it would never match "ong_string" etc, no point in trying.
6659 if (subtype == VSREPLACEALL) {
6661 if (quotes && (unsigned char)*idx == CTLESC)
6670 //bb_error_msg("repl:'%s'", repl);
6671 for (loc = (char*)repl; *loc; loc++) {
6672 char *restart_detect = stackblock();
6673 if (quotes && *loc == '\\') {
6674 STPUTC(CTLESC, expdest);
6677 STPUTC(*loc, expdest);
6678 if (stackblock() != restart_detect)
6683 if (subtype == VSREPLACE) {
6684 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6686 char *restart_detect = stackblock();
6687 STPUTC(*idx, expdest);
6688 if (stackblock() != restart_detect)
6697 /* We've put the replaced text into a buffer at workloc, now
6698 * move it to the right place and adjust the stack.
6700 STPUTC('\0', expdest);
6701 startp = (char *)stackblock() + startloc;
6702 memmove(startp, (char *)stackblock() + workloc, len + 1);
6703 //bb_error_msg("startp:'%s'", startp);
6704 amount = expdest - (startp + len);
6705 STADJUST(-amount, expdest);
6708 #endif /* ENABLE_ASH_BASH_COMPAT */
6710 subtype -= VSTRIMRIGHT;
6712 if (subtype < 0 || subtype > 7)
6715 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6716 zero = subtype >> 1;
6717 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6718 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6720 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6723 memmove(startp, loc, str - loc);
6724 loc = startp + (str - loc) - 1;
6727 amount = loc - expdest;
6728 STADJUST(amount, expdest);
6734 * Add the value of a specialized variable to the stack string.
6735 * name parameter (examples):
6736 * ash -c 'echo $1' name:'1='
6737 * ash -c 'echo $qwe' name:'qwe='
6738 * ash -c 'echo $$' name:'$='
6739 * ash -c 'echo ${$}' name:'$='
6740 * ash -c 'echo ${$##q}' name:'$=q'
6741 * ash -c 'echo ${#$}' name:'$='
6742 * note: examples with bad shell syntax:
6743 * ash -c 'echo ${#$1}' name:'$=1'
6744 * ash -c 'echo ${#1#}' name:'1=#'
6746 static NOINLINE ssize_t
6747 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6754 int quoted = *quotedp;
6755 int subtype = varflags & VSTYPE;
6756 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6757 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6760 sep = (flags & EXP_FULL) << CHAR_BIT;
6761 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6771 num = shellparam.nparam;
6779 goto check_1char_name;
6781 expdest = makestrspace(NOPTS, expdest);
6782 for (i = NOPTS - 1; i >= 0; i--) {
6784 USTPUTC(optletters(i), expdest);
6790 /* handles cases similar to ${#$1} */
6791 if (name[2] != '\0')
6792 raise_error_syntax("bad substitution");
6805 sep |= ifsset() ? ifsval()[0] : ' ';
6812 while ((p = *ap++) != NULL) {
6813 len += strtodest(p, syntax, quotes);
6817 memtodest(&sepc, 1, syntax, quotes);
6832 num = atoi(name); /* number(name) fails on ${N#str} etc */
6833 if (num < 0 || num > shellparam.nparam)
6835 p = num ? shellparam.p[num - 1] : arg0;
6838 /* NB: name has form "VAR=..." */
6840 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6841 * which should be considered before we check variables. */
6843 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6847 str = var_str_list->text;
6848 eq = strchr(str, '=');
6849 if (!eq) /* stop at first non-assignment */
6852 if (name_len == (unsigned)(eq - str)
6853 && strncmp(str, name, name_len) == 0
6856 /* goto value; - WRONG! */
6857 /* think "A=1 A=2 B=$A" */
6859 var_str_list = var_str_list->next;
6860 } while (var_str_list);
6864 p = lookupvar(name);
6869 len = strtodest(p, syntax, quotes);
6870 #if ENABLE_UNICODE_SUPPORT
6871 if (subtype == VSLENGTH && len > 0) {
6872 reinit_unicode_for_ash();
6873 if (unicode_status == UNICODE_ON) {
6874 STADJUST(-len, expdest);
6876 len = unicode_strlen(p);
6884 STADJUST(-len, expdest);
6889 * Expand a variable, and return a pointer to the next character in the
6893 evalvar(char *p, int flag, struct strlist *var_str_list)
6904 varflags = (unsigned char) *p++;
6905 subtype = varflags & VSTYPE;
6908 raise_error_syntax("bad substitution");
6910 quoted = flag & EXP_QUOTED;
6912 easy = (!quoted || (*var == '@' && shellparam.nparam));
6913 startloc = expdest - (char *)stackblock();
6914 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6917 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6918 if (varflags & VSNUL)
6921 if (subtype == VSPLUS) {
6922 varlen = -1 - varlen;
6926 if (subtype == VSMINUS) {
6931 flag | EXP_TILDE | EXP_WORD,
6939 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6943 subevalvar(p, var, 0, subtype, startloc, varflags,
6944 flag & ~QUOTES_ESC, var_str_list);
6947 * Remove any recorded regions beyond
6950 removerecordregions(startloc);
6954 if (varlen < 0 && uflag)
6955 varunset(p, var, 0, 0);
6957 if (subtype == VSLENGTH) {
6958 cvtnum(varlen > 0 ? varlen : 0);
6962 if (subtype == VSNORMAL) {
6966 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6975 case VSTRIMRIGHTMAX:
6976 #if ENABLE_ASH_BASH_COMPAT
6989 * Terminate the string and start recording the pattern
6992 STPUTC('\0', expdest);
6993 patloc = expdest - (char *)stackblock();
6994 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6995 startloc, varflags, flag, var_str_list)) {
6996 int amount = expdest - (
6997 (char *)stackblock() + patloc - 1
6999 STADJUST(-amount, expdest);
7001 /* Remove any recorded regions beyond start of variable */
7002 removerecordregions(startloc);
7007 if (subtype != VSNORMAL) { /* skip to end of alternative */
7010 unsigned char c = *p++;
7013 else if (c == CTLBACKQ) {
7015 argbackq = argbackq->next;
7016 } else if (c == CTLVAR) {
7017 if ((*p++ & VSTYPE) != VSNORMAL)
7019 } else if (c == CTLENDVAR) {
7029 * Add a file name to the list.
7032 addfname(const char *name)
7036 sp = stzalloc(sizeof(*sp));
7037 sp->text = sstrdup(name);
7039 exparg.lastp = &sp->next;
7042 /* If we want to use glob() from libc... */
7043 #if !ENABLE_ASH_INTERNAL_GLOB
7045 /* Add the result of glob() to the list */
7047 addglob(const glob_t *pglob)
7049 char **p = pglob->gl_pathv;
7056 expandmeta(struct strlist *str /*, int flag*/)
7058 /* TODO - EXP_REDIR */
7068 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7083 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7084 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7085 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7087 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7088 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7089 // Which means you need to unescape the string, right? Not so fast:
7090 // if there _is_ a file named "file\?" (with backslash), it is returned
7091 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7092 // You DONT KNOW by looking at the result whether you need to unescape it.
7094 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7095 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7096 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7097 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7098 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7099 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7100 i = glob(p, 0, NULL, &pglob);
7101 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7106 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7107 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7108 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7120 *exparg.lastp = str;
7121 rmescapes(str->text, 0);
7122 exparg.lastp = &str->next;
7124 default: /* GLOB_NOSPACE */
7127 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7134 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7137 * Do metacharacter (i.e. *, ?, [...]) expansion.
7140 expmeta(char *expdir, char *enddir, char *name)
7156 for (p = name; esc = 0, *p; p += esc + 1) {
7157 if (*p == '*' || *p == '?')
7159 else if (*p == '[') {
7166 if (*q == '/' || *q == '\0')
7176 if (p[esc] == '/') {
7179 start = p + esc + 1;
7183 if (metaflag == 0) { /* we've reached the end of the file name */
7184 if (enddir != expdir)
7192 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7203 } while (p < start);
7205 if (enddir == expdir) {
7207 } else if (enddir == expdir + 1 && *expdir == '/') {
7216 if (enddir != expdir)
7218 if (*endname == 0) {
7231 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7232 if (dp->d_name[0] == '.' && !matchdot)
7234 if (pmatch(start, dp->d_name)) {
7236 strcpy(enddir, dp->d_name);
7239 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7242 expmeta(expdir, p, endname);
7248 endname[-esc - 1] = esc ? '\\' : '/';
7251 static struct strlist *
7252 msort(struct strlist *list, int len)
7254 struct strlist *p, *q = NULL;
7255 struct strlist **lpp;
7263 for (n = half; --n >= 0;) {
7267 q->next = NULL; /* terminate first half of list */
7268 q = msort(list, half); /* sort first half of list */
7269 p = msort(p, len - half); /* sort second half */
7272 #if ENABLE_LOCALE_SUPPORT
7273 if (strcoll(p->text, q->text) < 0)
7275 if (strcmp(p->text, q->text) < 0)
7299 * Sort the results of file name expansion. It calculates the number of
7300 * strings to sort and then calls msort (short for merge sort) to do the
7303 static struct strlist *
7304 expsort(struct strlist *str)
7310 for (sp = str; sp; sp = sp->next)
7312 return msort(str, len);
7316 expandmeta(struct strlist *str /*, int flag*/)
7318 static const char metachars[] ALIGN1 = {
7321 /* TODO - EXP_REDIR */
7325 struct strlist **savelastp;
7331 if (!strpbrk(str->text, metachars))
7333 savelastp = exparg.lastp;
7336 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7338 int i = strlen(str->text);
7339 //BUGGY estimation of how long expanded name can be
7340 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7342 expmeta(expdir, expdir, p);
7347 if (exparg.lastp == savelastp) {
7352 *exparg.lastp = str;
7353 rmescapes(str->text, 0);
7354 exparg.lastp = &str->next;
7356 *exparg.lastp = NULL;
7357 *savelastp = sp = expsort(*savelastp);
7358 while (sp->next != NULL)
7360 exparg.lastp = &sp->next;
7365 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7368 * Perform variable substitution and command substitution on an argument,
7369 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7370 * perform splitting and file name expansion. When arglist is NULL, perform
7371 * here document expansion.
7374 expandarg(union node *arg, struct arglist *arglist, int flag)
7379 argbackq = arg->narg.backquote;
7380 STARTSTACKSTR(expdest);
7381 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7382 argstr(arg->narg.text, flag,
7383 /* var_str_list: */ arglist ? arglist->list : NULL);
7384 p = _STPUTC('\0', expdest);
7386 if (arglist == NULL) {
7387 /* here document expanded */
7390 p = grabstackstr(p);
7391 TRACE(("expandarg: p:'%s'\n", p));
7392 exparg.lastp = &exparg.list;
7396 if (flag & EXP_FULL) {
7397 ifsbreakup(p, &exparg);
7398 *exparg.lastp = NULL;
7399 exparg.lastp = &exparg.list;
7400 expandmeta(exparg.list /*, flag*/);
7402 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7404 TRACE(("expandarg: rmescapes:'%s'\n", p));
7406 sp = stzalloc(sizeof(*sp));
7409 exparg.lastp = &sp->next;
7411 *exparg.lastp = NULL;
7413 *arglist->lastp = exparg.list;
7414 arglist->lastp = exparg.lastp;
7422 * Expand shell variables and backquotes inside a here document.
7425 expandhere(union node *arg, int fd)
7427 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7428 full_write(fd, stackblock(), expdest - (char *)stackblock());
7432 * Returns true if the pattern matches the string.
7435 patmatch(char *pattern, const char *string)
7437 return pmatch(preglob(pattern, 0), string);
7441 * See if a pattern matches in a case statement.
7444 casematch(union node *pattern, char *val)
7446 struct stackmark smark;
7449 setstackmark(&smark);
7450 argbackq = pattern->narg.backquote;
7451 STARTSTACKSTR(expdest);
7452 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7453 /* var_str_list: */ NULL);
7454 STACKSTRNUL(expdest);
7456 result = patmatch(stackblock(), val);
7457 popstackmark(&smark);
7462 /* ============ find_command */
7466 int (*builtin)(int, char **) FAST_FUNC;
7467 /* unsigned flags; */
7469 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7470 /* "regular" builtins always take precedence over commands,
7471 * regardless of PATH=....%builtin... position */
7472 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7473 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7476 smallint cmdtype; /* CMDxxx */
7479 /* index >= 0 for commands without path (slashes) */
7480 /* (TODO: what exactly does the value mean? PATH position?) */
7481 /* index == -1 for commands with slashes */
7482 /* index == (-2 - applet_no) for NOFORK applets */
7483 const struct builtincmd *cmd;
7484 struct funcnode *func;
7487 /* values of cmdtype */
7488 #define CMDUNKNOWN -1 /* no entry in table for command */
7489 #define CMDNORMAL 0 /* command is an executable program */
7490 #define CMDFUNCTION 1 /* command is a shell function */
7491 #define CMDBUILTIN 2 /* command is a shell builtin */
7493 /* action to find_command() */
7494 #define DO_ERR 0x01 /* prints errors */
7495 #define DO_ABS 0x02 /* checks absolute paths */
7496 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7497 #define DO_ALTPATH 0x08 /* using alternate path */
7498 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7500 static void find_command(char *, struct cmdentry *, int, const char *);
7503 /* ============ Hashing commands */
7506 * When commands are first encountered, they are entered in a hash table.
7507 * This ensures that a full path search will not have to be done for them
7508 * on each invocation.
7510 * We should investigate converting to a linear search, even though that
7511 * would make the command name "hash" a misnomer.
7515 struct tblentry *next; /* next entry in hash chain */
7516 union param param; /* definition of builtin function */
7517 smallint cmdtype; /* CMDxxx */
7518 char rehash; /* if set, cd done since entry created */
7519 char cmdname[1]; /* name of command */
7522 static struct tblentry **cmdtable;
7523 #define INIT_G_cmdtable() do { \
7524 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7527 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7531 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7533 #if ENABLE_FEATURE_SH_STANDALONE
7534 if (applet_no >= 0) {
7535 if (APPLET_IS_NOEXEC(applet_no)) {
7539 run_applet_no_and_exit(applet_no, argv);
7541 /* re-exec ourselves with the new arguments */
7542 execve(bb_busybox_exec_path, argv, envp);
7543 /* If they called chroot or otherwise made the binary no longer
7544 * executable, fall through */
7551 execve(cmd, argv, envp);
7552 } while (errno == EINTR);
7554 execve(cmd, argv, envp);
7556 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7557 /* Run "cmd" as a shell script:
7558 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7559 * "If the execve() function fails with ENOEXEC, the shell
7560 * shall execute a command equivalent to having a shell invoked
7561 * with the command name as its first operand,
7562 * with any remaining arguments passed to the new shell"
7564 * That is, do not use $SHELL, user's shell, or /bin/sh;
7565 * just call ourselves.
7567 * Note that bash reads ~80 chars of the file, and if it sees
7568 * a zero byte before it sees newline, it doesn't try to
7569 * interpret it, but fails with "cannot execute binary file"
7570 * message and exit code 126. For one, this prevents attempts
7571 * to interpret foreign ELF binaries as shell scripts.
7574 cmd = (char*) bb_busybox_exec_path;
7575 /* NB: this is only possible because all callers of shellexec()
7576 * ensure that the argv[-1] slot exists!
7579 argv[0] = (char*) "ash";
7585 * Exec a program. Never returns. If you change this routine, you may
7586 * have to change the find_command routine as well.
7587 * argv[-1] must exist and be writable! See tryexec() for why.
7589 static void shellexec(char **, const char *, int) NORETURN;
7591 shellexec(char **argv, const char *path, int idx)
7597 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7599 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7600 if (strchr(argv[0], '/') != NULL
7601 #if ENABLE_FEATURE_SH_STANDALONE
7602 || (applet_no = find_applet_by_name(argv[0])) >= 0
7605 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7606 if (applet_no >= 0) {
7607 /* We tried execing ourself, but it didn't work.
7608 * Maybe /proc/self/exe doesn't exist?
7617 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7618 if (--idx < 0 && pathopt == NULL) {
7619 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7620 if (errno != ENOENT && errno != ENOTDIR)
7627 /* Map to POSIX errors */
7639 exitstatus = exerrno;
7640 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7641 argv[0], e, suppress_int));
7642 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7647 printentry(struct tblentry *cmdp)
7653 idx = cmdp->param.index;
7656 name = path_advance(&path, cmdp->cmdname);
7658 } while (--idx >= 0);
7659 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7663 * Clear out command entries. The argument specifies the first entry in
7664 * PATH which has changed.
7667 clearcmdentry(int firstchange)
7669 struct tblentry **tblp;
7670 struct tblentry **pp;
7671 struct tblentry *cmdp;
7674 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7676 while ((cmdp = *pp) != NULL) {
7677 if ((cmdp->cmdtype == CMDNORMAL &&
7678 cmdp->param.index >= firstchange)
7679 || (cmdp->cmdtype == CMDBUILTIN &&
7680 builtinloc >= firstchange)
7693 * Locate a command in the command hash table. If "add" is nonzero,
7694 * add the command to the table if it is not already present. The
7695 * variable "lastcmdentry" is set to point to the address of the link
7696 * pointing to the entry, so that delete_cmd_entry can delete the
7699 * Interrupts must be off if called with add != 0.
7701 static struct tblentry **lastcmdentry;
7703 static struct tblentry *
7704 cmdlookup(const char *name, int add)
7706 unsigned int hashval;
7708 struct tblentry *cmdp;
7709 struct tblentry **pp;
7712 hashval = (unsigned char)*p << 4;
7714 hashval += (unsigned char)*p++;
7716 pp = &cmdtable[hashval % CMDTABLESIZE];
7717 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7718 if (strcmp(cmdp->cmdname, name) == 0)
7722 if (add && cmdp == NULL) {
7723 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7725 /* + 1 - already done because
7726 * tblentry::cmdname is char[1] */);
7727 /*cmdp->next = NULL; - ckzalloc did it */
7728 cmdp->cmdtype = CMDUNKNOWN;
7729 strcpy(cmdp->cmdname, name);
7736 * Delete the command entry returned on the last lookup.
7739 delete_cmd_entry(void)
7741 struct tblentry *cmdp;
7744 cmdp = *lastcmdentry;
7745 *lastcmdentry = cmdp->next;
7746 if (cmdp->cmdtype == CMDFUNCTION)
7747 freefunc(cmdp->param.func);
7753 * Add a new command entry, replacing any existing command entry for
7754 * the same name - except special builtins.
7757 addcmdentry(char *name, struct cmdentry *entry)
7759 struct tblentry *cmdp;
7761 cmdp = cmdlookup(name, 1);
7762 if (cmdp->cmdtype == CMDFUNCTION) {
7763 freefunc(cmdp->param.func);
7765 cmdp->cmdtype = entry->cmdtype;
7766 cmdp->param = entry->u;
7770 static int FAST_FUNC
7771 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7773 struct tblentry **pp;
7774 struct tblentry *cmdp;
7776 struct cmdentry entry;
7779 if (nextopt("r") != '\0') {
7784 if (*argptr == NULL) {
7785 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7786 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7787 if (cmdp->cmdtype == CMDNORMAL)
7795 while ((name = *argptr) != NULL) {
7796 cmdp = cmdlookup(name, 0);
7798 && (cmdp->cmdtype == CMDNORMAL
7799 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7803 find_command(name, &entry, DO_ERR, pathval());
7804 if (entry.cmdtype == CMDUNKNOWN)
7812 * Called when a cd is done. Marks all commands so the next time they
7813 * are executed they will be rehashed.
7818 struct tblentry **pp;
7819 struct tblentry *cmdp;
7821 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7822 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7823 if (cmdp->cmdtype == CMDNORMAL
7824 || (cmdp->cmdtype == CMDBUILTIN
7825 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7835 * Fix command hash table when PATH changed.
7836 * Called before PATH is changed. The argument is the new value of PATH;
7837 * pathval() still returns the old value at this point.
7838 * Called with interrupts off.
7840 static void FAST_FUNC
7841 changepath(const char *new)
7849 firstchange = 9999; /* assume no change */
7855 if ((*old == '\0' && *new == ':')
7856 || (*old == ':' && *new == '\0')
7860 old = new; /* ignore subsequent differences */
7864 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7871 if (builtinloc < 0 && idx_bltin >= 0)
7872 builtinloc = idx_bltin; /* zap builtins */
7873 if (builtinloc >= 0 && idx_bltin < 0)
7875 clearcmdentry(firstchange);
7876 builtinloc = idx_bltin;
7901 #if ENABLE_ASH_BASH_COMPAT
7912 typedef smallint token_id_t;
7914 /* Nth bit indicates if token marks the end of a list */
7917 /* 0 */ | (1u << TEOF)
7918 /* 1 */ | (0u << TNL)
7919 /* 2 */ | (0u << TREDIR)
7920 /* 3 */ | (0u << TWORD)
7921 /* 4 */ | (0u << TSEMI)
7922 /* 5 */ | (0u << TBACKGND)
7923 /* 6 */ | (0u << TAND)
7924 /* 7 */ | (0u << TOR)
7925 /* 8 */ | (0u << TPIPE)
7926 /* 9 */ | (0u << TLP)
7927 /* 10 */ | (1u << TRP)
7928 /* 11 */ | (1u << TENDCASE)
7929 /* 12 */ | (1u << TENDBQUOTE)
7930 /* 13 */ | (0u << TNOT)
7931 /* 14 */ | (0u << TCASE)
7932 /* 15 */ | (1u << TDO)
7933 /* 16 */ | (1u << TDONE)
7934 /* 17 */ | (1u << TELIF)
7935 /* 18 */ | (1u << TELSE)
7936 /* 19 */ | (1u << TESAC)
7937 /* 20 */ | (1u << TFI)
7938 /* 21 */ | (0u << TFOR)
7939 #if ENABLE_ASH_BASH_COMPAT
7940 /* 22 */ | (0u << TFUNCTION)
7942 /* 23 */ | (0u << TIF)
7943 /* 24 */ | (0u << TIN)
7944 /* 25 */ | (1u << TTHEN)
7945 /* 26 */ | (0u << TUNTIL)
7946 /* 27 */ | (0u << TWHILE)
7947 /* 28 */ | (0u << TBEGIN)
7948 /* 29 */ | (1u << TEND)
7949 , /* thus far 29 bits used */
7952 static const char *const tokname_array[] = {
7966 #define KWDOFFSET 13
7967 /* the following are keywords */
7977 #if ENABLE_ASH_BASH_COMPAT
7989 /* Wrapper around strcmp for qsort/bsearch/... */
7991 pstrcmp(const void *a, const void *b)
7993 return strcmp((char*)a, *(char**)b);
7996 static const char *const *
7997 findkwd(const char *s)
7999 return bsearch(s, tokname_array + KWDOFFSET,
8000 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8001 sizeof(tokname_array[0]), pstrcmp);
8005 * Locate and print what a word is...
8008 describe_command(char *command, const char *path, int describe_command_verbose)
8010 struct cmdentry entry;
8011 struct tblentry *cmdp;
8012 #if ENABLE_ASH_ALIAS
8013 const struct alias *ap;
8016 path = path ? path : pathval();
8018 if (describe_command_verbose) {
8022 /* First look at the keywords */
8023 if (findkwd(command)) {
8024 out1str(describe_command_verbose ? " is a shell keyword" : command);
8028 #if ENABLE_ASH_ALIAS
8029 /* Then look at the aliases */
8030 ap = lookupalias(command, 0);
8032 if (!describe_command_verbose) {
8037 out1fmt(" is an alias for %s", ap->val);
8041 /* Then check if it is a tracked alias */
8042 cmdp = cmdlookup(command, 0);
8044 entry.cmdtype = cmdp->cmdtype;
8045 entry.u = cmdp->param;
8047 /* Finally use brute force */
8048 find_command(command, &entry, DO_ABS, path);
8051 switch (entry.cmdtype) {
8053 int j = entry.u.index;
8059 p = path_advance(&path, command);
8063 if (describe_command_verbose) {
8065 (cmdp ? " a tracked alias for" : nullstr), p
8074 if (describe_command_verbose) {
8075 out1str(" is a shell function");
8082 if (describe_command_verbose) {
8083 out1fmt(" is a %sshell builtin",
8084 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8085 "special " : nullstr
8093 if (describe_command_verbose) {
8094 out1str(": not found\n");
8103 static int FAST_FUNC
8104 typecmd(int argc UNUSED_PARAM, char **argv)
8110 /* type -p ... ? (we don't bother checking for 'p') */
8111 if (argv[1] && argv[1][0] == '-') {
8116 err |= describe_command(argv[i++], NULL, verbose);
8121 #if ENABLE_ASH_CMDCMD
8122 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8124 parse_command_args(char **argv, const char **path)
8137 if (c == '-' && !*cp) {
8145 *path = bb_default_path;
8148 /* run 'typecmd' for other options */
8157 static int FAST_FUNC
8158 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8166 const char *path = NULL;
8168 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8169 * never reaches this function.
8172 while ((c = nextopt("pvV")) != '\0')
8174 verify |= VERIFY_VERBOSE;
8176 /*verify |= VERIFY_BRIEF*/;
8182 path = bb_default_path;
8184 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8186 if (/*verify && */ cmd)
8187 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8194 /*static int funcblocksize; // size of structures in function */
8195 /*static int funcstringsize; // size of strings in node */
8196 static void *funcblock; /* block to allocate function from */
8197 static char *funcstring_end; /* end of block to allocate strings from */
8199 /* flags in argument to evaltree */
8200 #define EV_EXIT 01 /* exit after evaluating tree */
8201 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8203 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8204 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8205 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8206 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8207 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8208 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8209 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8210 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8211 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8212 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8213 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8214 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8215 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8216 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8217 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8218 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8219 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8220 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8221 #if ENABLE_ASH_BASH_COMPAT
8222 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8224 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8225 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8226 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8227 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8228 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8229 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8230 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8231 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8232 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8235 static int calcsize(int funcblocksize, union node *n);
8238 sizenodelist(int funcblocksize, struct nodelist *lp)
8241 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8242 funcblocksize = calcsize(funcblocksize, lp->n);
8245 return funcblocksize;
8249 calcsize(int funcblocksize, union node *n)
8252 return funcblocksize;
8253 funcblocksize += nodesize[n->type];
8256 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8257 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8258 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8261 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8266 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8267 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8274 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8275 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8278 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8279 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8280 funcblocksize = calcsize(funcblocksize, n->nif.test);
8283 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8284 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8285 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8288 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8289 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8292 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8293 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8294 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8298 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8299 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8300 funcblocksize = calcsize(funcblocksize, n->narg.next);
8303 #if ENABLE_ASH_BASH_COMPAT
8310 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8311 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8315 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8316 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8320 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8321 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8324 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8327 return funcblocksize;
8331 nodeckstrdup(char *s)
8333 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8334 return strcpy(funcstring_end, s);
8337 static union node *copynode(union node *);
8339 static struct nodelist *
8340 copynodelist(struct nodelist *lp)
8342 struct nodelist *start;
8343 struct nodelist **lpp;
8348 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8349 (*lpp)->n = copynode(lp->n);
8351 lpp = &(*lpp)->next;
8358 copynode(union node *n)
8365 funcblock = (char *) funcblock + nodesize[n->type];
8369 new->ncmd.redirect = copynode(n->ncmd.redirect);
8370 new->ncmd.args = copynode(n->ncmd.args);
8371 new->ncmd.assign = copynode(n->ncmd.assign);
8374 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8375 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8380 new->nredir.redirect = copynode(n->nredir.redirect);
8381 new->nredir.n = copynode(n->nredir.n);
8388 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8389 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8392 new->nif.elsepart = copynode(n->nif.elsepart);
8393 new->nif.ifpart = copynode(n->nif.ifpart);
8394 new->nif.test = copynode(n->nif.test);
8397 new->nfor.var = nodeckstrdup(n->nfor.var);
8398 new->nfor.body = copynode(n->nfor.body);
8399 new->nfor.args = copynode(n->nfor.args);
8402 new->ncase.cases = copynode(n->ncase.cases);
8403 new->ncase.expr = copynode(n->ncase.expr);
8406 new->nclist.body = copynode(n->nclist.body);
8407 new->nclist.pattern = copynode(n->nclist.pattern);
8408 new->nclist.next = copynode(n->nclist.next);
8412 new->narg.backquote = copynodelist(n->narg.backquote);
8413 new->narg.text = nodeckstrdup(n->narg.text);
8414 new->narg.next = copynode(n->narg.next);
8417 #if ENABLE_ASH_BASH_COMPAT
8424 new->nfile.fname = copynode(n->nfile.fname);
8425 new->nfile.fd = n->nfile.fd;
8426 new->nfile.next = copynode(n->nfile.next);
8430 new->ndup.vname = copynode(n->ndup.vname);
8431 new->ndup.dupfd = n->ndup.dupfd;
8432 new->ndup.fd = n->ndup.fd;
8433 new->ndup.next = copynode(n->ndup.next);
8437 new->nhere.doc = copynode(n->nhere.doc);
8438 new->nhere.fd = n->nhere.fd;
8439 new->nhere.next = copynode(n->nhere.next);
8442 new->nnot.com = copynode(n->nnot.com);
8445 new->type = n->type;
8450 * Make a copy of a parse tree.
8452 static struct funcnode *
8453 copyfunc(union node *n)
8458 /*funcstringsize = 0;*/
8459 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8460 f = ckzalloc(blocksize /* + funcstringsize */);
8461 funcblock = (char *) f + offsetof(struct funcnode, n);
8462 funcstring_end = (char *) f + blocksize;
8464 /* f->count = 0; - ckzalloc did it */
8469 * Define a shell function.
8472 defun(union node *func)
8474 struct cmdentry entry;
8477 entry.cmdtype = CMDFUNCTION;
8478 entry.u.func = copyfunc(func);
8479 addcmdentry(func->narg.text, &entry);
8483 /* Reasons for skipping commands (see comment on breakcmd routine) */
8484 #define SKIPBREAK (1 << 0)
8485 #define SKIPCONT (1 << 1)
8486 #define SKIPFUNC (1 << 2)
8487 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8488 static int skipcount; /* number of levels to skip */
8489 static int funcnest; /* depth of function calls */
8490 static int loopnest; /* current loop nesting level */
8492 /* Forward decl way out to parsing code - dotrap needs it */
8493 static int evalstring(char *s, int flags);
8495 /* Called to execute a trap.
8496 * Single callsite - at the end of evaltree().
8497 * If we return non-zero, evaltree raises EXEXIT exception.
8499 * Perhaps we should avoid entering new trap handlers
8500 * while we are executing a trap handler. [is it a TODO?]
8507 uint8_t last_status;
8512 last_status = exitstatus;
8516 TRACE(("dotrap entered\n"));
8517 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8529 /* non-trapped SIGINT is handled separately by raise_interrupt,
8530 * don't upset it by resetting gotsig[SIGINT-1] */
8531 if (sig == SIGINT && !p)
8534 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8540 exitstatus = last_status;
8541 TRACE(("dotrap returns\n"));
8544 /* forward declarations - evaluation is fairly recursive business... */
8545 static int evalloop(union node *, int);
8546 static int evalfor(union node *, int);
8547 static int evalcase(union node *, int);
8548 static int evalsubshell(union node *, int);
8549 static void expredir(union node *);
8550 static int evalpipe(union node *, int);
8551 static int evalcommand(union node *, int);
8552 static int evalbltin(const struct builtincmd *, int, char **, int);
8553 static void prehash(union node *);
8556 * Evaluate a parse tree. The value is left in the global variable
8560 evaltree(union node *n, int flags)
8563 int (*evalfn)(union node *, int);
8567 TRACE(("evaltree(NULL) called\n"));
8570 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8577 out1fmt("Node type = %d\n", n->type);
8582 status = !evaltree(n->nnot.com, EV_TESTED);
8585 expredir(n->nredir.redirect);
8586 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8588 status = evaltree(n->nredir.n, flags & EV_TESTED);
8590 if (n->nredir.redirect)
8591 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8594 evalfn = evalcommand;
8596 if (eflag && !(flags & EV_TESTED))
8608 evalfn = evalsubshell;
8621 #error NAND + 1 != NOR
8623 #if NOR + 1 != NSEMI
8624 #error NOR + 1 != NSEMI
8626 unsigned is_or = n->type - NAND;
8629 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8631 if ((!status) == is_or || evalskip)
8637 status = evalfn(n, flags);
8641 status = evaltree(n->nif.test, EV_TESTED);
8648 if (n->nif.elsepart) {
8649 n = n->nif.elsepart;
8656 /* Not necessary. To test it:
8657 * "false; f() { qwerty; }; echo $?" should print 0.
8661 exitstatus = status;
8665 /* Order of checks below is important:
8666 * signal handlers trigger before exit caused by "set -e".
8670 if (checkexit & status)
8671 raise_exception(EXEXIT);
8672 if (flags & EV_EXIT)
8673 raise_exception(EXEXIT);
8675 TRACE(("leaving evaltree (no interrupts)\n"));
8679 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8682 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8687 int skip = evalskip;
8694 if (--skipcount <= 0) {
8705 evalloop(union node *n, int flags)
8716 i = evaltree(n->nbinary.ch1, EV_TESTED);
8718 if (skip == SKIPFUNC)
8722 if (n->type != NWHILE)
8726 status = evaltree(n->nbinary.ch2, flags);
8728 } while (!(skip & ~SKIPCONT));
8735 evalfor(union node *n, int flags)
8737 struct arglist arglist;
8740 struct stackmark smark;
8743 setstackmark(&smark);
8744 arglist.list = NULL;
8745 arglist.lastp = &arglist.list;
8746 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8747 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8749 *arglist.lastp = NULL;
8753 for (sp = arglist.list; sp; sp = sp->next) {
8754 setvar0(n->nfor.var, sp->text);
8755 status = evaltree(n->nfor.body, flags);
8756 if (skiploop() & ~SKIPCONT)
8760 popstackmark(&smark);
8766 evalcase(union node *n, int flags)
8770 struct arglist arglist;
8771 struct stackmark smark;
8774 setstackmark(&smark);
8775 arglist.list = NULL;
8776 arglist.lastp = &arglist.list;
8777 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8778 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8779 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8780 if (casematch(patp, arglist.list->text)) {
8781 /* Ensure body is non-empty as otherwise
8782 * EV_EXIT may prevent us from setting the
8785 if (evalskip == 0 && cp->nclist.body) {
8786 status = evaltree(cp->nclist.body, flags);
8793 popstackmark(&smark);
8799 * Kick off a subshell to evaluate a tree.
8802 evalsubshell(union node *n, int flags)
8805 int backgnd = (n->type == NBACKGND);
8808 expredir(n->nredir.redirect);
8809 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8812 jp = makejob(/*n,*/ 1);
8813 if (forkshell(jp, n, backgnd) == 0) {
8818 flags &= ~EV_TESTED;
8820 redirect(n->nredir.redirect, 0);
8821 evaltreenr(n->nredir.n, flags);
8827 status = waitforjob(jp);
8833 * Compute the names of the files in a redirection list.
8835 static void fixredir(union node *, const char *, int);
8837 expredir(union node *n)
8841 for (redir = n; redir; redir = redir->nfile.next) {
8845 fn.lastp = &fn.list;
8846 switch (redir->type) {
8850 #if ENABLE_ASH_BASH_COMPAT
8855 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8856 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8857 #if ENABLE_ASH_BASH_COMPAT
8861 // By the design of stack allocator, the loop of this kind:
8862 // while true; do while true; do break; done </dev/null; done
8863 // will look like a memory leak: ash plans to free expfname's
8864 // of "/dev/null" as soon as it finishes running the loop
8865 // (in this case, never).
8866 // This "fix" is wrong:
8867 if (redir->nfile.expfname)
8868 stunalloc(redir->nfile.expfname);
8869 // It results in corrupted state of stacked allocations.
8871 redir->nfile.expfname = fn.list->text;
8874 case NTOFD: /* >& */
8875 if (redir->ndup.vname) {
8876 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8877 if (fn.list == NULL)
8878 ash_msg_and_raise_error("redir error");
8879 #if ENABLE_ASH_BASH_COMPAT
8880 //FIXME: we used expandarg with different args!
8881 if (!isdigit_str9(fn.list->text)) {
8882 /* >&file, not >&fd */
8883 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8884 ash_msg_and_raise_error("redir error");
8886 goto store_expfname;
8889 fixredir(redir, fn.list->text, 1);
8897 * Evaluate a pipeline. All the processes in the pipeline are children
8898 * of the process creating the pipeline. (This differs from some versions
8899 * of the shell, which make the last process in a pipeline the parent
8903 evalpipe(union node *n, int flags)
8906 struct nodelist *lp;
8912 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8914 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8918 jp = makejob(/*n,*/ pipelen);
8920 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8924 if (pipe(pip) < 0) {
8926 ash_msg_and_raise_error("pipe call failed");
8929 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8943 evaltreenr(lp->n, flags);
8950 /* Don't want to trigger debugging */
8954 if (n->npipe.pipe_backgnd == 0) {
8955 status = waitforjob(jp);
8956 TRACE(("evalpipe: job done exit status %d\n", status));
8964 * Controls whether the shell is interactive or not.
8967 setinteractive(int on)
8969 static smallint is_interactive;
8971 if (++on == is_interactive)
8973 is_interactive = on;
8977 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8978 if (is_interactive > 1) {
8979 /* Looks like they want an interactive shell */
8980 static smallint did_banner;
8983 /* note: ash and hush share this string */
8984 out1fmt("\n\n%s %s\n"
8985 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8988 "built-in shell (ash)"
9002 setinteractive(iflag);
9004 #if ENABLE_FEATURE_EDITING_VI
9006 line_input_state->flags |= VI_MODE;
9008 line_input_state->flags &= ~VI_MODE;
9010 viflag = 0; /* forcibly keep the option off */
9014 static struct localvar *localvars;
9017 * Called after a function returns.
9018 * Interrupts must be off.
9023 struct localvar *lvp;
9026 while ((lvp = localvars) != NULL) {
9027 localvars = lvp->next;
9029 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9030 if (vp == NULL) { /* $- saved */
9031 memcpy(optlist, lvp->text, sizeof(optlist));
9032 free((char*)lvp->text);
9034 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9035 unsetvar(vp->var_text);
9038 vp->var_func(var_end(lvp->text));
9039 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9040 free((char*)vp->var_text);
9041 vp->flags = lvp->flags;
9042 vp->var_text = lvp->text;
9049 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9051 volatile struct shparam saveparam;
9052 struct localvar *volatile savelocalvars;
9053 struct jmploc *volatile savehandler;
9054 struct jmploc jmploc;
9057 saveparam = shellparam;
9058 savelocalvars = localvars;
9059 savehandler = exception_handler;
9060 e = setjmp(jmploc.loc);
9065 exception_handler = &jmploc;
9067 shellparam.malloced = 0;
9071 shellparam.nparam = argc - 1;
9072 shellparam.p = argv + 1;
9073 #if ENABLE_ASH_GETOPTS
9074 shellparam.optind = 1;
9075 shellparam.optoff = -1;
9077 evaltree(func->n.narg.next, flags & EV_TESTED);
9083 localvars = savelocalvars;
9084 freeparam(&shellparam);
9085 shellparam = saveparam;
9086 exception_handler = savehandler;
9088 evalskip &= ~SKIPFUNC;
9093 * Make a variable a local variable. When a variable is made local, it's
9094 * value and flags are saved in a localvar structure. The saved values
9095 * will be restored when the shell function returns. We handle the name
9096 * "-" as a special case: it makes changes to "set +-options" local
9097 * (options will be restored on return from the function).
9102 struct localvar *lvp;
9105 char *eq = strchr(name, '=');
9108 /* Cater for duplicate "local". Examples:
9109 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9110 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9114 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9118 * it's a duplicate "local VAR" declaration, do nothing
9125 lvp = ckzalloc(sizeof(*lvp));
9126 if (LONE_DASH(name)) {
9128 p = ckmalloc(sizeof(optlist));
9129 lvp->text = memcpy(p, optlist, sizeof(optlist));
9132 vpp = hashvar(name);
9133 vp = *findvar(vpp, name);
9135 /* variable did not exist yet */
9137 setvareq(name, VSTRFIXED);
9139 setvar(name, NULL, VSTRFIXED);
9140 vp = *vpp; /* the new variable */
9141 lvp->flags = VUNSET;
9143 lvp->text = vp->var_text;
9144 lvp->flags = vp->flags;
9145 /* make sure neither "struct var" nor string gets freed
9146 * during (un)setting:
9148 vp->flags |= VSTRFIXED|VTEXTFIXED;
9152 /* "local VAR" unsets VAR: */
9153 setvar0(name, NULL);
9157 lvp->next = localvars;
9164 * The "local" command.
9166 static int FAST_FUNC
9167 localcmd(int argc UNUSED_PARAM, char **argv)
9172 ash_msg_and_raise_error("not in a function");
9175 while ((name = *argv++) != NULL) {
9181 static int FAST_FUNC
9182 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9187 static int FAST_FUNC
9188 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9193 static int FAST_FUNC
9194 execcmd(int argc UNUSED_PARAM, char **argv)
9197 iflag = 0; /* exit on error */
9200 /* We should set up signals for "exec CMD"
9201 * the same way as for "CMD" without "exec".
9202 * But optschanged->setinteractive->setsignal
9203 * still thought we are a root shell. Therefore, for example,
9204 * SIGQUIT is still set to IGN. Fix it:
9208 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9209 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9210 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9212 shellexec(argv + 1, pathval(), 0);
9219 * The return command.
9221 static int FAST_FUNC
9222 returncmd(int argc UNUSED_PARAM, char **argv)
9225 * If called outside a function, do what ksh does;
9226 * skip the rest of the file.
9228 evalskip = SKIPFUNC;
9229 return argv[1] ? number(argv[1]) : exitstatus;
9232 /* Forward declarations for builtintab[] */
9233 static int breakcmd(int, char **) FAST_FUNC;
9234 static int dotcmd(int, char **) FAST_FUNC;
9235 static int evalcmd(int, char **, int) FAST_FUNC;
9236 static int exitcmd(int, char **) FAST_FUNC;
9237 static int exportcmd(int, char **) FAST_FUNC;
9238 #if ENABLE_ASH_GETOPTS
9239 static int getoptscmd(int, char **) FAST_FUNC;
9242 static int helpcmd(int, char **) FAST_FUNC;
9245 static int historycmd(int, char **) FAST_FUNC;
9247 #if ENABLE_SH_MATH_SUPPORT
9248 static int letcmd(int, char **) FAST_FUNC;
9250 static int readcmd(int, char **) FAST_FUNC;
9251 static int setcmd(int, char **) FAST_FUNC;
9252 static int shiftcmd(int, char **) FAST_FUNC;
9253 static int timescmd(int, char **) FAST_FUNC;
9254 static int trapcmd(int, char **) FAST_FUNC;
9255 static int umaskcmd(int, char **) FAST_FUNC;
9256 static int unsetcmd(int, char **) FAST_FUNC;
9257 static int ulimitcmd(int, char **) FAST_FUNC;
9259 #define BUILTIN_NOSPEC "0"
9260 #define BUILTIN_SPECIAL "1"
9261 #define BUILTIN_REGULAR "2"
9262 #define BUILTIN_SPEC_REG "3"
9263 #define BUILTIN_ASSIGN "4"
9264 #define BUILTIN_SPEC_ASSG "5"
9265 #define BUILTIN_REG_ASSG "6"
9266 #define BUILTIN_SPEC_REG_ASSG "7"
9268 /* Stubs for calling non-FAST_FUNC's */
9269 #if ENABLE_ASH_BUILTIN_ECHO
9270 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9272 #if ENABLE_ASH_BUILTIN_PRINTF
9273 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9275 #if ENABLE_ASH_BUILTIN_TEST
9276 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9279 /* Keep these in proper order since it is searched via bsearch() */
9280 static const struct builtincmd builtintab[] = {
9281 { BUILTIN_SPEC_REG "." , dotcmd },
9282 { BUILTIN_SPEC_REG ":" , truecmd },
9283 #if ENABLE_ASH_BUILTIN_TEST
9284 { BUILTIN_REGULAR "[" , testcmd },
9285 # if ENABLE_ASH_BASH_COMPAT
9286 { BUILTIN_REGULAR "[[" , testcmd },
9289 #if ENABLE_ASH_ALIAS
9290 { BUILTIN_REG_ASSG "alias" , aliascmd },
9293 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9295 { BUILTIN_SPEC_REG "break" , breakcmd },
9296 { BUILTIN_REGULAR "cd" , cdcmd },
9297 { BUILTIN_NOSPEC "chdir" , cdcmd },
9298 #if ENABLE_ASH_CMDCMD
9299 { BUILTIN_REGULAR "command" , commandcmd },
9301 { BUILTIN_SPEC_REG "continue", breakcmd },
9302 #if ENABLE_ASH_BUILTIN_ECHO
9303 { BUILTIN_REGULAR "echo" , echocmd },
9305 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9306 { BUILTIN_SPEC_REG "exec" , execcmd },
9307 { BUILTIN_SPEC_REG "exit" , exitcmd },
9308 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9309 { BUILTIN_REGULAR "false" , falsecmd },
9311 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9313 #if ENABLE_ASH_GETOPTS
9314 { BUILTIN_REGULAR "getopts" , getoptscmd },
9316 { BUILTIN_NOSPEC "hash" , hashcmd },
9318 { BUILTIN_NOSPEC "help" , helpcmd },
9321 { BUILTIN_NOSPEC "history" , historycmd },
9324 { BUILTIN_REGULAR "jobs" , jobscmd },
9325 { BUILTIN_REGULAR "kill" , killcmd },
9327 #if ENABLE_SH_MATH_SUPPORT
9328 { BUILTIN_NOSPEC "let" , letcmd },
9330 { BUILTIN_ASSIGN "local" , localcmd },
9331 #if ENABLE_ASH_BUILTIN_PRINTF
9332 { BUILTIN_REGULAR "printf" , printfcmd },
9334 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9335 { BUILTIN_REGULAR "read" , readcmd },
9336 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9337 { BUILTIN_SPEC_REG "return" , returncmd },
9338 { BUILTIN_SPEC_REG "set" , setcmd },
9339 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9340 #if ENABLE_ASH_BASH_COMPAT
9341 { BUILTIN_SPEC_REG "source" , dotcmd },
9343 #if ENABLE_ASH_BUILTIN_TEST
9344 { BUILTIN_REGULAR "test" , testcmd },
9346 { BUILTIN_SPEC_REG "times" , timescmd },
9347 { BUILTIN_SPEC_REG "trap" , trapcmd },
9348 { BUILTIN_REGULAR "true" , truecmd },
9349 { BUILTIN_NOSPEC "type" , typecmd },
9350 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9351 { BUILTIN_REGULAR "umask" , umaskcmd },
9352 #if ENABLE_ASH_ALIAS
9353 { BUILTIN_REGULAR "unalias" , unaliascmd },
9355 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9356 { BUILTIN_REGULAR "wait" , waitcmd },
9359 /* Should match the above table! */
9360 #define COMMANDCMD (builtintab + \
9362 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9363 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9364 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9365 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9366 /* break cd cddir */ 3)
9367 #define EVALCMD (COMMANDCMD + \
9368 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9369 /* continue */ 1 + \
9370 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9372 #define EXECCMD (EVALCMD + \
9376 * Search the table of builtin commands.
9379 pstrcmp1(const void *a, const void *b)
9381 return strcmp((char*)a, *(char**)b + 1);
9383 static struct builtincmd *
9384 find_builtin(const char *name)
9386 struct builtincmd *bp;
9389 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9396 * Execute a simple command.
9399 isassignment(const char *p)
9401 const char *q = endofname(p);
9406 static int FAST_FUNC
9407 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9409 /* Preserve exitstatus of a previous possible redirection
9410 * as POSIX mandates */
9411 return back_exitstatus;
9414 evalcommand(union node *cmd, int flags)
9416 static const struct builtincmd null_bltin = {
9417 "\0\0", bltincmd /* why three NULs? */
9419 struct stackmark smark;
9421 struct arglist arglist;
9422 struct arglist varlist;
9425 const struct strlist *sp;
9426 struct cmdentry cmdentry;
9433 struct builtincmd *bcmd;
9434 smallint cmd_is_exec;
9435 smallint pseudovarflag = 0;
9437 /* First expand the arguments. */
9438 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9439 setstackmark(&smark);
9440 back_exitstatus = 0;
9442 cmdentry.cmdtype = CMDBUILTIN;
9443 cmdentry.u.cmd = &null_bltin;
9444 varlist.lastp = &varlist.list;
9445 *varlist.lastp = NULL;
9446 arglist.lastp = &arglist.list;
9447 *arglist.lastp = NULL;
9450 if (cmd->ncmd.args) {
9451 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9452 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9455 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9456 struct strlist **spp;
9458 spp = arglist.lastp;
9459 if (pseudovarflag && isassignment(argp->narg.text))
9460 expandarg(argp, &arglist, EXP_VARTILDE);
9462 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9464 for (sp = *spp; sp; sp = sp->next)
9468 /* Reserve one extra spot at the front for shellexec. */
9469 nargv = stalloc(sizeof(char *) * (argc + 2));
9471 for (sp = arglist.list; sp; sp = sp->next) {
9472 TRACE(("evalcommand arg: %s\n", sp->text));
9473 *nargv++ = sp->text;
9478 if (iflag && funcnest == 0 && argc > 0)
9479 lastarg = nargv[-1];
9482 expredir(cmd->ncmd.redirect);
9483 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9485 path = vpath.var_text;
9486 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9487 struct strlist **spp;
9490 spp = varlist.lastp;
9491 expandarg(argp, &varlist, EXP_VARTILDE);
9494 * Modify the command lookup path, if a PATH= assignment
9498 if (varcmp(p, path) == 0)
9502 /* Print the command if xflag is set. */
9505 const char *p = " %s" + 1;
9507 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9509 for (n = 0; n < 2; n++) {
9511 fdprintf(preverrout_fd, p, sp->text);
9517 safe_write(preverrout_fd, "\n", 1);
9523 /* Now locate the command. */
9525 int cmd_flag = DO_ERR;
9526 #if ENABLE_ASH_CMDCMD
9527 const char *oldpath = path + 5;
9531 find_command(argv[0], &cmdentry, cmd_flag, path);
9532 if (cmdentry.cmdtype == CMDUNKNOWN) {
9533 flush_stdout_stderr();
9538 /* implement bltin and command here */
9539 if (cmdentry.cmdtype != CMDBUILTIN)
9542 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9543 if (cmdentry.u.cmd == EXECCMD)
9545 #if ENABLE_ASH_CMDCMD
9546 if (cmdentry.u.cmd == COMMANDCMD) {
9548 nargv = parse_command_args(argv, &path);
9551 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9552 * nargv => "PROG". path is updated if -p.
9554 argc -= nargv - argv;
9556 cmd_flag |= DO_NOFUNC;
9564 /* We have a redirection error. */
9566 raise_exception(EXERROR);
9568 exitstatus = status;
9572 /* Execute the command. */
9573 switch (cmdentry.cmdtype) {
9576 #if ENABLE_FEATURE_SH_NOFORK
9577 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9578 * around run_nofork_applet() call.
9579 * (2) Should this check also be done in forkshell()?
9580 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9582 /* find_command() encodes applet_no as (-2 - applet_no) */
9583 int applet_no = (- cmdentry.u.index - 2);
9584 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9585 listsetvar(varlist.list, VEXPORT|VSTACK);
9586 /* run <applet>_main() */
9587 status = run_nofork_applet(applet_no, argv);
9591 /* Can we avoid forking off? For example, very last command
9592 * in a script or a subshell does not need forking,
9593 * we can just exec it.
9595 if (!(flags & EV_EXIT) || may_have_traps) {
9596 /* No, forking off a child is necessary */
9598 jp = makejob(/*cmd,*/ 1);
9599 if (forkshell(jp, cmd, FORK_FG) != 0) {
9601 status = waitforjob(jp);
9603 TRACE(("forked child exited with %d\n", status));
9608 /* fall through to exec'ing external program */
9610 listsetvar(varlist.list, VEXPORT|VSTACK);
9611 shellexec(argv, path, cmdentry.u.index);
9615 cmdenviron = varlist.list;
9617 struct strlist *list = cmdenviron;
9619 if (spclbltin > 0 || argc == 0) {
9621 if (cmd_is_exec && argc > 1)
9624 listsetvar(list, i);
9626 /* Tight loop with builtins only:
9627 * "while kill -0 $child; do true; done"
9628 * will never exit even if $child died, unless we do this
9629 * to reap the zombie and make kill detect that it's gone: */
9630 dowait(DOWAIT_NONBLOCK, NULL);
9632 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9633 if (exception_type == EXERROR && spclbltin <= 0) {
9638 longjmp(exception_handler->loc, 1);
9643 listsetvar(varlist.list, 0);
9644 /* See above for the rationale */
9645 dowait(DOWAIT_NONBLOCK, NULL);
9646 if (evalfun(cmdentry.u.func, argc, argv, flags))
9649 status = exitstatus;
9654 if (cmd->ncmd.redirect)
9655 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9657 /* dsl: I think this is intended to be used to support
9658 * '_' in 'vi' command mode during line editing...
9659 * However I implemented that within libedit itself.
9661 setvar0("_", lastarg);
9663 popstackmark(&smark);
9669 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9671 char *volatile savecmdname;
9672 struct jmploc *volatile savehandler;
9673 struct jmploc jmploc;
9677 savecmdname = commandname;
9678 savehandler = exception_handler;
9679 i = setjmp(jmploc.loc);
9682 exception_handler = &jmploc;
9683 commandname = argv[0];
9685 optptr = NULL; /* initialize nextopt */
9687 status = evalcmd(argc, argv, flags);
9689 status = (*cmd->builtin)(argc, argv);
9690 flush_stdout_stderr();
9691 status |= ferror(stdout);
9692 exitstatus = status;
9695 commandname = savecmdname;
9696 exception_handler = savehandler;
9702 goodname(const char *p)
9704 return endofname(p)[0] == '\0';
9709 * Search for a command. This is called before we fork so that the
9710 * location of the command will be available in the parent as well as
9711 * the child. The check for "goodname" is an overly conservative
9712 * check that the name will not be subject to expansion.
9715 prehash(union node *n)
9717 struct cmdentry entry;
9719 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9720 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9724 /* ============ Builtin commands
9726 * Builtin commands whose functions are closely tied to evaluation
9727 * are implemented here.
9731 * Handle break and continue commands. Break, continue, and return are
9732 * all handled by setting the evalskip flag. The evaluation routines
9733 * above all check this flag, and if it is set they start skipping
9734 * commands rather than executing them. The variable skipcount is
9735 * the number of loops to break/continue, or the number of function
9736 * levels to return. (The latter is always 1.) It should probably
9737 * be an error to break out of more loops than exist, but it isn't
9738 * in the standard shell so we don't make it one here.
9740 static int FAST_FUNC
9741 breakcmd(int argc UNUSED_PARAM, char **argv)
9743 int n = argv[1] ? number(argv[1]) : 1;
9746 ash_msg_and_raise_error(msg_illnum, argv[1]);
9750 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9758 * This implements the input routines used by the parser.
9762 INPUT_PUSH_FILE = 1,
9763 INPUT_NOFILE_OK = 2,
9766 static smallint checkkwd;
9767 /* values of checkkwd variable */
9768 #define CHKALIAS 0x1
9773 * Push a string back onto the input at this current parsefile level.
9774 * We handle aliases this way.
9776 #if !ENABLE_ASH_ALIAS
9777 #define pushstring(s, ap) pushstring(s)
9780 pushstring(char *s, struct alias *ap)
9787 if (g_parsefile->strpush) {
9788 sp = ckzalloc(sizeof(*sp));
9789 sp->prev = g_parsefile->strpush;
9791 sp = &(g_parsefile->basestrpush);
9793 g_parsefile->strpush = sp;
9794 sp->prev_string = g_parsefile->next_to_pgetc;
9795 sp->prev_left_in_line = g_parsefile->left_in_line;
9796 sp->unget = g_parsefile->unget;
9797 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9798 #if ENABLE_ASH_ALIAS
9801 ap->flag |= ALIASINUSE;
9805 g_parsefile->next_to_pgetc = s;
9806 g_parsefile->left_in_line = len;
9807 g_parsefile->unget = 0;
9814 struct strpush *sp = g_parsefile->strpush;
9817 #if ENABLE_ASH_ALIAS
9819 if (g_parsefile->next_to_pgetc[-1] == ' '
9820 || g_parsefile->next_to_pgetc[-1] == '\t'
9822 checkkwd |= CHKALIAS;
9824 if (sp->string != sp->ap->val) {
9827 sp->ap->flag &= ~ALIASINUSE;
9828 if (sp->ap->flag & ALIASDEAD) {
9829 unalias(sp->ap->name);
9833 g_parsefile->next_to_pgetc = sp->prev_string;
9834 g_parsefile->left_in_line = sp->prev_left_in_line;
9835 g_parsefile->unget = sp->unget;
9836 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9837 g_parsefile->strpush = sp->prev;
9838 if (sp != &(g_parsefile->basestrpush))
9847 char *buf = g_parsefile->buf;
9849 g_parsefile->next_to_pgetc = buf;
9850 #if ENABLE_FEATURE_EDITING
9852 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9853 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9856 # if ENABLE_ASH_IDLE_TIMEOUT
9858 const char *tmout_var = lookupvar("TMOUT");
9860 timeout = atoi(tmout_var) * 1000;
9866 # if ENABLE_FEATURE_TAB_COMPLETION
9867 line_input_state->path_lookup = pathval();
9869 reinit_unicode_for_ash();
9870 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9872 /* ^C pressed, "convert" to SIGINT */
9873 write(STDOUT_FILENO, "^C", 2);
9880 exitstatus = 128 + SIGINT;
9886 /* Ctrl+D pressed */
9889 # if ENABLE_ASH_IDLE_TIMEOUT
9890 else if (errno == EAGAIN && timeout > 0) {
9891 puts("\007timed out waiting for input: auto-logout");
9898 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9901 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9903 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9904 int flags = fcntl(0, F_GETFL);
9905 if (flags >= 0 && (flags & O_NONBLOCK)) {
9906 flags &= ~O_NONBLOCK;
9907 if (fcntl(0, F_SETFL, flags) >= 0) {
9908 out2str("sh: turning off NDELAY mode\n");
9919 * Refill the input buffer and return the next input character:
9921 * 1) If a string was pushed back on the input, pop it;
9922 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9923 * or we are reading from a string so we can't refill the buffer,
9925 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9926 * 4) Process input up to the next newline, deleting nul characters.
9928 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9929 #define pgetc_debug(...) ((void)0)
9930 static int pgetc(void);
9937 if (g_parsefile->strpush) {
9938 #if ENABLE_ASH_ALIAS
9939 if (g_parsefile->left_in_line == -1
9940 && g_parsefile->strpush->ap
9941 && g_parsefile->next_to_pgetc[-1] != ' '
9942 && g_parsefile->next_to_pgetc[-1] != '\t'
9944 pgetc_debug("preadbuffer PEOA");
9951 /* on both branches above g_parsefile->left_in_line < 0.
9952 * "pgetc" needs refilling.
9955 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9956 * pungetc() may increment it a few times.
9957 * Assuming it won't increment it to less than -90.
9959 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9960 pgetc_debug("preadbuffer PEOF1");
9961 /* even in failure keep left_in_line and next_to_pgetc
9962 * in lock step, for correct multi-layer pungetc.
9963 * left_in_line was decremented before preadbuffer(),
9964 * must inc next_to_pgetc: */
9965 g_parsefile->next_to_pgetc++;
9969 more = g_parsefile->left_in_buffer;
9971 flush_stdout_stderr();
9975 /* don't try reading again */
9976 g_parsefile->left_in_line = -99;
9977 pgetc_debug("preadbuffer PEOF2");
9978 g_parsefile->next_to_pgetc++;
9983 /* Find out where's the end of line.
9984 * Set g_parsefile->left_in_line
9985 * and g_parsefile->left_in_buffer acordingly.
9986 * NUL chars are deleted.
9988 q = g_parsefile->next_to_pgetc;
9996 memmove(q, q + 1, more);
10000 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10006 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10007 if (g_parsefile->left_in_line < 0)
10012 g_parsefile->left_in_buffer = more;
10017 out2str(g_parsefile->next_to_pgetc);
10021 pgetc_debug("preadbuffer at %d:%p'%s'",
10022 g_parsefile->left_in_line,
10023 g_parsefile->next_to_pgetc,
10024 g_parsefile->next_to_pgetc);
10025 return (unsigned char)*g_parsefile->next_to_pgetc++;
10031 g_parsefile->linno++;
10032 setprompt_if(doprompt, 2);
10037 g_parsefile->linno++;
10038 needprompt = doprompt;
10046 pgetc_debug("pgetc at %d:%p'%s'",
10047 g_parsefile->left_in_line,
10048 g_parsefile->next_to_pgetc,
10049 g_parsefile->next_to_pgetc);
10050 if (g_parsefile->unget)
10051 return g_parsefile->lastc[--g_parsefile->unget];
10053 if (--g_parsefile->left_in_line >= 0)
10054 c = (signed char)*g_parsefile->next_to_pgetc++;
10058 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10059 g_parsefile->lastc[0] = c;
10064 #if ENABLE_ASH_ALIAS
10066 pgetc_without_PEOA(void)
10070 pgetc_debug("pgetc at %d:%p'%s'",
10071 g_parsefile->left_in_line,
10072 g_parsefile->next_to_pgetc,
10073 g_parsefile->next_to_pgetc);
10075 } while (c == PEOA);
10079 # define pgetc_without_PEOA() pgetc()
10083 * Read a line from the script.
10086 pfgets(char *line, int len)
10092 while (--nleft > 0) {
10093 c = pgetc_without_PEOA();
10108 * Undo a call to pgetc. Only two characters may be pushed back.
10109 * PEOF may be pushed back.
10114 g_parsefile->unget++;
10117 /* This one eats backslash+newline */
10123 while ((c = pgetc()) == '\\') {
10124 if (pgetc() != '\n') {
10136 * To handle the "." command, a stack of input files is used. Pushfile
10137 * adds a new entry to the stack and popfile restores the previous level.
10142 struct parsefile *pf;
10144 pf = ckzalloc(sizeof(*pf));
10145 pf->prev = g_parsefile;
10147 /*pf->strpush = NULL; - ckzalloc did it */
10148 /*pf->basestrpush.prev = NULL;*/
10156 struct parsefile *pf = g_parsefile;
10162 if (pf->pf_fd >= 0)
10165 while (pf->strpush)
10167 g_parsefile = pf->prev;
10173 * Return to top level.
10178 while (g_parsefile != &basepf)
10183 * Close the file(s) that the shell is reading commands from. Called
10184 * after a fork is done.
10190 if (g_parsefile->pf_fd > 0) {
10191 close(g_parsefile->pf_fd);
10192 g_parsefile->pf_fd = 0;
10197 * Like setinputfile, but takes an open file descriptor. Call this with
10201 setinputfd(int fd, int push)
10205 g_parsefile->buf = NULL;
10207 g_parsefile->pf_fd = fd;
10208 if (g_parsefile->buf == NULL)
10209 g_parsefile->buf = ckmalloc(IBUFSIZ);
10210 g_parsefile->left_in_buffer = 0;
10211 g_parsefile->left_in_line = 0;
10212 g_parsefile->linno = 1;
10216 * Set the input to take input from a file. If push is set, push the
10217 * old input onto the stack first.
10220 setinputfile(const char *fname, int flags)
10225 fd = open(fname, O_RDONLY);
10227 if (flags & INPUT_NOFILE_OK)
10230 ash_msg_and_raise_error("can't open '%s'", fname);
10235 close_on_exec_on(fd);
10236 setinputfd(fd, flags & INPUT_PUSH_FILE);
10243 * Like setinputfile, but takes input from a string.
10246 setinputstring(char *string)
10250 g_parsefile->next_to_pgetc = string;
10251 g_parsefile->left_in_line = strlen(string);
10252 g_parsefile->buf = NULL;
10253 g_parsefile->linno = 1;
10259 * Routines to check for mail.
10262 #if ENABLE_ASH_MAIL
10264 /* Hash of mtimes of mailboxes */
10265 static unsigned mailtime_hash;
10266 /* Set if MAIL or MAILPATH is changed. */
10267 static smallint mail_var_path_changed;
10270 * Print appropriate message(s) if mail has arrived.
10271 * If mail_var_path_changed is set,
10272 * then the value of MAIL has mail_var_path_changed,
10273 * so we just update the values.
10282 struct stackmark smark;
10285 setstackmark(&smark);
10286 mpath = mpathset() ? mpathval() : mailval();
10289 p = path_advance(&mpath, nullstr);
10294 for (q = p; *q; q++)
10300 q[-1] = '\0'; /* delete trailing '/' */
10301 if (stat(p, &statb) < 0) {
10304 /* Very simplistic "hash": just a sum of all mtimes */
10305 new_hash += (unsigned)statb.st_mtime;
10307 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10308 if (mailtime_hash != 0)
10309 out2str("you have mail\n");
10310 mailtime_hash = new_hash;
10312 mail_var_path_changed = 0;
10313 popstackmark(&smark);
10316 static void FAST_FUNC
10317 changemail(const char *val UNUSED_PARAM)
10319 mail_var_path_changed = 1;
10322 #endif /* ASH_MAIL */
10325 /* ============ ??? */
10328 * Set the shell parameters.
10331 setparam(char **argv)
10337 for (nparam = 0; argv[nparam]; nparam++)
10339 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10341 *ap++ = ckstrdup(*argv++);
10344 freeparam(&shellparam);
10345 shellparam.malloced = 1;
10346 shellparam.nparam = nparam;
10347 shellparam.p = newparam;
10348 #if ENABLE_ASH_GETOPTS
10349 shellparam.optind = 1;
10350 shellparam.optoff = -1;
10355 * Process shell options. The global variable argptr contains a pointer
10356 * to the argument list; we advance it past the options.
10358 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10359 * For a non-interactive shell, an error condition encountered
10360 * by a special built-in ... shall cause the shell to write a diagnostic message
10361 * to standard error and exit as shown in the following table:
10362 * Error Special Built-In
10364 * Utility syntax error (option or operand error) Shall exit
10366 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10367 * we see that bash does not do that (set "finishes" with error code 1 instead,
10368 * and shell continues), and people rely on this behavior!
10370 * set -o barfoo 2>/dev/null
10373 * Oh well. Let's mimic that.
10376 plus_minus_o(char *name, int val)
10381 for (i = 0; i < NOPTS; i++) {
10382 if (strcmp(name, optnames(i)) == 0) {
10387 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10390 for (i = 0; i < NOPTS; i++) {
10392 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10394 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10400 setoption(int flag, int val)
10404 for (i = 0; i < NOPTS; i++) {
10405 if (optletters(i) == flag) {
10410 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10414 options(int cmdline)
10422 while ((p = *argptr) != NULL) {
10424 if (c != '-' && c != '+')
10427 val = 0; /* val = 0 if c == '+' */
10430 if (p[0] == '\0' || LONE_DASH(p)) {
10432 /* "-" means turn off -x and -v */
10435 /* "--" means reset params */
10436 else if (*argptr == NULL)
10439 break; /* "-" or "--" terminates options */
10442 /* first char was + or - */
10443 while ((c = *p++) != '\0') {
10444 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10445 if (c == 'c' && cmdline) {
10446 minusc = p; /* command is after shell args */
10447 } else if (c == 'o') {
10448 if (plus_minus_o(*argptr, val)) {
10449 /* it already printed err message */
10450 return 1; /* error */
10454 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10456 /* bash does not accept +-login, we also won't */
10457 } else if (cmdline && val && (c == '-')) { /* long options */
10458 if (strcmp(p, "login") == 0)
10470 * The shift builtin command.
10472 static int FAST_FUNC
10473 shiftcmd(int argc UNUSED_PARAM, char **argv)
10480 n = number(argv[1]);
10481 if (n > shellparam.nparam)
10482 n = 0; /* bash compat, was = shellparam.nparam; */
10484 shellparam.nparam -= n;
10485 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10486 if (shellparam.malloced)
10489 ap2 = shellparam.p;
10490 while ((*ap2++ = *ap1++) != NULL)
10492 #if ENABLE_ASH_GETOPTS
10493 shellparam.optind = 1;
10494 shellparam.optoff = -1;
10501 * POSIX requires that 'set' (but not export or readonly) output the
10502 * variables in lexicographic order - by the locale's collating order (sigh).
10503 * Maybe we could keep them in an ordered balanced binary tree
10504 * instead of hashed lists.
10505 * For now just roll 'em through qsort for printing...
10508 showvars(const char *sep_prefix, int on, int off)
10511 char **ep, **epend;
10513 ep = listvars(on, off, &epend);
10514 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10516 sep = *sep_prefix ? " " : sep_prefix;
10518 for (; ep < epend; ep++) {
10522 p = strchrnul(*ep, '=');
10525 q = single_quote(++p);
10526 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10532 * The set command builtin.
10534 static int FAST_FUNC
10535 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10540 return showvars(nullstr, 0, VUNSET);
10543 retval = options(/*cmdline:*/ 0);
10544 if (retval == 0) { /* if no parse error... */
10546 if (*argptr != NULL) {
10554 #if ENABLE_ASH_RANDOM_SUPPORT
10555 static void FAST_FUNC
10556 change_random(const char *value)
10560 if (value == NULL) {
10561 /* "get", generate */
10562 t = next_random(&random_gen);
10563 /* set without recursion */
10564 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10565 vrandom.flags &= ~VNOFUNC;
10568 t = strtoul(value, NULL, 10);
10569 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10574 #if ENABLE_ASH_GETOPTS
10576 getopts(char *optstr, char *optvar, char **optfirst)
10583 int ind = shellparam.optind;
10584 int off = shellparam.optoff;
10588 shellparam.optind = -1;
10589 optnext = optfirst + ind - 1;
10591 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10594 p = optnext[-1] + off;
10595 if (p == NULL || *p == '\0') {
10596 /* Current word is done, advance */
10598 if (p == NULL || *p != '-' || *++p == '\0') {
10605 if (LONE_DASH(p)) /* check for "--" */
10610 for (q = optstr; *q != c;) {
10612 if (optstr[0] == ':') {
10614 /*sbuf[1] = '\0'; - already is */
10615 setvar0("OPTARG", sbuf);
10617 fprintf(stderr, "Illegal option -%c\n", c);
10618 unsetvar("OPTARG");
10628 if (*p == '\0' && (p = *optnext) == NULL) {
10629 if (optstr[0] == ':') {
10631 /*sbuf[1] = '\0'; - already is */
10632 setvar0("OPTARG", sbuf);
10635 fprintf(stderr, "No arg for -%c option\n", c);
10636 unsetvar("OPTARG");
10644 setvar0("OPTARG", p);
10647 setvar0("OPTARG", nullstr);
10649 ind = optnext - optfirst + 1;
10650 setvar("OPTIND", itoa(ind), VNOFUNC);
10652 /*sbuf[1] = '\0'; - already is */
10653 setvar0(optvar, sbuf);
10655 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10656 shellparam.optind = ind;
10662 * The getopts builtin. Shellparam.optnext points to the next argument
10663 * to be processed. Shellparam.optptr points to the next character to
10664 * be processed in the current argument. If shellparam.optnext is NULL,
10665 * then it's the first time getopts has been called.
10667 static int FAST_FUNC
10668 getoptscmd(int argc, char **argv)
10673 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10675 optbase = shellparam.p;
10676 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10677 shellparam.optind = 1;
10678 shellparam.optoff = -1;
10681 optbase = &argv[3];
10682 if ((unsigned)shellparam.optind > argc - 2) {
10683 shellparam.optind = 1;
10684 shellparam.optoff = -1;
10688 return getopts(argv[1], argv[2], optbase);
10690 #endif /* ASH_GETOPTS */
10693 /* ============ Shell parser */
10696 struct heredoc *next; /* next here document in list */
10697 union node *here; /* redirection node */
10698 char *eofmark; /* string indicating end of input */
10699 smallint striptabs; /* if set, strip leading tabs */
10702 static smallint tokpushback; /* last token pushed back */
10703 static smallint quoteflag; /* set if (part of) last token was quoted */
10704 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10705 static struct heredoc *heredoclist; /* list of here documents to read */
10706 static char *wordtext; /* text of last word returned by readtoken */
10707 static struct nodelist *backquotelist;
10708 static union node *redirnode;
10709 static struct heredoc *heredoc;
10711 static const char *
10712 tokname(char *buf, int tok)
10715 return tokname_array[tok];
10716 sprintf(buf, "\"%s\"", tokname_array[tok]);
10720 /* raise_error_unexpected_syntax:
10721 * Called when an unexpected token is read during the parse. The argument
10722 * is the token that is expected, or -1 if more than one type of token can
10723 * occur at this point.
10725 static void raise_error_unexpected_syntax(int) NORETURN;
10727 raise_error_unexpected_syntax(int token)
10733 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10735 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10736 raise_error_syntax(msg);
10740 #define EOFMARKLEN 79
10742 /* parsing is heavily cross-recursive, need these forward decls */
10743 static union node *andor(void);
10744 static union node *pipeline(void);
10745 static union node *parse_command(void);
10746 static void parseheredoc(void);
10747 static int peektoken(void);
10748 static int readtoken(void);
10750 static union node *
10753 union node *n1, *n2, *n3;
10758 switch (peektoken()) {
10766 if (!n1 && (nlflag & 1))
10772 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10773 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10779 if (tok == TBACKGND) {
10780 if (n2->type == NPIPE) {
10781 n2->npipe.pipe_backgnd = 1;
10783 if (n2->type != NREDIR) {
10784 n3 = stzalloc(sizeof(struct nredir));
10786 /*n3->nredir.redirect = NULL; - stzalloc did it */
10789 n2->type = NBACKGND;
10795 n3 = stzalloc(sizeof(struct nbinary));
10797 n3->nbinary.ch1 = n1;
10798 n3->nbinary.ch2 = n2;
10811 raise_error_unexpected_syntax(-1);
10818 static union node *
10821 union node *n1, *n2, *n3;
10829 } else if (t == TOR) {
10835 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10837 n3 = stzalloc(sizeof(struct nbinary));
10839 n3->nbinary.ch1 = n1;
10840 n3->nbinary.ch2 = n2;
10845 static union node *
10848 union node *n1, *n2, *pipenode;
10849 struct nodelist *lp, *prev;
10853 TRACE(("pipeline: entered\n"));
10854 if (readtoken() == TNOT) {
10856 checkkwd = CHKKWD | CHKALIAS;
10859 n1 = parse_command();
10860 if (readtoken() == TPIPE) {
10861 pipenode = stzalloc(sizeof(struct npipe));
10862 pipenode->type = NPIPE;
10863 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10864 lp = stzalloc(sizeof(struct nodelist));
10865 pipenode->npipe.cmdlist = lp;
10869 lp = stzalloc(sizeof(struct nodelist));
10870 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10871 lp->n = parse_command();
10873 } while (readtoken() == TPIPE);
10879 n2 = stzalloc(sizeof(struct nnot));
10887 static union node *
10892 n = stzalloc(sizeof(struct narg));
10894 /*n->narg.next = NULL; - stzalloc did it */
10895 n->narg.text = wordtext;
10896 n->narg.backquote = backquotelist;
10901 fixredir(union node *n, const char *text, int err)
10905 TRACE(("Fix redir %s %d\n", text, err));
10907 n->ndup.vname = NULL;
10909 fd = bb_strtou(text, NULL, 10);
10910 if (!errno && fd >= 0)
10911 n->ndup.dupfd = fd;
10912 else if (LONE_DASH(text))
10913 n->ndup.dupfd = -1;
10916 raise_error_syntax("bad fd number");
10917 n->ndup.vname = makename();
10922 * Returns true if the text contains nothing to expand (no dollar signs
10926 noexpand(const char *text)
10930 while ((c = *text++) != '\0') {
10931 if (c == CTLQUOTEMARK)
10935 else if (SIT(c, BASESYNTAX) == CCTL)
10944 union node *n = redirnode;
10946 if (readtoken() != TWORD)
10947 raise_error_unexpected_syntax(-1);
10948 if (n->type == NHERE) {
10949 struct heredoc *here = heredoc;
10953 if (quoteflag == 0)
10955 TRACE(("Here document %d\n", n->type));
10956 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10957 raise_error_syntax("illegal eof marker for << redirection");
10958 rmescapes(wordtext, 0);
10959 here->eofmark = wordtext;
10961 if (heredoclist == NULL)
10962 heredoclist = here;
10964 for (p = heredoclist; p->next; p = p->next)
10968 } else if (n->type == NTOFD || n->type == NFROMFD) {
10969 fixredir(n, wordtext, 0);
10971 n->nfile.fname = makename();
10975 static union node *
10978 union node *args, **app;
10979 union node *n = NULL;
10980 union node *vars, **vpp;
10981 union node **rpp, *redir;
10983 #if ENABLE_ASH_BASH_COMPAT
10984 smallint double_brackets_flag = 0;
10985 smallint function_flag = 0;
10995 savecheckkwd = CHKALIAS;
10998 checkkwd = savecheckkwd;
11001 #if ENABLE_ASH_BASH_COMPAT
11003 if (peektoken() != TWORD)
11004 raise_error_unexpected_syntax(TWORD);
11007 case TAND: /* "&&" */
11008 case TOR: /* "||" */
11009 if (!double_brackets_flag) {
11013 wordtext = (char *) (t == TAND ? "-a" : "-o");
11016 n = stzalloc(sizeof(struct narg));
11018 /*n->narg.next = NULL; - stzalloc did it */
11019 n->narg.text = wordtext;
11020 #if ENABLE_ASH_BASH_COMPAT
11021 if (strcmp("[[", wordtext) == 0)
11022 double_brackets_flag = 1;
11023 else if (strcmp("]]", wordtext) == 0)
11024 double_brackets_flag = 0;
11026 n->narg.backquote = backquotelist;
11027 if (savecheckkwd && isassignment(wordtext)) {
11029 vpp = &n->narg.next;
11032 app = &n->narg.next;
11035 #if ENABLE_ASH_BASH_COMPAT
11036 if (function_flag) {
11037 checkkwd = CHKNL | CHKKWD;
11038 switch (peektoken()) {
11050 if (strcmp("[[", wordtext) == 0)
11054 raise_error_unexpected_syntax(-1);
11060 *rpp = n = redirnode;
11061 rpp = &n->nfile.next;
11062 parsefname(); /* read name of redirection file */
11065 IF_ASH_BASH_COMPAT(do_func:)
11066 if (args && app == &args->narg.next
11069 struct builtincmd *bcmd;
11072 /* We have a function */
11073 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11074 raise_error_unexpected_syntax(TRP);
11075 name = n->narg.text;
11076 if (!goodname(name)
11077 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11079 raise_error_syntax("bad function name");
11082 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11083 n->narg.next = parse_command();
11086 IF_ASH_BASH_COMPAT(function_flag = 0;)
11097 n = stzalloc(sizeof(struct ncmd));
11099 n->ncmd.args = args;
11100 n->ncmd.assign = vars;
11101 n->ncmd.redirect = redir;
11105 static union node *
11106 parse_command(void)
11108 union node *n1, *n2;
11109 union node *ap, **app;
11110 union node *cp, **cpp;
11111 union node *redir, **rpp;
11118 switch (readtoken()) {
11120 raise_error_unexpected_syntax(-1);
11123 n1 = stzalloc(sizeof(struct nif));
11125 n1->nif.test = list(0);
11126 if (readtoken() != TTHEN)
11127 raise_error_unexpected_syntax(TTHEN);
11128 n1->nif.ifpart = list(0);
11130 while (readtoken() == TELIF) {
11131 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11132 n2 = n2->nif.elsepart;
11134 n2->nif.test = list(0);
11135 if (readtoken() != TTHEN)
11136 raise_error_unexpected_syntax(TTHEN);
11137 n2->nif.ifpart = list(0);
11139 if (lasttoken == TELSE)
11140 n2->nif.elsepart = list(0);
11142 n2->nif.elsepart = NULL;
11150 n1 = stzalloc(sizeof(struct nbinary));
11151 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11152 n1->nbinary.ch1 = list(0);
11155 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11156 got == TWORD ? wordtext : ""));
11157 raise_error_unexpected_syntax(TDO);
11159 n1->nbinary.ch2 = list(0);
11164 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11165 raise_error_syntax("bad for loop variable");
11166 n1 = stzalloc(sizeof(struct nfor));
11168 n1->nfor.var = wordtext;
11169 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11170 if (readtoken() == TIN) {
11172 while (readtoken() == TWORD) {
11173 n2 = stzalloc(sizeof(struct narg));
11175 /*n2->narg.next = NULL; - stzalloc did it */
11176 n2->narg.text = wordtext;
11177 n2->narg.backquote = backquotelist;
11179 app = &n2->narg.next;
11182 n1->nfor.args = ap;
11183 if (lasttoken != TNL && lasttoken != TSEMI)
11184 raise_error_unexpected_syntax(-1);
11186 n2 = stzalloc(sizeof(struct narg));
11188 /*n2->narg.next = NULL; - stzalloc did it */
11189 n2->narg.text = (char *)dolatstr;
11190 /*n2->narg.backquote = NULL;*/
11191 n1->nfor.args = n2;
11193 * Newline or semicolon here is optional (but note
11194 * that the original Bourne shell only allowed NL).
11196 if (lasttoken != TSEMI)
11199 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11200 if (readtoken() != TDO)
11201 raise_error_unexpected_syntax(TDO);
11202 n1->nfor.body = list(0);
11206 n1 = stzalloc(sizeof(struct ncase));
11208 if (readtoken() != TWORD)
11209 raise_error_unexpected_syntax(TWORD);
11210 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11212 /*n2->narg.next = NULL; - stzalloc did it */
11213 n2->narg.text = wordtext;
11214 n2->narg.backquote = backquotelist;
11215 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11216 if (readtoken() != TIN)
11217 raise_error_unexpected_syntax(TIN);
11218 cpp = &n1->ncase.cases;
11220 checkkwd = CHKNL | CHKKWD;
11222 while (t != TESAC) {
11223 if (lasttoken == TLP)
11225 *cpp = cp = stzalloc(sizeof(struct nclist));
11227 app = &cp->nclist.pattern;
11229 *app = ap = stzalloc(sizeof(struct narg));
11231 /*ap->narg.next = NULL; - stzalloc did it */
11232 ap->narg.text = wordtext;
11233 ap->narg.backquote = backquotelist;
11234 if (readtoken() != TPIPE)
11236 app = &ap->narg.next;
11239 //ap->narg.next = NULL;
11240 if (lasttoken != TRP)
11241 raise_error_unexpected_syntax(TRP);
11242 cp->nclist.body = list(2);
11244 cpp = &cp->nclist.next;
11246 checkkwd = CHKNL | CHKKWD;
11250 raise_error_unexpected_syntax(TENDCASE);
11257 n1 = stzalloc(sizeof(struct nredir));
11258 n1->type = NSUBSHELL;
11259 n1->nredir.n = list(0);
11260 /*n1->nredir.redirect = NULL; - stzalloc did it */
11267 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11271 return simplecmd();
11274 if (readtoken() != t)
11275 raise_error_unexpected_syntax(t);
11278 /* Now check for redirection which may follow command */
11279 checkkwd = CHKKWD | CHKALIAS;
11281 while (readtoken() == TREDIR) {
11282 *rpp = n2 = redirnode;
11283 rpp = &n2->nfile.next;
11289 if (n1->type != NSUBSHELL) {
11290 n2 = stzalloc(sizeof(struct nredir));
11295 n1->nredir.redirect = redir;
11300 #if ENABLE_ASH_BASH_COMPAT
11302 decode_dollar_squote(void)
11304 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11310 p = strchr(C_escapes, c);
11315 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11319 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11321 } else if (c == 'x') { /* \xHH */
11325 } while (isxdigit(c) && --cnt);
11327 if (cnt == 3) { /* \x but next char is "bad" */
11331 } else { /* simple seq like \\ or \t */
11336 c = bb_process_escape_sequence((void*)&p);
11337 } else { /* unrecognized "\z": print both chars unless ' or " */
11338 if (c != '\'' && c != '"') {
11340 c |= 0x100; /* "please encode \, then me" */
11348 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11349 * is not NULL, read a here document. In the latter case, eofmark is the
11350 * word which marks the end of the document and striptabs is true if
11351 * leading tabs should be stripped from the document. The argument c
11352 * is the first character of the input token or document.
11354 * Because C does not have internal subroutines, I have simulated them
11355 * using goto's to implement the subroutine linkage. The following macros
11356 * will run code that appears at the end of readtoken1.
11358 #define CHECKEND() {goto checkend; checkend_return:;}
11359 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11360 #define PARSESUB() {goto parsesub; parsesub_return:;}
11361 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11362 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11363 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11365 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11367 /* NB: syntax parameter fits into smallint */
11368 /* c parameter is an unsigned char or PEOF or PEOA */
11371 char line[EOFMARKLEN + 1];
11372 struct nodelist *bqlist;
11376 smallint prevsyntax; /* syntax before arithmetic */
11377 #if ENABLE_ASH_EXPAND_PRMT
11378 smallint pssyntax; /* we are expanding a prompt string */
11380 int varnest; /* levels of variables expansion */
11381 int arinest; /* levels of arithmetic expansion */
11382 int parenlevel; /* levels of parens in arithmetic */
11383 int dqvarnest; /* levels of variables expansion within double quotes */
11385 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11387 startlinno = g_parsefile->linno;
11391 #if ENABLE_ASH_EXPAND_PRMT
11392 pssyntax = (syntax == PSSYNTAX);
11396 dblquote = (syntax == DQSYNTAX);
11402 STARTSTACKSTR(out);
11404 /* For each line, until end of word */
11405 CHECKEND(); /* set c to PEOF if at end of here document */
11406 for (;;) { /* until end of line or end of word */
11407 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11408 switch (SIT(c, syntax)) {
11409 case CNL: /* '\n' */
11410 if (syntax == BASESYNTAX)
11411 goto endword; /* exit outer loop */
11415 goto loop; /* continue outer loop */
11420 #if ENABLE_ASH_BASH_COMPAT
11421 if (c == '\\' && bash_dollar_squote) {
11422 c = decode_dollar_squote();
11424 /* skip $'\000', $'\x00' (like bash) */
11428 /* Unknown escape. Encode as '\z' */
11429 c = (unsigned char)c;
11430 if (eofmark == NULL || dblquote)
11431 USTPUTC(CTLESC, out);
11432 USTPUTC('\\', out);
11436 if (eofmark == NULL || dblquote)
11437 USTPUTC(CTLESC, out);
11440 case CBACK: /* backslash */
11441 c = pgetc_without_PEOA();
11443 USTPUTC(CTLESC, out);
11444 USTPUTC('\\', out);
11446 } else if (c == '\n') {
11449 #if ENABLE_ASH_EXPAND_PRMT
11450 if (c == '$' && pssyntax) {
11451 USTPUTC(CTLESC, out);
11452 USTPUTC('\\', out);
11455 /* Backslash is retained if we are in "str" and next char isn't special */
11460 && (c != '"' || eofmark != NULL)
11462 USTPUTC('\\', out);
11464 USTPUTC(CTLESC, out);
11472 if (eofmark == NULL) {
11473 USTPUTC(CTLQUOTEMARK, out);
11481 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11482 if (eofmark != NULL && varnest == 0) {
11485 if (dqvarnest == 0) {
11486 syntax = BASESYNTAX;
11493 case CVAR: /* '$' */
11494 PARSESUB(); /* parse substitution */
11496 case CENDVAR: /* '}' */
11499 if (dqvarnest > 0) {
11506 #if ENABLE_SH_MATH_SUPPORT
11507 case CLP: /* '(' in arithmetic */
11511 case CRP: /* ')' in arithmetic */
11512 if (parenlevel > 0) {
11515 if (pgetc_eatbnl() == ')') {
11517 if (--arinest == 0) {
11518 syntax = prevsyntax;
11522 * unbalanced parens
11523 * (don't 2nd guess - no error)
11531 case CBQUOTE: /* '`' */
11535 goto endword; /* exit outer loop */
11539 if (varnest == 0) {
11540 #if ENABLE_ASH_BASH_COMPAT
11542 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11543 if (pgetc() == '>')
11544 c = 0x100 + '>'; /* flag &> */
11548 goto endword; /* exit outer loop */
11550 IF_ASH_ALIAS(if (c != PEOA))
11557 #if ENABLE_SH_MATH_SUPPORT
11558 if (syntax == ARISYNTAX)
11559 raise_error_syntax("missing '))'");
11561 if (syntax != BASESYNTAX && eofmark == NULL)
11562 raise_error_syntax("unterminated quoted string");
11563 if (varnest != 0) {
11564 startlinno = g_parsefile->linno;
11566 raise_error_syntax("missing '}'");
11568 USTPUTC('\0', out);
11569 len = out - (char *)stackblock();
11570 out = stackblock();
11571 if (eofmark == NULL) {
11572 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11575 if (isdigit_str9(out)) {
11576 PARSEREDIR(); /* passed as params: out, c */
11577 lasttoken = TREDIR;
11580 /* else: non-number X seen, interpret it
11581 * as "NNNX>file" = "NNNX >file" */
11585 quoteflag = quotef;
11586 backquotelist = bqlist;
11587 grabstackblock(len);
11591 /* end of readtoken routine */
11594 * Check to see whether we are at the end of the here document. When this
11595 * is called, c is set to the first character of the next input line. If
11596 * we are at the end of the here document, this routine sets the c to PEOF.
11600 #if ENABLE_ASH_ALIAS
11602 c = pgetc_without_PEOA();
11605 while (c == '\t') {
11606 c = pgetc_without_PEOA();
11609 if (c == *eofmark) {
11610 if (pfgets(line, sizeof(line)) != NULL) {
11615 for (q = eofmark + 1;; p++, q++) {
11619 if (!*q || cc != *q)
11626 pushstring(line, NULL);
11631 goto checkend_return;
11635 * Parse a redirection operator. The variable "out" points to a string
11636 * specifying the fd to be redirected. The variable "c" contains the
11637 * first character of the redirection operator.
11640 /* out is already checked to be a valid number or "" */
11641 int fd = (*out == '\0' ? -1 : atoi(out));
11644 np = stzalloc(sizeof(struct nfile));
11649 np->type = NAPPEND;
11651 np->type = NCLOBBER;
11654 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11660 #if ENABLE_ASH_BASH_COMPAT
11661 else if (c == 0x100 + '>') { /* this flags &> redirection */
11663 pgetc(); /* this is '>', no need to check */
11667 else { /* c == '<' */
11668 /*np->nfile.fd = 0; - stzalloc did it */
11672 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11673 np = stzalloc(sizeof(struct nhere));
11674 /*np->nfile.fd = 0; - stzalloc did it */
11677 heredoc = stzalloc(sizeof(struct heredoc));
11678 heredoc->here = np;
11681 heredoc->striptabs = 1;
11683 /*heredoc->striptabs = 0; - stzalloc did it */
11689 np->type = NFROMFD;
11693 np->type = NFROMTO;
11705 goto parseredir_return;
11709 * Parse a substitution. At this point, we have read the dollar sign
11710 * and nothing else.
11713 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11714 * (assuming ascii char codes, as the original implementation did) */
11715 #define is_special(c) \
11716 (((unsigned)(c) - 33 < 32) \
11717 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11719 unsigned char subtype;
11722 c = pgetc_eatbnl();
11723 if (c > 255 /* PEOA or PEOF */
11724 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11726 #if ENABLE_ASH_BASH_COMPAT
11727 if (syntax != DQSYNTAX && c == '\'')
11728 bash_dollar_squote = 1;
11733 } else if (c == '(') {
11734 /* $(command) or $((arith)) */
11735 if (pgetc_eatbnl() == '(') {
11736 #if ENABLE_SH_MATH_SUPPORT
11739 raise_error_syntax("you disabled math support for $((arith)) syntax");
11746 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11747 USTPUTC(CTLVAR, out);
11748 typeloc = out - (char *)stackblock();
11750 subtype = VSNORMAL;
11752 c = pgetc_eatbnl();
11757 /* $[{[#]]NAME[}] */
11760 c = pgetc_eatbnl();
11761 } while (is_in_name(c));
11762 } else if (isdigit(c)) {
11763 /* $[{[#]]NUM[}] */
11766 c = pgetc_eatbnl();
11767 } while (isdigit(c));
11768 } else if (is_special(c)) {
11769 /* $[{[#]]<specialchar>[}] */
11772 c = pgetc_eatbnl();
11773 if (!subtype && cc == '#') {
11774 subtype = VSLENGTH;
11775 if (c == '_' || isalnum(c))
11778 c = pgetc_eatbnl();
11779 if (cc == '}' || c != '}') {
11790 if (c != '}' && subtype == VSLENGTH) {
11791 /* ${#VAR didn't end with } */
11795 if (subtype == 0) {
11796 static const char types[] ALIGN1 = "}-+?=";
11797 /* ${VAR...} but not $VAR or ${#VAR} */
11798 /* c == first char after VAR */
11801 c = pgetc_eatbnl();
11802 #if ENABLE_ASH_BASH_COMPAT
11803 /* This check is only needed to not misinterpret
11804 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11807 if (!strchr(types, c)) {
11808 subtype = VSSUBSTR;
11810 break; /* "goto badsub" is bigger (!) */
11816 const char *p = strchr(types, c);
11819 subtype |= p - types + VSNORMAL;
11825 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11826 c = pgetc_eatbnl();
11832 #if ENABLE_ASH_BASH_COMPAT
11834 /* ${v/[/]pattern/repl} */
11835 //TODO: encode pattern and repl separately.
11836 // Currently ${v/$var_with_slash/repl} is horribly broken
11837 subtype = VSREPLACE;
11838 c = pgetc_eatbnl();
11841 subtype++; /* VSREPLACEALL */
11849 ((unsigned char *)stackblock())[typeloc] = subtype;
11850 if (subtype != VSNORMAL) {
11857 goto parsesub_return;
11861 * Called to parse command substitutions. Newstyle is set if the command
11862 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11863 * list of commands (passed by reference), and savelen is the number of
11864 * characters on the top of the stack which must be preserved.
11867 struct nodelist **nlpp;
11871 smallint saveprompt = 0;
11874 savelen = out - (char *)stackblock();
11877 * FIXME: this can allocate very large block on stack and SEGV.
11879 * echo "..<100kbytes>..`true` $(true) `true` ..."
11880 * allocates 100kb for every command subst. With about
11881 * a hundred command substitutions stack overflows.
11882 * With larger prepended string, SEGV happens sooner.
11884 str = alloca(savelen);
11885 memcpy(str, stackblock(), savelen);
11889 /* We must read until the closing backquote, giving special
11890 * treatment to some slashes, and then push the string and
11891 * reread it as input, interpreting it normally.
11897 STARTSTACKSTR(pout);
11901 setprompt_if(needprompt, 2);
11912 * If eating a newline, avoid putting
11913 * the newline into the new character
11914 * stream (via the STPUTC after the
11919 if (pc != '\\' && pc != '`' && pc != '$'
11920 && (!dblquote || pc != '"')
11922 STPUTC('\\', pout);
11924 if (pc <= 255 /* not PEOA or PEOF */) {
11930 IF_ASH_ALIAS(case PEOA:)
11931 startlinno = g_parsefile->linno;
11932 raise_error_syntax("EOF in backquote substitution");
11944 STPUTC('\0', pout);
11945 psavelen = pout - (char *)stackblock();
11946 if (psavelen > 0) {
11947 pstr = grabstackstr(pout);
11948 setinputstring(pstr);
11953 nlpp = &(*nlpp)->next;
11954 *nlpp = stzalloc(sizeof(**nlpp));
11955 /* (*nlpp)->next = NULL; - stzalloc did it */
11958 saveprompt = doprompt;
11965 doprompt = saveprompt;
11966 else if (readtoken() != TRP)
11967 raise_error_unexpected_syntax(TRP);
11972 * Start reading from old file again, ignoring any pushed back
11973 * tokens left from the backquote parsing
11978 while (stackblocksize() <= savelen)
11980 STARTSTACKSTR(out);
11982 memcpy(out, str, savelen);
11983 STADJUST(savelen, out);
11985 USTPUTC(CTLBACKQ, out);
11987 goto parsebackq_oldreturn;
11988 goto parsebackq_newreturn;
11991 #if ENABLE_SH_MATH_SUPPORT
11993 * Parse an arithmetic expansion (indicate start of one and set state)
11996 if (++arinest == 1) {
11997 prevsyntax = syntax;
11998 syntax = ARISYNTAX;
12000 USTPUTC(CTLARI, out);
12001 goto parsearith_return;
12004 } /* end of readtoken */
12007 * Read the next input token.
12008 * If the token is a word, we set backquotelist to the list of cmds in
12009 * backquotes. We set quoteflag to true if any part of the word was
12011 * If the token is TREDIR, then we set redirnode to a structure containing
12013 * In all cases, the variable startlinno is set to the number of the line
12014 * on which the token starts.
12016 * [Change comment: here documents and internal procedures]
12017 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12018 * word parsing code into a separate routine. In this case, readtoken
12019 * doesn't need to have any internal procedures, but parseword does.
12020 * We could also make parseoperator in essence the main routine, and
12021 * have parseword (readtoken1?) handle both words and redirection.]
12023 #define NEW_xxreadtoken
12024 #ifdef NEW_xxreadtoken
12025 /* singles must be first! */
12026 static const char xxreadtoken_chars[7] ALIGN1 = {
12027 '\n', '(', ')', /* singles */
12028 '&', '|', ';', /* doubles */
12032 #define xxreadtoken_singles 3
12033 #define xxreadtoken_doubles 3
12035 static const char xxreadtoken_tokens[] ALIGN1 = {
12036 TNL, TLP, TRP, /* only single occurrence allowed */
12037 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12038 TEOF, /* corresponds to trailing nul */
12039 TAND, TOR, TENDCASE /* if double occurrence */
12051 setprompt_if(needprompt, 2);
12052 startlinno = g_parsefile->linno;
12053 for (;;) { /* until token or start of word found */
12055 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12059 while ((c = pgetc()) != '\n' && c != PEOF)
12062 } else if (c == '\\') {
12063 if (pgetc() != '\n') {
12065 break; /* return readtoken1(...) */
12071 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12077 p = strchr(xxreadtoken_chars, c);
12079 break; /* return readtoken1(...) */
12081 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12083 if (cc == c) { /* double occurrence? */
12084 p += xxreadtoken_doubles + 1;
12087 #if ENABLE_ASH_BASH_COMPAT
12088 if (c == '&' && cc == '>') /* &> */
12089 break; /* return readtoken1(...) */
12094 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12099 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12101 #else /* old xxreadtoken */
12102 #define RETURN(token) return lasttoken = token
12112 setprompt_if(needprompt, 2);
12113 startlinno = g_parsefile->linno;
12114 for (;;) { /* until token or start of word found */
12117 case ' ': case '\t':
12118 IF_ASH_ALIAS(case PEOA:)
12121 while ((c = pgetc()) != '\n' && c != PEOF)
12126 if (pgetc() == '\n') {
12138 if (pgetc() == '&')
12143 if (pgetc() == '|')
12148 if (pgetc() == ';')
12161 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12164 #endif /* old xxreadtoken */
12170 int kwd = checkkwd;
12172 smallint alreadyseen = tokpushback;
12175 #if ENABLE_ASH_ALIAS
12191 if (t != TWORD || quoteflag) {
12196 * check for keywords
12198 if (kwd & CHKKWD) {
12199 const char *const *pp;
12201 pp = findkwd(wordtext);
12203 lasttoken = t = pp - tokname_array;
12204 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12209 if (checkkwd & CHKALIAS) {
12210 #if ENABLE_ASH_ALIAS
12212 ap = lookupalias(wordtext, 1);
12215 pushstring(ap->val, ap);
12225 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12227 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12243 * Read and parse a command. Returns NODE_EOF on end of file.
12244 * (NULL is a valid parse tree indicating a blank line.)
12246 static union node *
12247 parsecmd(int interact)
12252 doprompt = interact;
12253 setprompt_if(doprompt, doprompt);
12259 * Input any here documents.
12264 struct heredoc *here;
12267 here = heredoclist;
12268 heredoclist = NULL;
12271 setprompt_if(needprompt, 2);
12272 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12273 here->eofmark, here->striptabs);
12274 n = stzalloc(sizeof(struct narg));
12275 n->narg.type = NARG;
12276 /*n->narg.next = NULL; - stzalloc did it */
12277 n->narg.text = wordtext;
12278 n->narg.backquote = backquotelist;
12279 here->here->nhere.doc = n;
12286 * called by editline -- any expansions to the prompt should be added here.
12288 #if ENABLE_ASH_EXPAND_PRMT
12289 static const char *
12290 expandstr(const char *ps)
12295 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12296 * and token processing _can_ alter it (delete NULs etc). */
12297 setinputstring((char *)ps);
12299 saveprompt = doprompt;
12301 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12302 doprompt = saveprompt;
12306 n.narg.type = NARG;
12307 n.narg.next = NULL;
12308 n.narg.text = wordtext;
12309 n.narg.backquote = backquotelist;
12311 expandarg(&n, NULL, EXP_QUOTED);
12312 return stackblock();
12317 * Execute a command or commands contained in a string.
12320 evalstring(char *s, int flags)
12322 struct jmploc *volatile savehandler;
12323 struct jmploc jmploc;
12327 struct stackmark smark;
12332 setstackmark(&smark);
12335 /* On exception inside execution loop, we must popfile().
12336 * Try interactively:
12338 * command eval "a=b" # throws "is read only" error
12339 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12340 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12342 savehandler = exception_handler;
12343 ex = setjmp(jmploc.loc);
12346 exception_handler = &jmploc;
12348 while ((n = parsecmd(0)) != NODE_EOF) {
12351 i = evaltree(n, flags);
12354 popstackmark(&smark);
12359 popstackmark(&smark);
12363 exception_handler = savehandler;
12365 longjmp(exception_handler->loc, ex);
12371 * The eval command.
12373 static int FAST_FUNC
12374 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12383 STARTSTACKSTR(concat);
12385 concat = stack_putstr(p, concat);
12389 STPUTC(' ', concat);
12391 STPUTC('\0', concat);
12392 p = grabstackstr(concat);
12394 return evalstring(p, flags & EV_TESTED);
12400 * Read and execute commands.
12401 * "Top" is nonzero for the top level command loop;
12402 * it turns on prompting if the shell is interactive.
12408 struct stackmark smark;
12413 TRACE(("cmdloop(%d) called\n", top));
12417 setstackmark(&smark);
12420 showjobs(SHOW_CHANGED|SHOW_STDERR);
12423 if (iflag && top) {
12427 n = parsecmd(inter);
12429 if (DEBUG > 2 && debug && (n != NODE_EOF))
12432 if (n == NODE_EOF) {
12433 if (!top || numeof >= 50)
12435 if (!stoppedjobs()) {
12438 out2str("\nUse \"exit\" to leave shell.\n");
12441 } else if (nflag == 0) {
12444 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12447 i = evaltree(n, 0);
12451 popstackmark(&smark);
12455 evalskip &= ~SKIPFUNC;
12463 * Take commands from a file. To be compatible we should do a path
12464 * search for the file, which is necessary to find sub-commands.
12467 find_dot_file(char *name)
12470 const char *path = pathval();
12473 /* don't try this for absolute or relative paths */
12474 if (strchr(name, '/'))
12477 /* IIRC standards do not say whether . is to be searched.
12478 * And it is even smaller this way, making it unconditional for now:
12480 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12485 while ((fullname = path_advance(&path, name)) != NULL) {
12487 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12489 * Don't bother freeing here, since it will
12490 * be freed by the caller.
12494 if (fullname != name)
12495 stunalloc(fullname);
12498 /* not found in the PATH */
12499 ash_msg_and_raise_error("%s: not found", name);
12503 static int FAST_FUNC
12504 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12506 /* "false; . empty_file; echo $?" should print 0, not 1: */
12510 struct strlist *sp;
12511 volatile struct shparam saveparam;
12513 for (sp = cmdenviron; sp; sp = sp->next)
12514 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12516 nextopt(nullstr); /* handle possible "--" */
12520 /* bash says: "bash: .: filename argument required" */
12521 return 2; /* bash compat */
12524 /* This aborts if file isn't found, which is POSIXly correct.
12525 * bash returns exitcode 1 instead.
12527 fullname = find_dot_file(argv[0]);
12529 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12531 saveparam = shellparam;
12532 shellparam.malloced = 0;
12536 shellparam.nparam = argc;
12537 shellparam.p = argv;
12540 /* This aborts if file can't be opened, which is POSIXly correct.
12541 * bash returns exitcode 1 instead.
12543 setinputfile(fullname, INPUT_PUSH_FILE);
12544 commandname = fullname;
12545 status = cmdloop(0);
12549 freeparam(&shellparam);
12550 shellparam = saveparam;
12556 static int FAST_FUNC
12557 exitcmd(int argc UNUSED_PARAM, char **argv)
12562 exitstatus = number(argv[1]);
12563 raise_exception(EXEXIT);
12568 * Read a file containing shell functions.
12571 readcmdfile(char *name)
12573 setinputfile(name, INPUT_PUSH_FILE);
12579 /* ============ find_command inplementation */
12582 * Resolve a command name. If you change this routine, you may have to
12583 * change the shellexec routine as well.
12586 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12588 struct tblentry *cmdp;
12595 struct builtincmd *bcmd;
12597 /* If name contains a slash, don't use PATH or hash table */
12598 if (strchr(name, '/') != NULL) {
12599 entry->u.index = -1;
12600 if (act & DO_ABS) {
12601 while (stat(name, &statb) < 0) {
12603 if (errno == EINTR)
12606 entry->cmdtype = CMDUNKNOWN;
12610 entry->cmdtype = CMDNORMAL;
12614 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12616 updatetbl = (path == pathval());
12619 if (strstr(path, "%builtin") != NULL)
12620 act |= DO_ALTBLTIN;
12623 /* If name is in the table, check answer will be ok */
12624 cmdp = cmdlookup(name, 0);
12625 if (cmdp != NULL) {
12628 switch (cmdp->cmdtype) {
12646 } else if (cmdp->rehash == 0)
12647 /* if not invalidated by cd, we're done */
12651 /* If %builtin not in path, check for builtin next */
12652 bcmd = find_builtin(name);
12654 if (IS_BUILTIN_REGULAR(bcmd))
12655 goto builtin_success;
12656 if (act & DO_ALTPATH) {
12657 if (!(act & DO_ALTBLTIN))
12658 goto builtin_success;
12659 } else if (builtinloc <= 0) {
12660 goto builtin_success;
12664 #if ENABLE_FEATURE_SH_STANDALONE
12666 int applet_no = find_applet_by_name(name);
12667 if (applet_no >= 0) {
12668 entry->cmdtype = CMDNORMAL;
12669 entry->u.index = -2 - applet_no;
12675 /* We have to search path. */
12676 prev = -1; /* where to start */
12677 if (cmdp && cmdp->rehash) { /* doing a rehash */
12678 if (cmdp->cmdtype == CMDBUILTIN)
12681 prev = cmdp->param.index;
12687 while ((fullname = path_advance(&path, name)) != NULL) {
12688 stunalloc(fullname);
12689 /* NB: code below will still use fullname
12690 * despite it being "unallocated" */
12693 if (prefix(pathopt, "builtin")) {
12695 goto builtin_success;
12698 if ((act & DO_NOFUNC)
12699 || !prefix(pathopt, "func")
12700 ) { /* ignore unimplemented options */
12704 /* if rehash, don't redo absolute path names */
12705 if (fullname[0] == '/' && idx <= prev) {
12708 TRACE(("searchexec \"%s\": no change\n", name));
12711 while (stat(fullname, &statb) < 0) {
12713 if (errno == EINTR)
12716 if (errno != ENOENT && errno != ENOTDIR)
12720 e = EACCES; /* if we fail, this will be the error */
12721 if (!S_ISREG(statb.st_mode))
12723 if (pathopt) { /* this is a %func directory */
12724 stalloc(strlen(fullname) + 1);
12725 /* NB: stalloc will return space pointed by fullname
12726 * (because we don't have any intervening allocations
12727 * between stunalloc above and this stalloc) */
12728 readcmdfile(fullname);
12729 cmdp = cmdlookup(name, 0);
12730 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12731 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12732 stunalloc(fullname);
12735 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12737 entry->cmdtype = CMDNORMAL;
12738 entry->u.index = idx;
12742 cmdp = cmdlookup(name, 1);
12743 cmdp->cmdtype = CMDNORMAL;
12744 cmdp->param.index = idx;
12749 /* We failed. If there was an entry for this command, delete it */
12750 if (cmdp && updatetbl)
12751 delete_cmd_entry();
12753 ash_msg("%s: %s", name, errmsg(e, "not found"));
12754 entry->cmdtype = CMDUNKNOWN;
12759 entry->cmdtype = CMDBUILTIN;
12760 entry->u.cmd = bcmd;
12764 cmdp = cmdlookup(name, 1);
12765 cmdp->cmdtype = CMDBUILTIN;
12766 cmdp->param.cmd = bcmd;
12770 entry->cmdtype = cmdp->cmdtype;
12771 entry->u = cmdp->param;
12776 * The trap builtin.
12778 static int FAST_FUNC
12779 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12783 int signo, exitcode;
12788 for (signo = 0; signo < NSIG; signo++) {
12789 char *tr = trap_ptr[signo];
12791 /* note: bash adds "SIG", but only if invoked
12792 * as "bash". If called as "sh", or if set -o posix,
12793 * then it prints short signal names.
12794 * We are printing short names: */
12795 out1fmt("trap -- %s %s\n",
12797 get_signame(signo));
12798 /* trap_ptr != trap only if we are in special-cased `trap` code.
12799 * In this case, we will exit very soon, no need to free(). */
12800 /* if (trap_ptr != trap && tp[0]) */
12805 if (trap_ptr != trap) {
12818 signo = get_signum(*ap);
12820 /* Mimic bash message exactly */
12821 ash_msg("%s: invalid signal specification", *ap);
12827 if (LONE_DASH(action))
12830 if (action[0]) /* not NULL and not "" and not "-" */
12831 may_have_traps = 1;
12832 action = ckstrdup(action);
12836 trap[signo] = action;
12847 /* ============ Builtins */
12849 #if ENABLE_ASH_HELP
12850 static int FAST_FUNC
12851 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12857 "Built-in commands:\n"
12858 "------------------\n");
12859 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12860 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12861 builtintab[i].name + 1);
12867 # if ENABLE_FEATURE_SH_STANDALONE
12869 const char *a = applet_names;
12871 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12876 while (*a++ != '\0')
12881 newline_and_flush(stdout);
12882 return EXIT_SUCCESS;
12887 static int FAST_FUNC
12888 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12890 show_history(line_input_state);
12891 return EXIT_SUCCESS;
12896 * The export and readonly commands.
12898 static int FAST_FUNC
12899 exportcmd(int argc UNUSED_PARAM, char **argv)
12909 /* "readonly" in bash accepts, but ignores -n.
12910 * We do the same: it saves a conditional in nextopt's param.
12913 while ((opt = nextopt("np")) != '\0') {
12915 flag_off = VEXPORT;
12918 if (argv[0][0] == 'r') {
12920 flag_off = 0; /* readonly ignores -n */
12922 flag_off = ~flag_off;
12924 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12930 p = strchr(name, '=');
12934 vp = *findvar(hashvar(name), name);
12936 vp->flags = ((vp->flags | flag) & flag_off);
12940 setvar(name, p, (flag & flag_off));
12941 } while ((name = *++aptr) != NULL);
12946 /* No arguments. Show the list of exported or readonly vars.
12949 showvars(argv[0], flag, 0);
12954 * Delete a function if it exists.
12957 unsetfunc(const char *name)
12959 struct tblentry *cmdp;
12961 cmdp = cmdlookup(name, 0);
12962 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12963 delete_cmd_entry();
12967 * The unset builtin command. We unset the function before we unset the
12968 * variable to allow a function to be unset when there is a readonly variable
12969 * with the same name.
12971 static int FAST_FUNC
12972 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12979 while ((i = nextopt("vf")) != 0) {
12983 for (ap = argptr; *ap; ap++) {
12996 static const unsigned char timescmd_str[] ALIGN1 = {
12997 ' ', offsetof(struct tms, tms_utime),
12998 '\n', offsetof(struct tms, tms_stime),
12999 ' ', offsetof(struct tms, tms_cutime),
13000 '\n', offsetof(struct tms, tms_cstime),
13003 static int FAST_FUNC
13004 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13006 unsigned long clk_tck, s, t;
13007 const unsigned char *p;
13010 clk_tck = bb_clk_tck();
13015 t = *(clock_t *)(((char *) &buf) + p[1]);
13018 out1fmt("%lum%lu.%03lus%c",
13020 (t * 1000) / clk_tck,
13028 #if ENABLE_SH_MATH_SUPPORT
13030 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13031 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13033 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13035 static int FAST_FUNC
13036 letcmd(int argc UNUSED_PARAM, char **argv)
13042 ash_msg_and_raise_error("expression expected");
13044 i = ash_arith(*argv);
13052 * The read builtin. Options:
13053 * -r Do not interpret '\' specially
13054 * -s Turn off echo (tty only)
13055 * -n NCHARS Read NCHARS max
13056 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13057 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13058 * -u FD Read from given FD instead of fd 0
13059 * This uses unbuffered input, which may be avoidable in some cases.
13060 * TODO: bash also has:
13061 * -a ARRAY Read into array[0],[1],etc
13062 * -d DELIM End on DELIM char, not newline
13063 * -e Use line editing (tty only)
13065 static int FAST_FUNC
13066 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13068 char *opt_n = NULL;
13069 char *opt_p = NULL;
13070 char *opt_t = NULL;
13071 char *opt_u = NULL;
13072 int read_flags = 0;
13076 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13085 read_flags |= BUILTIN_READ_SILENT;
13091 read_flags |= BUILTIN_READ_RAW;
13101 /* "read -s" needs to save/restore termios, can't allow ^C
13102 * to jump out of it.
13105 r = shell_builtin_read(setvar0,
13107 bltinlookup("IFS"), /* can be NULL */
13116 if ((uintptr_t)r > 1)
13117 ash_msg_and_raise_error(r);
13119 return (uintptr_t)r;
13122 static int FAST_FUNC
13123 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13125 static const char permuser[3] ALIGN1 = "ogu";
13128 int symbolic_mode = 0;
13130 while (nextopt("S") != '\0') {
13139 if (*argptr == NULL) {
13140 if (symbolic_mode) {
13141 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13148 *p++ = permuser[i];
13150 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13151 if (!(mask & 0400)) *p++ = 'r';
13152 if (!(mask & 0200)) *p++ = 'w';
13153 if (!(mask & 0100)) *p++ = 'x';
13161 out1fmt("%04o\n", mask);
13164 char *modestr = *argptr;
13165 /* numeric umasks are taken as-is */
13166 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13167 if (!isdigit(modestr[0]))
13169 mask = bb_parse_mode(modestr, mask);
13170 if ((unsigned)mask > 0777) {
13171 ash_msg_and_raise_error("illegal mode: %s", modestr);
13173 if (!isdigit(modestr[0]))
13180 static int FAST_FUNC
13181 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13183 return shell_builtin_ulimit(argv);
13186 /* ============ main() and helpers */
13189 * Called to exit the shell.
13198 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13199 save_history(line_input_state);
13201 status = exitstatus;
13202 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13203 if (setjmp(loc.loc)) {
13204 if (exception_type == EXEXIT)
13205 status = exitstatus;
13208 exception_handler = &loc;
13214 /*free(p); - we'll exit soon */
13217 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13218 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13221 flush_stdout_stderr();
13229 /* we will never free this */
13230 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13232 sigmode[SIGCHLD - 1] = S_DFL;
13233 setsignal(SIGCHLD);
13235 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13236 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13238 signal(SIGHUP, SIG_DFL);
13243 struct stat st1, st2;
13246 for (envp = environ; envp && *envp; envp++) {
13247 p = endofname(*envp);
13248 if (p != *envp && *p == '=') {
13249 setvareq(*envp, VEXPORT|VTEXTFIXED);
13253 setvareq((char*)defoptindvar, VTEXTFIXED);
13255 setvar0("PPID", utoa(getppid()));
13256 #if ENABLE_ASH_BASH_COMPAT
13257 p = lookupvar("SHLVL");
13258 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13259 if (!lookupvar("HOSTNAME")) {
13260 struct utsname uts;
13262 setvar0("HOSTNAME", uts.nodename);
13265 p = lookupvar("PWD");
13267 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13268 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13278 //usage:#define ash_trivial_usage
13279 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13280 //usage:#define ash_full_usage "\n\n"
13281 //usage: "Unix shell interpreter"
13283 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13284 //usage:# define sh_trivial_usage ash_trivial_usage
13285 //usage:# define sh_full_usage ash_full_usage
13287 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13288 //usage:# define bash_trivial_usage ash_trivial_usage
13289 //usage:# define bash_full_usage ash_full_usage
13293 * Process the shell command line arguments.
13296 procargs(char **argv)
13299 const char *xminusc;
13304 /* if (xargv[0]) - mmm, this is always true! */
13306 for (i = 0; i < NOPTS; i++)
13309 if (options(/*cmdline:*/ 1)) {
13310 /* it already printed err message */
13311 raise_exception(EXERROR);
13315 if (*xargv == NULL) {
13317 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13320 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13324 for (i = 0; i < NOPTS; i++)
13325 if (optlist[i] == 2)
13330 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13335 } else if (!sflag) {
13336 setinputfile(*xargv, 0);
13339 commandname = arg0;
13342 shellparam.p = xargv;
13343 #if ENABLE_ASH_GETOPTS
13344 shellparam.optind = 1;
13345 shellparam.optoff = -1;
13347 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13349 shellparam.nparam++;
13356 * Read /etc/profile, ~/.profile, $ENV.
13359 read_profile(const char *name)
13361 name = expandstr(name);
13362 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13369 * This routine is called when an error or an interrupt occurs in an
13370 * interactive shell and control is returned to the main command loop.
13371 * (In dash, this function is auto-generated by build machinery).
13380 /* from expand.c: */
13383 /* from input.c: */
13384 g_parsefile->left_in_buffer = 0;
13385 g_parsefile->left_in_line = 0; /* clear input buffer */
13388 /* from redir.c: */
13390 popredir(/*drop:*/ 0, /*restore:*/ 0);
13394 static short profile_buf[16384];
13395 extern int etext();
13399 * Main routine. We initialize things, parse the arguments, execute
13400 * profiles if we're a login shell, and then call cmdloop to execute
13401 * commands. The setjmp call sets up the location to jump to when an
13402 * exception occurs. When an exception occurs the variable "state"
13403 * is used to figure out how far we had gotten.
13405 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13406 int ash_main(int argc UNUSED_PARAM, char **argv)
13408 volatile smallint state;
13409 struct jmploc jmploc;
13410 struct stackmark smark;
13412 /* Initialize global data */
13416 #if ENABLE_ASH_ALIAS
13422 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13425 #if ENABLE_FEATURE_EDITING
13426 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13429 if (setjmp(jmploc.loc)) {
13435 e = exception_type;
13437 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13441 newline_and_flush(stderr);
13444 popstackmark(&smark);
13445 FORCE_INT_ON; /* enable interrupts */
13454 exception_handler = &jmploc;
13455 rootpid = getpid();
13458 setstackmark(&smark);
13461 TRACE(("Shell args: "));
13462 trace_puts_args(argv);
13465 if (argv[0] && argv[0][0] == '-')
13471 read_profile("/etc/profile");
13474 hp = lookupvar("HOME");
13476 read_profile("$HOME/.profile");
13482 getuid() == geteuid() && getgid() == getegid() &&
13486 const char *shinit = lookupvar("ENV");
13487 if (shinit != NULL && *shinit != '\0')
13488 read_profile(shinit);
13490 popstackmark(&smark);
13494 /* evalstring pushes parsefile stack.
13495 * Ensure we don't falsely claim that 0 (stdin)
13496 * is one of stacked source fds.
13497 * Testcase: ash -c 'exec 1>&0' must not complain. */
13498 // if (!sflag) g_parsefile->pf_fd = -1;
13499 // ^^ not necessary since now we special-case fd 0
13500 // in is_hidden_fd() to not be considered "hidden fd"
13501 evalstring(minusc, 0);
13504 if (sflag || minusc == NULL) {
13505 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13507 const char *hp = lookupvar("HISTFILE");
13509 hp = lookupvar("HOME");
13511 hp = concat_path_file(hp, ".ash_history");
13512 setvar0("HISTFILE", hp);
13514 hp = lookupvar("HISTFILE");
13518 line_input_state->hist_file = hp;
13519 # if ENABLE_FEATURE_SH_HISTFILESIZE
13520 hp = lookupvar("HISTFILESIZE");
13521 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13525 state4: /* XXX ??? - why isn't this before the "if" statement */
13533 extern void _mcleanup(void);
13537 TRACE(("End of main reached\n"));
13544 * Copyright (c) 1989, 1991, 1993, 1994
13545 * The Regents of the University of California. All rights reserved.
13547 * This code is derived from software contributed to Berkeley by
13548 * Kenneth Almquist.
13550 * Redistribution and use in source and binary forms, with or without
13551 * modification, are permitted provided that the following conditions
13553 * 1. Redistributions of source code must retain the above copyright
13554 * notice, this list of conditions and the following disclaimer.
13555 * 2. Redistributions in binary form must reproduce the above copyright
13556 * notice, this list of conditions and the following disclaimer in the
13557 * documentation and/or other materials provided with the distribution.
13558 * 3. Neither the name of the University nor the names of its contributors
13559 * may be used to endorse or promote products derived from this software
13560 * without specific prior written permission.
13562 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13563 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13564 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13565 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13566 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13567 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13568 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13569 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13570 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13571 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF