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,
3117 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3118 #else /* debug version, caught one signed char bug */
3119 # define SIT(c, syntax) \
3121 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3122 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3123 if ((syntax) < 0 || (syntax) > (2 + ENABLE_SH_MATH_SUPPORT)) \
3124 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3125 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3129 #endif /* !USE_SIT_FUNCTION */
3132 /* ============ Alias handling */
3134 #if ENABLE_ASH_ALIAS
3136 #define ALIASINUSE 1
3147 static struct alias **atab; // [ATABSIZE];
3148 #define INIT_G_alias() do { \
3149 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3153 static struct alias **
3154 __lookupalias(const char *name)
3156 unsigned int hashval;
3163 ch = (unsigned char)*p;
3167 ch = (unsigned char)*++p;
3169 app = &atab[hashval % ATABSIZE];
3171 for (; *app; app = &(*app)->next) {
3172 if (strcmp(name, (*app)->name) == 0) {
3180 static struct alias *
3181 lookupalias(const char *name, int check)
3183 struct alias *ap = *__lookupalias(name);
3185 if (check && ap && (ap->flag & ALIASINUSE))
3190 static struct alias *
3191 freealias(struct alias *ap)
3195 if (ap->flag & ALIASINUSE) {
3196 ap->flag |= ALIASDEAD;
3208 setalias(const char *name, const char *val)
3210 struct alias *ap, **app;
3212 app = __lookupalias(name);
3216 if (!(ap->flag & ALIASINUSE)) {
3219 ap->val = ckstrdup(val);
3220 ap->flag &= ~ALIASDEAD;
3223 ap = ckzalloc(sizeof(struct alias));
3224 ap->name = ckstrdup(name);
3225 ap->val = ckstrdup(val);
3226 /*ap->flag = 0; - ckzalloc did it */
3227 /*ap->next = NULL;*/
3234 unalias(const char *name)
3238 app = __lookupalias(name);
3242 *app = freealias(*app);
3253 struct alias *ap, **app;
3257 for (i = 0; i < ATABSIZE; i++) {
3259 for (ap = *app; ap; ap = *app) {
3260 *app = freealias(*app);
3270 printalias(const struct alias *ap)
3272 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3276 * TODO - sort output
3278 static int FAST_FUNC
3279 aliascmd(int argc UNUSED_PARAM, char **argv)
3288 for (i = 0; i < ATABSIZE; i++) {
3289 for (ap = atab[i]; ap; ap = ap->next) {
3295 while ((n = *++argv) != NULL) {
3296 v = strchr(n+1, '=');
3297 if (v == NULL) { /* n+1: funny ksh stuff */
3298 ap = *__lookupalias(n);
3300 fprintf(stderr, "%s: %s not found\n", "alias", n);
3313 static int FAST_FUNC
3314 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3318 while ((i = nextopt("a")) != '\0') {
3324 for (i = 0; *argptr; argptr++) {
3325 if (unalias(*argptr)) {
3326 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3334 #endif /* ASH_ALIAS */
3337 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3340 #define FORK_NOJOB 2
3342 /* mode flags for showjob(s) */
3343 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3344 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3345 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3346 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3349 * A job structure contains information about a job. A job is either a
3350 * single process or a set of processes contained in a pipeline. In the
3351 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3355 pid_t ps_pid; /* process id */
3356 int ps_status; /* last process status from wait() */
3357 char *ps_cmd; /* text of command being run */
3361 struct procstat ps0; /* status of process */
3362 struct procstat *ps; /* status or processes when more than one */
3364 int stopstatus; /* status of a stopped job */
3367 nprocs: 16, /* number of processes */
3369 #define JOBRUNNING 0 /* at least one proc running */
3370 #define JOBSTOPPED 1 /* all procs are stopped */
3371 #define JOBDONE 2 /* all procs are completed */
3373 sigint: 1, /* job was killed by SIGINT */
3374 jobctl: 1, /* job running under job control */
3376 waited: 1, /* true if this entry has been waited for */
3377 used: 1, /* true if this entry is in used */
3378 changed: 1; /* true if status has changed */
3379 struct job *prev_job; /* previous job */
3382 static struct job *makejob(/*union node *,*/ int);
3383 static int forkshell(struct job *, union node *, int);
3384 static int waitforjob(struct job *);
3387 enum { doing_jobctl = 0 };
3388 #define setjobctl(on) do {} while (0)
3390 static smallint doing_jobctl; //references:8
3391 static void setjobctl(int);
3398 ignoresig(int signo)
3400 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3401 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3402 /* No, need to do it */
3403 signal(signo, SIG_IGN);
3405 sigmode[signo - 1] = S_HARD_IGN;
3409 * Only one usage site - in setsignal()
3412 signal_handler(int signo)
3414 if (signo == SIGCHLD) {
3420 gotsig[signo - 1] = 1;
3421 pending_sig = signo;
3423 if (signo == SIGINT && !trap[SIGINT]) {
3424 if (!suppress_int) {
3426 raise_interrupt(); /* does not return */
3433 * Set the signal handler for the specified signal. The routine figures
3434 * out what it should be set to.
3437 setsignal(int signo)
3440 char cur_act, new_act;
3441 struct sigaction act;
3445 if (t != NULL) { /* trap for this sig is set */
3447 if (t[0] == '\0') /* trap is "": ignore this sig */
3451 if (rootshell && new_act == S_DFL) {
3454 if (iflag || minusc || sflag == 0)
3463 * "In all cases, bash ignores SIGQUIT. Non-builtin
3464 * commands run by bash have signal handlers
3465 * set to the values inherited by the shell
3466 * from its parent". */
3482 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3483 //whereas we have to restore it to what shell got on entry
3484 //from the parent. See comment above
3486 if (signo == SIGCHLD)
3489 t = &sigmode[signo - 1];
3492 /* current setting is not yet known */
3493 if (sigaction(signo, NULL, &act)) {
3494 /* pretend it worked; maybe we should give a warning,
3495 * but other shells don't. We don't alter sigmode,
3496 * so we retry every time.
3497 * btw, in Linux it never fails. --vda */
3500 if (act.sa_handler == SIG_IGN) {
3501 cur_act = S_HARD_IGN;
3503 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3505 cur_act = S_IGN; /* don't hard ignore these */
3509 if (cur_act == S_HARD_IGN || cur_act == new_act)
3512 act.sa_handler = SIG_DFL;
3515 act.sa_handler = signal_handler;
3518 act.sa_handler = SIG_IGN;
3522 /* flags and mask matter only if !DFL and !IGN, but we do it
3523 * for all cases for more deterministic behavior:
3526 sigfillset(&act.sa_mask);
3528 sigaction_set(signo, &act);
3533 /* mode flags for set_curjob */
3534 #define CUR_DELETE 2
3535 #define CUR_RUNNING 1
3536 #define CUR_STOPPED 0
3539 /* pgrp of shell on invocation */
3540 static int initialpgrp; //references:2
3541 static int ttyfd = -1; //5
3544 static struct job *jobtab; //5
3546 static unsigned njobs; //4
3548 static struct job *curjob; //lots
3549 /* number of presumed living untracked jobs */
3550 static int jobless; //4
3553 set_curjob(struct job *jp, unsigned mode)
3556 struct job **jpp, **curp;
3558 /* first remove from list */
3559 jpp = curp = &curjob;
3564 jpp = &jp1->prev_job;
3566 *jpp = jp1->prev_job;
3568 /* Then re-insert in correct position */
3576 /* job being deleted */
3579 /* newly created job or backgrounded job,
3580 * put after all stopped jobs.
3585 if (!jp1 || jp1->state != JOBSTOPPED)
3588 jpp = &jp1->prev_job;
3594 /* newly stopped job - becomes curjob */
3595 jp->prev_job = *jpp;
3603 jobno(const struct job *jp)
3605 return jp - jobtab + 1;
3610 * Convert a job name to a job structure.
3613 #define getjob(name, getctl) getjob(name)
3616 getjob(const char *name, int getctl)
3620 const char *err_msg = "%s: no such job";
3624 char *(*match)(const char *, const char *);
3639 if (c == '+' || c == '%') {
3641 err_msg = "No current job";
3647 err_msg = "No previous job";
3657 if (num > 0 && num <= njobs) {
3658 jp = jobtab + num - 1;
3673 if (match(jp->ps[0].ps_cmd, p)) {
3677 err_msg = "%s: ambiguous";
3687 err_msg = "job %s not created under job control";
3688 if (getctl && jp->jobctl == 0)
3693 ash_msg_and_raise_error(err_msg, name);
3697 * Mark a job structure as unused.
3700 freejob(struct job *jp)
3702 struct procstat *ps;
3706 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3707 if (ps->ps_cmd != nullstr)
3710 if (jp->ps != &jp->ps0)
3713 set_curjob(jp, CUR_DELETE);
3719 xtcsetpgrp(int fd, pid_t pgrp)
3721 if (tcsetpgrp(fd, pgrp))
3722 ash_msg_and_raise_error("can't set tty process group (%m)");
3726 * Turn job control on and off.
3728 * Note: This code assumes that the third arg to ioctl is a character
3729 * pointer, which is true on Berkeley systems but not System V. Since
3730 * System V doesn't have job control yet, this isn't a problem now.
3732 * Called with interrupts off.
3740 if (on == doing_jobctl || rootshell == 0)
3744 ofd = fd = open(_PATH_TTY, O_RDWR);
3746 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3747 * That sometimes helps to acquire controlling tty.
3748 * Obviously, a workaround for bugs when someone
3749 * failed to provide a controlling tty to bash! :) */
3755 /* fd is a tty at this point */
3756 fd = fcntl(fd, F_DUPFD, 10);
3757 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3760 goto out; /* F_DUPFD failed */
3761 close_on_exec_on(fd);
3762 while (1) { /* while we are in the background */
3763 pgrp = tcgetpgrp(fd);
3766 ash_msg("can't access tty; job control turned off");
3770 if (pgrp == getpgrp())
3781 xtcsetpgrp(fd, pgrp);
3783 /* turning job control off */
3786 /* was xtcsetpgrp, but this can make exiting ash
3787 * loop forever if pty is already deleted */
3788 tcsetpgrp(fd, pgrp);
3802 static int FAST_FUNC
3803 killcmd(int argc, char **argv)
3805 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3808 if (argv[i][0] == '%') {
3810 * "kill %N" - job kill
3811 * Converting to pgrp / pid kill
3817 jp = getjob(argv[i], 0);
3819 * In jobs started under job control, we signal
3820 * entire process group by kill -PGRP_ID.
3821 * This happens, f.e., in interactive shell.
3823 * Otherwise, we signal each child via
3824 * kill PID1 PID2 PID3.
3826 * sh -c 'sleep 1|sleep 1 & kill %1'
3827 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3828 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3830 n = jp->nprocs; /* can't be 0 (I hope) */
3833 dst = alloca(n * sizeof(int)*4);
3835 for (j = 0; j < n; j++) {
3836 struct procstat *ps = &jp->ps[j];
3837 /* Skip non-running and not-stopped members
3838 * (i.e. dead members) of the job
3840 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3843 * kill_main has matching code to expect
3844 * leading space. Needed to not confuse
3845 * negative pids with "kill -SIGNAL_NO" syntax
3847 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3851 } while (argv[++i]);
3853 return kill_main(argc, argv);
3857 showpipe(struct job *jp /*, FILE *out*/)
3859 struct procstat *ps;
3860 struct procstat *psend;
3862 psend = jp->ps + jp->nprocs;
3863 for (ps = jp->ps + 1; ps < psend; ps++)
3864 printf(" | %s", ps->ps_cmd);
3865 newline_and_flush(stdout);
3866 flush_stdout_stderr();
3871 restartjob(struct job *jp, int mode)
3873 struct procstat *ps;
3879 if (jp->state == JOBDONE)
3881 jp->state = JOBRUNNING;
3882 pgid = jp->ps[0].ps_pid;
3883 if (mode == FORK_FG)
3884 xtcsetpgrp(ttyfd, pgid);
3885 killpg(pgid, SIGCONT);
3889 if (WIFSTOPPED(ps->ps_status)) {
3895 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3900 static int FAST_FUNC
3901 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3907 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3911 jp = getjob(*argv, 1);
3912 if (mode == FORK_BG) {
3913 set_curjob(jp, CUR_RUNNING);
3914 printf("[%d] ", jobno(jp));
3916 out1str(jp->ps[0].ps_cmd);
3917 showpipe(jp /*, stdout*/);
3918 retval = restartjob(jp, mode);
3919 } while (*argv && *++argv);
3925 sprint_status48(char *s, int status, int sigonly)
3931 if (!WIFEXITED(status)) {
3932 if (JOBS && WIFSTOPPED(status))
3933 st = WSTOPSIG(status);
3935 st = WTERMSIG(status);
3937 if (st == SIGINT || st == SIGPIPE)
3939 if (JOBS && WIFSTOPPED(status))
3943 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3944 col = fmtstr(s, 32, strsignal(st));
3945 if (WCOREDUMP(status)) {
3946 strcpy(s + col, " (core dumped)");
3947 col += sizeof(" (core dumped)")-1;
3949 } else if (!sigonly) {
3950 st = WEXITSTATUS(status);
3951 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3958 wait_block_or_sig(int *status)
3965 /* Poll all children for changes in their state */
3967 /* if job control is active, accept stopped processes too */
3968 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3970 break; /* Error (e.g. EINTR, ECHILD) or pid */
3972 /* Children exist, but none are ready. Sleep until interesting signal */
3975 sigprocmask(SIG_SETMASK, &mask, &mask);
3976 while (!got_sigchld && !pending_sig)
3978 sigprocmask(SIG_SETMASK, &mask, NULL);
3979 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3980 while (!got_sigchld && !pending_sig)
3984 /* If it was SIGCHLD, poll children again */
3985 } while (got_sigchld);
3990 #define DOWAIT_NONBLOCK 0
3991 #define DOWAIT_BLOCK 1
3992 #define DOWAIT_BLOCK_OR_SIG 2
3995 dowait(int block, struct job *job)
4000 struct job *thisjob = NULL;
4002 TRACE(("dowait(0x%x) called\n", block));
4004 /* It's wrong to call waitpid() outside of INT_OFF region:
4005 * signal can arrive just after syscall return and handler can
4006 * longjmp away, losing stop/exit notification processing.
4007 * Thus, for "jobs" builtin, and for waiting for a fg job,
4008 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4010 * However, for "wait" builtin it is wrong to simply call waitpid()
4011 * in INT_OFF region: "wait" needs to wait for any running job
4012 * to change state, but should exit on any trap too.
4013 * In INT_OFF region, a signal just before syscall entry can set
4014 * pending_sig variables, but we can't check them, and we would
4015 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4017 * Because of this, we run inside INT_OFF, but use a special routine
4018 * which combines waitpid() and sigsuspend().
4019 * This is the reason why we need to have a handler for SIGCHLD:
4020 * SIG_DFL handler does not wake sigsuspend().
4023 if (block == DOWAIT_BLOCK_OR_SIG) {
4024 pid = wait_block_or_sig(&status);
4027 if (block == DOWAIT_NONBLOCK)
4028 wait_flags = WNOHANG;
4029 /* if job control is active, accept stopped processes too */
4031 wait_flags |= WUNTRACED;
4032 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4033 pid = waitpid(-1, &status, wait_flags);
4035 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4036 pid, status, errno, strerror(errno)));
4041 for (jp = curjob; jp; jp = jp->prev_job) {
4043 struct procstat *ps;
4044 struct procstat *psend;
4045 if (jp->state == JOBDONE)
4049 psend = ps + jp->nprocs;
4051 if (ps->ps_pid == pid) {
4052 TRACE(("Job %d: changing status of proc %d "
4053 "from 0x%x to 0x%x\n",
4054 jobno(jp), pid, ps->ps_status, status));
4055 ps->ps_status = status;
4058 if (ps->ps_status == -1)
4059 jobstate = JOBRUNNING;
4061 if (jobstate == JOBRUNNING)
4063 if (WIFSTOPPED(ps->ps_status)) {
4064 jp->stopstatus = ps->ps_status;
4065 jobstate = JOBSTOPPED;
4068 } while (++ps < psend);
4072 /* Found the job where one of its processes changed its state.
4073 * Is there at least one live and running process in this job? */
4074 if (jobstate != JOBRUNNING) {
4075 /* No. All live processes in the job are stopped
4076 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4078 thisjob->changed = 1;
4079 if (thisjob->state != jobstate) {
4080 TRACE(("Job %d: changing state from %d to %d\n",
4081 jobno(thisjob), thisjob->state, jobstate));
4082 thisjob->state = jobstate;
4084 if (jobstate == JOBSTOPPED)
4085 set_curjob(thisjob, CUR_STOPPED);
4091 /* The process wasn't found in job list */
4092 if (JOBS && !WIFSTOPPED(status))
4097 if (thisjob && thisjob == job) {
4101 len = sprint_status48(s, status, 1);
4113 showjob(struct job *jp, int mode)
4115 struct procstat *ps;
4116 struct procstat *psend;
4119 char s[16 + 16 + 48];
4120 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4124 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4125 /* just output process (group) id of pipeline */
4126 fprintf(out, "%d\n", ps->ps_pid);
4130 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4135 else if (curjob && jp == curjob->prev_job)
4138 if (mode & SHOW_PIDS)
4139 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4141 psend = ps + jp->nprocs;
4143 if (jp->state == JOBRUNNING) {
4144 strcpy(s + col, "Running");
4145 col += sizeof("Running") - 1;
4147 int status = psend[-1].ps_status;
4148 if (jp->state == JOBSTOPPED)
4149 status = jp->stopstatus;
4150 col += sprint_status48(s + col, status, 0);
4152 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4154 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4155 * or prints several "PID | <cmdN>" lines,
4156 * depending on SHOW_PIDS bit.
4157 * We do not print status of individual processes
4158 * between PID and <cmdN>. bash does it, but not very well:
4159 * first line shows overall job status, not process status,
4160 * making it impossible to know 1st process status.
4164 /* for each process */
4167 if (mode & SHOW_PIDS)
4168 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4170 fprintf(out, "%s%*c%s%s",
4172 33 - col >= 0 ? 33 - col : 0, ' ',
4173 ps == jp->ps ? "" : "| ",
4176 } while (++ps != psend);
4177 newline_and_flush(out);
4181 if (jp->state == JOBDONE) {
4182 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4188 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4189 * statuses have changed since the last call to showjobs.
4196 TRACE(("showjobs(0x%x) called\n", mode));
4198 /* Handle all finished jobs */
4199 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4202 for (jp = curjob; jp; jp = jp->prev_job) {
4203 if (!(mode & SHOW_CHANGED) || jp->changed) {
4209 static int FAST_FUNC
4210 jobscmd(int argc UNUSED_PARAM, char **argv)
4215 while ((m = nextopt("lp")) != '\0') {
4219 mode |= SHOW_ONLY_PGID;
4225 showjob(getjob(*argv, 0), mode);
4235 /* Called only on finished or stopped jobs (no members are running) */
4237 getstatus(struct job *job)
4241 struct procstat *ps;
4243 /* Fetch last member's status */
4244 ps = job->ps + job->nprocs - 1;
4245 status = ps->ps_status;
4247 /* "set -o pipefail" mode: use last _nonzero_ status */
4248 while (status == 0 && --ps >= job->ps)
4249 status = ps->ps_status;
4252 retval = WEXITSTATUS(status);
4253 if (!WIFEXITED(status)) {
4255 retval = WSTOPSIG(status);
4256 if (!WIFSTOPPED(status))
4259 /* XXX: limits number of signals */
4260 retval = WTERMSIG(status);
4262 if (retval == SIGINT)
4268 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4269 jobno(job), job->nprocs, status, retval));
4273 static int FAST_FUNC
4274 waitcmd(int argc UNUSED_PARAM, char **argv)
4285 /* wait for all jobs */
4289 if (!jp) /* no running procs */
4291 if (jp->state == JOBRUNNING)
4297 * "When bash is waiting for an asynchronous command via
4298 * the wait builtin, the reception of a signal for which a trap
4299 * has been set will cause the wait builtin to return immediately
4300 * with an exit status greater than 128, immediately after which
4301 * the trap is executed."
4303 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4304 /* if child sends us a signal *and immediately exits*,
4305 * dowait() returns pid > 0. Check this case,
4306 * not "if (dowait() < 0)"!
4315 if (**argv != '%') {
4316 pid_t pid = number(*argv);
4321 if (job->ps[job->nprocs - 1].ps_pid == pid)
4323 job = job->prev_job;
4326 job = getjob(*argv, 0);
4328 /* loop until process terminated or stopped */
4329 while (job->state == JOBRUNNING) {
4330 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4335 retval = getstatus(job);
4342 retval = 128 + pending_sig;
4351 struct job *jp, *jq;
4353 len = njobs * sizeof(*jp);
4355 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4357 offset = (char *)jp - (char *)jq;
4359 /* Relocate pointers */
4362 jq = (struct job *)((char *)jq + l);
4366 #define joff(p) ((struct job *)((char *)(p) + l))
4367 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4368 if (joff(jp)->ps == &jq->ps0)
4369 jmove(joff(jp)->ps);
4370 if (joff(jp)->prev_job)
4371 jmove(joff(jp)->prev_job);
4381 jp = (struct job *)((char *)jp + len);
4385 } while (--jq >= jp);
4390 * Return a new job structure.
4391 * Called with interrupts off.
4394 makejob(/*union node *node,*/ int nprocs)
4399 for (i = njobs, jp = jobtab; ; jp++) {
4406 if (jp->state != JOBDONE || !jp->waited)
4415 memset(jp, 0, sizeof(*jp));
4417 /* jp->jobctl is a bitfield.
4418 * "jp->jobctl |= jobctl" likely to give awful code */
4422 jp->prev_job = curjob;
4427 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4429 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4436 * Return a string identifying a command (to be printed by the
4439 static char *cmdnextc;
4442 cmdputs(const char *s)
4444 static const char vstype[VSTYPE + 1][3] = {
4445 "", "}", "-", "+", "?", "=",
4446 "%", "%%", "#", "##"
4447 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4450 const char *p, *str;
4454 unsigned char subtype = 0;
4458 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4460 while ((c = *p++) != '\0') {
4468 if ((subtype & VSTYPE) == VSLENGTH)
4474 str = "\"}" + !(quoted & 1);
4481 #if ENABLE_SH_MATH_SUPPORT
4496 if ((subtype & VSTYPE) != VSNORMAL)
4498 str = vstype[subtype & VSTYPE];
4499 if (subtype & VSNUL)
4508 /* These can only happen inside quotes */
4521 while ((c = *str++) != '\0') {
4524 } /* while *p++ not NUL */
4527 USTPUTC('"', nextc);
4533 /* cmdtxt() and cmdlist() call each other */
4534 static void cmdtxt(union node *n);
4537 cmdlist(union node *np, int sep)
4539 for (; np; np = np->narg.next) {
4543 if (sep && np->narg.next)
4549 cmdtxt(union node *n)
4552 struct nodelist *lp;
4563 lp = n->npipe.cmdlist;
4581 cmdtxt(n->nbinary.ch1);
4597 cmdtxt(n->nif.test);
4599 if (n->nif.elsepart) {
4600 cmdtxt(n->nif.ifpart);
4602 n = n->nif.elsepart;
4620 cmdtxt(n->nbinary.ch1);
4630 cmdputs(n->nfor.var);
4632 cmdlist(n->nfor.args, 1);
4637 cmdputs(n->narg.text);
4641 cmdlist(n->ncmd.args, 1);
4642 cmdlist(n->ncmd.redirect, 0);
4655 cmdputs(n->ncase.expr->narg.text);
4657 for (np = n->ncase.cases; np; np = np->nclist.next) {
4658 cmdtxt(np->nclist.pattern);
4660 cmdtxt(np->nclist.body);
4674 #if ENABLE_ASH_BASH_COMPAT
4689 cmdputs(utoa(n->nfile.fd));
4691 if (n->type == NTOFD || n->type == NFROMFD) {
4692 cmdputs(utoa(n->ndup.dupfd));
4701 commandtext(union node *n)
4705 STARTSTACKSTR(cmdnextc);
4707 name = stackblock();
4708 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4709 return ckstrdup(name);
4714 * Fork off a subshell. If we are doing job control, give the subshell its
4715 * own process group. Jp is a job structure that the job is to be added to.
4716 * N is the command that will be evaluated by the child. Both jp and n may
4717 * be NULL. The mode parameter can be one of the following:
4718 * FORK_FG - Fork off a foreground process.
4719 * FORK_BG - Fork off a background process.
4720 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4721 * process group even if job control is on.
4723 * When job control is turned off, background processes have their standard
4724 * input redirected to /dev/null (except for the second and later processes
4727 * Called with interrupts off.
4730 * Clear traps on a fork.
4738 for (tp = trap; tp < &trap[NSIG]; tp++) {
4739 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4740 if (trap_ptr == trap)
4742 /* else: it "belongs" to trap_ptr vector, don't free */
4744 if ((tp - trap) != 0)
4745 setsignal(tp - trap);
4752 /* Lives far away from here, needed for forkchild */
4753 static void closescript(void);
4755 /* Called after fork(), in child */
4756 /* jp and n are NULL when called by openhere() for heredoc support */
4757 static NOINLINE void
4758 forkchild(struct job *jp, union node *n, int mode)
4762 TRACE(("Child shell %d\n", getpid()));
4766 /* man bash: "Non-builtin commands run by bash have signal handlers
4767 * set to the values inherited by the shell from its parent".
4768 * Do we do it correctly? */
4772 if (mode == FORK_NOJOB /* is it `xxx` ? */
4773 && n && n->type == NCMD /* is it single cmd? */
4774 /* && n->ncmd.args->type == NARG - always true? */
4775 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4776 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4777 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4779 TRACE(("Trap hack\n"));
4780 /* Awful hack for `trap` or $(trap).
4782 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4783 * contains an example where "trap" is executed in a subshell:
4785 * save_traps=$(trap)
4787 * eval "$save_traps"
4789 * Standard does not say that "trap" in subshell shall print
4790 * parent shell's traps. It only says that its output
4791 * must have suitable form, but then, in the above example
4792 * (which is not supposed to be normative), it implies that.
4794 * bash (and probably other shell) does implement it
4795 * (traps are reset to defaults, but "trap" still shows them),
4796 * but as a result, "trap" logic is hopelessly messed up:
4799 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4800 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4801 * # true | trap <--- trap is in subshell - no output (ditto)
4802 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4803 * trap -- 'echo Ho' SIGWINCH
4804 * # echo `(trap)` <--- in subshell in subshell - output
4805 * trap -- 'echo Ho' SIGWINCH
4806 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4807 * trap -- 'echo Ho' SIGWINCH
4809 * The rules when to forget and when to not forget traps
4810 * get really complex and nonsensical.
4812 * Our solution: ONLY bare $(trap) or `trap` is special.
4814 /* Save trap handler strings for trap builtin to print */
4815 trap_ptr = xmemdup(trap, sizeof(trap));
4816 /* Fall through into clearing traps */
4820 /* do job control only in root shell */
4822 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4825 if (jp->nprocs == 0)
4828 pgrp = jp->ps[0].ps_pid;
4829 /* this can fail because we are doing it in the parent also */
4831 if (mode == FORK_FG)
4832 xtcsetpgrp(ttyfd, pgrp);
4837 if (mode == FORK_BG) {
4838 /* man bash: "When job control is not in effect,
4839 * asynchronous commands ignore SIGINT and SIGQUIT" */
4842 if (jp->nprocs == 0) {
4844 if (open(bb_dev_null, O_RDONLY) != 0)
4845 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4849 if (iflag) { /* why if iflag only? */
4854 * "In all cases, bash ignores SIGQUIT. Non-builtin
4855 * commands run by bash have signal handlers
4856 * set to the values inherited by the shell
4858 * Take care of the second rule: */
4862 if (n && n->type == NCMD
4863 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4865 TRACE(("Job hack\n"));
4866 /* "jobs": we do not want to clear job list for it,
4867 * instead we remove only _its_ own_ job from job list.
4868 * This makes "jobs .... | cat" more useful.
4874 for (jp = curjob; jp; jp = jp->prev_job)
4879 /* Called after fork(), in parent */
4881 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4884 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4886 TRACE(("In parent shell: child = %d\n", pid));
4888 /* jp is NULL when called by openhere() for heredoc support */
4889 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4895 if (mode != FORK_NOJOB && jp->jobctl) {
4898 if (jp->nprocs == 0)
4901 pgrp = jp->ps[0].ps_pid;
4902 /* This can fail because we are doing it in the child also */
4906 if (mode == FORK_BG) {
4907 backgndpid = pid; /* set $! */
4908 set_curjob(jp, CUR_RUNNING);
4911 struct procstat *ps = &jp->ps[jp->nprocs++];
4914 ps->ps_cmd = nullstr;
4916 if (doing_jobctl && n)
4917 ps->ps_cmd = commandtext(n);
4922 /* jp and n are NULL when called by openhere() for heredoc support */
4924 forkshell(struct job *jp, union node *n, int mode)
4928 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4931 TRACE(("Fork failed, errno=%d", errno));
4934 ash_msg_and_raise_error("can't fork");
4937 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4938 forkchild(jp, n, mode);
4940 forkparent(jp, n, mode, pid);
4946 * Wait for job to finish.
4948 * Under job control we have the problem that while a child process
4949 * is running interrupts generated by the user are sent to the child
4950 * but not to the shell. This means that an infinite loop started by
4951 * an interactive user may be hard to kill. With job control turned off,
4952 * an interactive user may place an interactive program inside a loop.
4953 * If the interactive program catches interrupts, the user doesn't want
4954 * these interrupts to also abort the loop. The approach we take here
4955 * is to have the shell ignore interrupt signals while waiting for a
4956 * foreground process to terminate, and then send itself an interrupt
4957 * signal if the child process was terminated by an interrupt signal.
4958 * Unfortunately, some programs want to do a bit of cleanup and then
4959 * exit on interrupt; unless these processes terminate themselves by
4960 * sending a signal to themselves (instead of calling exit) they will
4961 * confuse this approach.
4963 * Called with interrupts off.
4966 waitforjob(struct job *jp)
4970 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4973 while (jp->state == JOBRUNNING) {
4974 /* In non-interactive shells, we _can_ get
4975 * a keyboard signal here and be EINTRed,
4976 * but we just loop back, waiting for command to complete.
4979 * "If bash is waiting for a command to complete and receives
4980 * a signal for which a trap has been set, the trap
4981 * will not be executed until the command completes."
4983 * Reality is that even if trap is not set, bash
4984 * will not act on the signal until command completes.
4985 * Try this. sleep5intoff.c:
4986 * #include <signal.h>
4987 * #include <unistd.h>
4990 * sigemptyset(&set);
4991 * sigaddset(&set, SIGINT);
4992 * sigaddset(&set, SIGQUIT);
4993 * sigprocmask(SIG_BLOCK, &set, NULL);
4997 * $ bash -c './sleep5intoff; echo hi'
4998 * ^C^C^C^C <--- pressing ^C once a second
5000 * $ bash -c './sleep5intoff; echo hi'
5001 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5004 dowait(DOWAIT_BLOCK, jp);
5011 xtcsetpgrp(ttyfd, rootpid);
5013 * This is truly gross.
5014 * If we're doing job control, then we did a TIOCSPGRP which
5015 * caused us (the shell) to no longer be in the controlling
5016 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5017 * intuit from the subprocess exit status whether a SIGINT
5018 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5020 if (jp->sigint) /* TODO: do the same with all signals */
5021 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5023 if (jp->state == JOBDONE)
5030 * return 1 if there are stopped jobs, otherwise 0
5042 if (jp && jp->state == JOBSTOPPED) {
5043 out2str("You have stopped jobs.\n");
5053 * Code for dealing with input/output redirection.
5058 #define EMPTY -2 /* marks an unused slot in redirtab */
5059 #define CLOSED -3 /* marks a slot of previously-closed fd */
5062 * Open a file in noclobber mode.
5063 * The code was copied from bash.
5066 noclobberopen(const char *fname)
5069 struct stat finfo, finfo2;
5072 * If the file exists and is a regular file, return an error
5075 r = stat(fname, &finfo);
5076 if (r == 0 && S_ISREG(finfo.st_mode)) {
5082 * If the file was not present (r != 0), make sure we open it
5083 * exclusively so that if it is created before we open it, our open
5084 * will fail. Make sure that we do not truncate an existing file.
5085 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5086 * file was not a regular file, we leave O_EXCL off.
5089 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5090 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5092 /* If the open failed, return the file descriptor right away. */
5097 * OK, the open succeeded, but the file may have been changed from a
5098 * non-regular file to a regular file between the stat and the open.
5099 * We are assuming that the O_EXCL open handles the case where FILENAME
5100 * did not exist and is symlinked to an existing file between the stat
5105 * If we can open it and fstat the file descriptor, and neither check
5106 * revealed that it was a regular file, and the file has not been
5107 * replaced, return the file descriptor.
5109 if (fstat(fd, &finfo2) == 0
5110 && !S_ISREG(finfo2.st_mode)
5111 && finfo.st_dev == finfo2.st_dev
5112 && finfo.st_ino == finfo2.st_ino
5117 /* The file has been replaced. badness. */
5124 * Handle here documents. Normally we fork off a process to write the
5125 * data to a pipe. If the document is short, we can stuff the data in
5126 * the pipe without forking.
5128 /* openhere needs this forward reference */
5129 static void expandhere(union node *arg, int fd);
5131 openhere(union node *redir)
5137 ash_msg_and_raise_error("pipe call failed");
5138 if (redir->type == NHERE) {
5139 len = strlen(redir->nhere.doc->narg.text);
5140 if (len <= PIPE_BUF) {
5141 full_write(pip[1], redir->nhere.doc->narg.text, len);
5145 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5148 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5149 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5150 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5151 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5152 signal(SIGPIPE, SIG_DFL);
5153 if (redir->type == NHERE)
5154 full_write(pip[1], redir->nhere.doc->narg.text, len);
5156 expandhere(redir->nhere.doc, pip[1]);
5157 _exit(EXIT_SUCCESS);
5165 openredirect(union node *redir)
5170 switch (redir->nfile.type) {
5171 /* Can't happen, our single caller does this itself */
5177 return openhere(redir);
5180 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5181 * allocated space. Do it only when we know it is safe.
5183 fname = redir->nfile.expfname;
5185 switch (redir->nfile.type) {
5191 f = open(fname, O_RDONLY);
5196 f = open(fname, O_RDWR|O_CREAT, 0666);
5201 #if ENABLE_ASH_BASH_COMPAT
5204 /* Take care of noclobber mode. */
5206 f = noclobberopen(fname);
5213 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5218 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5226 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5228 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5232 * Copy a file descriptor to be >= 10. Throws exception on error.
5240 newfd = fcntl(from, F_DUPFD, 10);
5241 err = newfd < 0 ? errno : 0;
5244 ash_msg_and_raise_error("%d: %m", from);
5246 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5252 dup2_or_raise(int from, int to)
5256 newfd = (from != to) ? dup2(from, to) : to;
5258 /* Happens when source fd is not open: try "echo >&99" */
5259 ash_msg_and_raise_error("%d: %m", from);
5264 /* Struct def and variable are moved down to the first usage site */
5269 struct redirtab *next;
5271 struct two_fd_t two_fd[];
5273 #define redirlist (G_var.redirlist)
5275 COPYFD_RESTORE = (int)~(INT_MAX),
5279 need_to_remember(struct redirtab *rp, int fd)
5283 if (!rp) /* remembering was not requested */
5286 for (i = 0; i < rp->pair_count; i++) {
5287 if (rp->two_fd[i].orig == fd) {
5288 /* already remembered */
5295 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5297 is_hidden_fd(struct redirtab *rp, int fd)
5300 struct parsefile *pf;
5304 /* Check open scripts' fds */
5307 /* We skip pf_fd == 0 case because of the following case:
5308 * $ ash # running ash interactively
5310 * and in script.sh: "exec 9>&0".
5311 * Even though top-level pf_fd _is_ 0,
5312 * it's still ok to use it: "read" builtin uses it,
5313 * why should we cripple "exec" builtin?
5315 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5323 /* Check saved fds of redirects */
5324 fd |= COPYFD_RESTORE;
5325 for (i = 0; i < rp->pair_count; i++) {
5326 if (rp->two_fd[i].copy == fd) {
5334 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5335 * old file descriptors are stashed away so that the redirection can be
5336 * undone by calling popredir.
5338 /* flags passed to redirect */
5339 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5340 #define REDIR_SAVEFD2 03 /* set preverrout */
5342 redirect(union node *redir, int flags)
5344 struct redirtab *sv;
5349 int copied_fd2 = -1;
5358 if (flags & REDIR_PUSH) {
5359 union node *tmp = redir;
5362 #if ENABLE_ASH_BASH_COMPAT
5363 if (tmp->nfile.type == NTO2)
5366 tmp = tmp->nfile.next;
5368 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5369 sv->next = redirlist;
5370 sv->pair_count = sv_pos;
5372 while (sv_pos > 0) {
5374 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5380 fd = redir->nfile.fd;
5381 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5382 right_fd = redir->ndup.dupfd;
5383 //bb_error_msg("doing %d > %d", fd, right_fd);
5384 /* redirect from/to same file descriptor? */
5387 /* "echo >&10" and 10 is a fd opened to a sh script? */
5388 if (is_hidden_fd(sv, right_fd)) {
5389 errno = EBADF; /* as if it is closed */
5390 ash_msg_and_raise_error("%d: %m", right_fd);
5394 newfd = openredirect(redir); /* always >= 0 */
5396 /* Descriptor wasn't open before redirect.
5397 * Mark it for close in the future */
5398 if (need_to_remember(sv, fd)) {
5399 goto remember_to_close;
5404 #if ENABLE_ASH_BASH_COMPAT
5407 if (need_to_remember(sv, fd)) {
5408 /* Copy old descriptor */
5409 /* Careful to not accidentally "save"
5410 * to the same fd as right side fd in N>&M */
5411 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5412 i = fcntl(fd, F_DUPFD, minfd);
5413 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5414 * are closed in popredir() in the child, preventing them from leaking
5415 * into child. (popredir() also cleans up the mess in case of failures)
5420 /* Strange error (e.g. "too many files" EMFILE?) */
5424 ash_msg_and_raise_error("%d: %m", fd);
5427 /* EBADF: it is not open - good, remember to close it */
5430 } else { /* fd is open, save its copy */
5431 /* "exec fd>&-" should not close fds
5432 * which point to script file(s).
5433 * Force them to be restored afterwards */
5434 if (is_hidden_fd(sv, fd))
5435 i |= COPYFD_RESTORE;
5439 sv->two_fd[sv_pos].orig = fd;
5440 sv->two_fd[sv_pos].copy = i;
5444 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5445 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5446 /* Don't want to trigger debugging */
5450 dup2_or_raise(redir->ndup.dupfd, fd);
5452 } else if (fd != newfd) { /* move newfd to fd */
5453 dup2_or_raise(newfd, fd);
5454 #if ENABLE_ASH_BASH_COMPAT
5455 if (!(redir->nfile.type == NTO2 && fd == 2))
5459 #if ENABLE_ASH_BASH_COMPAT
5460 if (redir->nfile.type == NTO2 && fd == 1) {
5461 /* We already redirected it to fd 1, now copy it to 2 */
5467 } while ((redir = redir->nfile.next) != NULL);
5470 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5471 preverrout_fd = copied_fd2;
5475 * Undo the effects of the last redirection.
5478 popredir(int drop, int restore)
5480 struct redirtab *rp;
5483 if (redirlist == NULL)
5487 for (i = 0; i < rp->pair_count; i++) {
5488 int fd = rp->two_fd[i].orig;
5489 int copy = rp->two_fd[i].copy;
5490 if (copy == CLOSED) {
5495 if (copy != EMPTY) {
5496 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5497 copy &= ~COPYFD_RESTORE;
5499 dup2_or_raise(copy, fd);
5501 close(copy & ~COPYFD_RESTORE);
5504 redirlist = rp->next;
5510 * Undo all redirections. Called on error or interrupt.
5514 redirectsafe(union node *redir, int flags)
5517 volatile int saveint;
5518 struct jmploc *volatile savehandler = exception_handler;
5519 struct jmploc jmploc;
5522 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5523 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5525 exception_handler = &jmploc;
5526 redirect(redir, flags);
5528 exception_handler = savehandler;
5529 if (err && exception_type != EXERROR)
5530 longjmp(exception_handler->loc, 1);
5531 RESTORE_INT(saveint);
5536 /* ============ Routines to expand arguments to commands
5538 * We have to deal with backquotes, shell variables, and file metacharacters.
5541 #if ENABLE_SH_MATH_SUPPORT
5543 ash_arith(const char *s)
5545 arith_state_t math_state;
5548 math_state.lookupvar = lookupvar;
5549 math_state.setvar = setvar0;
5550 //math_state.endofname = endofname;
5553 result = arith(&math_state, s);
5554 if (math_state.errmsg)
5555 ash_msg_and_raise_error(math_state.errmsg);
5565 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5566 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5567 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5568 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5569 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5570 * POSIX says for this case:
5571 * Pathname expansion shall not be performed on the word by a
5572 * non-interactive shell; an interactive shell may perform it, but shall
5573 * do so only when the expansion would result in one word.
5574 * Currently, our code complies to the above rule by never globbing
5575 * redirection filenames.
5576 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5577 * (this means that on a typical Linux distro, bash almost always
5578 * performs globbing, and thus diverges from what we do).
5580 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5581 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5582 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5583 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5584 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5588 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5589 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5590 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5591 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5592 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5594 /* Add CTLESC when necessary. */
5595 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5596 /* Do not skip NUL characters. */
5597 #define QUOTES_KEEPNUL EXP_TILDE
5600 * Structure specifying which parts of the string should be searched
5601 * for IFS characters.
5604 struct ifsregion *next; /* next region in list */
5605 int begoff; /* offset of start of region */
5606 int endoff; /* offset of end of region */
5607 int nulonly; /* search for nul bytes only */
5611 struct strlist *list;
5612 struct strlist **lastp;
5615 /* output of current string */
5616 static char *expdest;
5617 /* list of back quote expressions */
5618 static struct nodelist *argbackq;
5619 /* first struct in list of ifs regions */
5620 static struct ifsregion ifsfirst;
5621 /* last struct in list */
5622 static struct ifsregion *ifslastp;
5623 /* holds expanded arg list */
5624 static struct arglist exparg;
5629 #if !ENABLE_SH_MATH_SUPPORT
5630 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5631 typedef long arith_t;
5632 # define ARITH_FMT "%ld"
5639 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5640 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5641 STADJUST(len, expdest);
5646 * Break the argument string into pieces based upon IFS and add the
5647 * strings to the argument list. The regions of the string to be
5648 * searched for IFS characters have been stored by recordregion.
5651 ifsbreakup(char *string, struct arglist *arglist)
5653 struct ifsregion *ifsp;
5658 const char *ifs, *realifs;
5663 if (ifslastp != NULL) {
5666 realifs = ifsset() ? ifsval() : defifs;
5669 p = string + ifsp->begoff;
5670 nulonly = ifsp->nulonly;
5671 ifs = nulonly ? nullstr : realifs;
5673 while (p < string + ifsp->endoff) {
5675 if ((unsigned char)*p == CTLESC)
5677 if (!strchr(ifs, *p)) {
5682 ifsspc = (strchr(defifs, *p) != NULL);
5683 /* Ignore IFS whitespace at start */
5684 if (q == start && ifsspc) {
5690 sp = stzalloc(sizeof(*sp));
5692 *arglist->lastp = sp;
5693 arglist->lastp = &sp->next;
5697 if (p >= string + ifsp->endoff) {
5701 if ((unsigned char)*p == CTLESC)
5703 if (strchr(ifs, *p) == NULL) {
5707 if (strchr(defifs, *p) == NULL) {
5722 } while (ifsp != NULL);
5731 sp = stzalloc(sizeof(*sp));
5733 *arglist->lastp = sp;
5734 arglist->lastp = &sp->next;
5740 struct ifsregion *p = ifsfirst.next;
5747 struct ifsregion *ifsp;
5752 ifsfirst.next = NULL;
5759 esclen(const char *start, const char *p)
5763 while (p > start && (unsigned char)*--p == CTLESC) {
5770 * Remove any CTLESC characters from a string.
5773 rmescapes(char *str, int flag)
5775 static const char qchars[] ALIGN1 = {
5776 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5780 unsigned protect_against_glob;
5782 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5784 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5790 if (flag & RMESCAPE_ALLOC) {
5791 size_t len = p - str;
5792 size_t fulllen = len + strlen(p) + 1;
5794 if (flag & RMESCAPE_GROW) {
5795 int strloc = str - (char *)stackblock();
5796 r = makestrspace(fulllen, expdest);
5797 /* p and str may be invalidated by makestrspace */
5798 str = (char *)stackblock() + strloc;
5800 } else if (flag & RMESCAPE_HEAP) {
5801 r = ckmalloc(fulllen);
5803 r = stalloc(fulllen);
5807 q = (char *)memcpy(q, str, len) + len;
5812 globbing = flag & RMESCAPE_GLOB;
5813 protect_against_glob = globbing;
5815 if ((unsigned char)*p == CTLQUOTEMARK) {
5816 // Note: both inquotes and protect_against_glob only affect whether
5817 inquotes = ~inquotes;
5819 protect_against_glob = globbing;
5822 if ((unsigned char)*p == CTLESC) {
5826 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5828 if (protect_against_glob) {
5831 } else if (*p == '\\' && !inquotes) {
5832 /* naked back slash */
5833 protect_against_glob = 0;
5836 #if ENABLE_ASH_BASH_COMPAT
5837 else if (*p == '/' && slash) {
5838 /* stop handling globbing and mark location of slash */
5839 globbing = slash = 0;
5843 protect_against_glob = globbing;
5848 if (flag & RMESCAPE_GROW) {
5850 STADJUST(q - r + 1, expdest);
5854 #define pmatch(a, b) !fnmatch((a), (b), 0)
5857 * Prepare a pattern for a expmeta (internal glob(3)) call.
5859 * Returns an stalloced string.
5862 preglob(const char *pattern, int flag)
5864 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5868 * Put a string on the stack.
5871 memtodest(const char *p, size_t len, int syntax, int quotes)
5878 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5881 unsigned char c = *p++;
5883 if (quotes & QUOTES_ESC) {
5884 int n = SIT(c, syntax);
5886 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5893 } else if (!(quotes & QUOTES_KEEPNUL))
5902 strtodest(const char *p, int syntax, int quotes)
5904 size_t len = strlen(p);
5905 memtodest(p, len, syntax, quotes);
5910 * Record the fact that we have to scan this region of the
5911 * string for IFS characters.
5914 recordregion(int start, int end, int nulonly)
5916 struct ifsregion *ifsp;
5918 if (ifslastp == NULL) {
5922 ifsp = ckzalloc(sizeof(*ifsp));
5923 /*ifsp->next = NULL; - ckzalloc did it */
5924 ifslastp->next = ifsp;
5928 ifslastp->begoff = start;
5929 ifslastp->endoff = end;
5930 ifslastp->nulonly = nulonly;
5934 removerecordregions(int endoff)
5936 if (ifslastp == NULL)
5939 if (ifsfirst.endoff > endoff) {
5940 while (ifsfirst.next) {
5941 struct ifsregion *ifsp;
5943 ifsp = ifsfirst.next->next;
5944 free(ifsfirst.next);
5945 ifsfirst.next = ifsp;
5948 if (ifsfirst.begoff > endoff) {
5951 ifslastp = &ifsfirst;
5952 ifsfirst.endoff = endoff;
5957 ifslastp = &ifsfirst;
5958 while (ifslastp->next && ifslastp->next->begoff < endoff)
5959 ifslastp = ifslastp->next;
5960 while (ifslastp->next) {
5961 struct ifsregion *ifsp;
5963 ifsp = ifslastp->next->next;
5964 free(ifslastp->next);
5965 ifslastp->next = ifsp;
5968 if (ifslastp->endoff > endoff)
5969 ifslastp->endoff = endoff;
5973 exptilde(char *startp, char *p, int flags)
5979 int quotes = flags & QUOTES_ESC;
5983 while ((c = *++p) != '\0') {
5990 if (flags & EXP_VARTILDE)
6000 if (*name == '\0') {
6001 home = lookupvar("HOME");
6003 pw = getpwnam(name);
6008 if (!home || !*home)
6011 strtodest(home, SQSYNTAX, quotes);
6019 * Execute a command inside back quotes. If it's a builtin command, we
6020 * want to save its output in a block obtained from malloc. Otherwise
6021 * we fork off a subprocess and get the output of the command via a pipe.
6022 * Should be called with interrupts off.
6024 struct backcmd { /* result of evalbackcmd */
6025 int fd; /* file descriptor to read from */
6026 int nleft; /* number of chars in buffer */
6027 char *buf; /* buffer */
6028 struct job *jp; /* job structure for command */
6031 /* These forward decls are needed to use "eval" code for backticks handling: */
6032 #define EV_EXIT 01 /* exit after evaluating tree */
6033 static int evaltree(union node *, int);
6035 static void FAST_FUNC
6036 evalbackcmd(union node *n, struct backcmd *result)
6050 ash_msg_and_raise_error("pipe call failed");
6051 jp = makejob(/*n,*/ 1);
6052 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6058 dup2_or_raise(pip[1], 1);
6061 /* TODO: eflag clearing makes the following not abort:
6062 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6063 * which is what bash does (unless it is in POSIX mode).
6064 * dash deleted "eflag = 0" line in the commit
6065 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6066 * [EVAL] Don't clear eflag in evalbackcmd
6067 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6071 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6076 result->fd = pip[0];
6080 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6081 result->fd, result->buf, result->nleft, result->jp));
6085 * Expand stuff in backwards quotes.
6088 expbackq(union node *cmd, int flag)
6096 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6097 struct stackmark smark;
6100 startloc = expdest - (char *)stackblock();
6101 pushstackmark(&smark, startloc);
6102 evalbackcmd(cmd, &in);
6103 popstackmark(&smark);
6110 memtodest(p, i, syntax, flag & QUOTES_ESC);
6114 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6115 TRACE(("expbackq: read returns %d\n", i));
6124 back_exitstatus = waitforjob(in.jp);
6128 /* Eat all trailing newlines */
6130 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6134 if (!(flag & EXP_QUOTED))
6135 recordregion(startloc, dest - (char *)stackblock(), 0);
6136 TRACE(("evalbackq: size:%d:'%.*s'\n",
6137 (int)((dest - (char *)stackblock()) - startloc),
6138 (int)((dest - (char *)stackblock()) - startloc),
6139 stackblock() + startloc));
6142 #if ENABLE_SH_MATH_SUPPORT
6144 * Expand arithmetic expression. Backup to start of expression,
6145 * evaluate, place result in (backed up) result, adjust string position.
6157 * This routine is slightly over-complicated for
6158 * efficiency. Next we scan backwards looking for the
6159 * start of arithmetic.
6161 start = stackblock();
6168 while ((unsigned char)*p != CTLARI) {
6172 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6177 esc = esclen(start, p);
6187 removerecordregions(begoff);
6191 if (flag & QUOTES_ESC)
6192 rmescapes(p + 1, 0);
6194 len = cvtnum(ash_arith(p + 1));
6196 if (!(flag & EXP_QUOTED))
6197 recordregion(begoff, begoff + len, 0);
6201 /* argstr needs it */
6202 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6205 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6206 * characters to allow for further processing. Otherwise treat
6207 * $@ like $* since no splitting will be performed.
6209 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6210 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6211 * for correct expansion of "B=$A" word.
6214 argstr(char *p, int flags, struct strlist *var_str_list)
6216 static const char spclchars[] ALIGN1 = {
6224 #if ENABLE_SH_MATH_SUPPORT
6229 const char *reject = spclchars;
6230 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6235 if (!(flags & EXP_VARTILDE)) {
6237 } else if (flags & EXP_VARTILDE2) {
6242 if (flags & EXP_TILDE) {
6245 flags &= ~EXP_TILDE;
6249 p = exptilde(p, q, flags);
6252 startloc = expdest - (char *)stackblock();
6256 length += strcspn(p + length, reject);
6260 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6262 /* c == '=' || c == ':' || c == CTLENDARI */
6268 expdest = stack_nputstr(p, length, expdest);
6269 newloc = expdest - (char *)stackblock();
6270 if (breakall && !inquotes && newloc > startloc) {
6271 recordregion(startloc, newloc, 0);
6282 if (flags & EXP_VARTILDE2) {
6286 flags |= EXP_VARTILDE2;
6291 * sort of a hack - expand tildes in variable
6292 * assignments (after the first '=' and after ':'s).
6301 case CTLENDVAR: /* ??? */
6304 inquotes ^= EXP_QUOTED;
6305 /* "$@" syntax adherence hack */
6306 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6307 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6311 if (flags & QUOTES_ESC) {
6322 * Quoted parameter expansion pattern: remove quote
6323 * unless inside inner quotes or we have a literal
6326 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6327 EXP_QPAT && *p != '\\')
6332 TRACE(("argstr: evalvar('%s')\n", p));
6333 p = evalvar(p, flags | inquotes, var_str_list);
6334 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6337 expbackq(argbackq->n, flags | inquotes);
6338 argbackq = argbackq->next;
6340 #if ENABLE_SH_MATH_SUPPORT
6343 expari(flags | inquotes);
6352 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6353 char *pattern, int quotes, int zero)
6362 const char *s = loc2;
6369 match = pmatch(pattern, s);
6374 if (quotes && (unsigned char)*loc == CTLESC)
6383 scanright(char *startp, char *rmesc, char *rmescend,
6384 char *pattern, int quotes, int match_at_start)
6386 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6387 int try2optimize = match_at_start;
6393 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6394 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6395 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6397 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6398 * and on each iteration they go back two/one char until they reach the beginning.
6399 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6401 /* TODO: document in what other circumstances we are called. */
6403 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6406 const char *s = loc2;
6407 if (match_at_start) {
6411 match = pmatch(pattern, s);
6412 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6416 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6418 /* Maybe we can optimize this:
6419 * if pattern ends with unescaped *, we can avoid checking
6420 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6421 * it wont match truncated "raw_value_of_" strings too.
6423 unsigned plen = strlen(pattern);
6424 /* Does it end with "*"? */
6425 if (plen != 0 && pattern[--plen] == '*') {
6426 /* "xxxx*" is not escaped */
6427 /* "xxx\*" is escaped */
6428 /* "xx\\*" is not escaped */
6429 /* "x\\\*" is escaped */
6431 while (plen != 0 && pattern[--plen] == '\\')
6434 break; /* ends with unescaped "*" */
6442 esc = esclen(startp, loc);
6453 static void varunset(const char *, const char *, const char *, int) NORETURN;
6455 varunset(const char *end, const char *var, const char *umsg, int varflags)
6461 msg = "parameter not set";
6463 if ((unsigned char)*end == CTLENDVAR) {
6464 if (varflags & VSNUL)
6470 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6474 subevalvar(char *p, char *varname, int strloc, int subtype,
6475 int startloc, int varflags, int flag, struct strlist *var_str_list)
6477 struct nodelist *saveargbackq = argbackq;
6478 int quotes = flag & QUOTES_ESC;
6481 char *rmesc, *rmescend;
6483 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6484 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6485 int amount, resetloc;
6486 IF_ASH_BASH_COMPAT(int workloc;)
6488 char *(*scan)(char*, char*, char*, char*, int, int);
6490 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6491 // p, varname, strloc, subtype, startloc, varflags, quotes);
6493 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6494 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6496 STPUTC('\0', expdest);
6497 argbackq = saveargbackq;
6498 startp = (char *)stackblock() + startloc;
6502 setvar0(varname, startp);
6503 amount = startp - expdest;
6504 STADJUST(amount, expdest);
6508 varunset(p, varname, startp, varflags);
6511 #if ENABLE_ASH_BASH_COMPAT
6513 //TODO: support more general format ${v:EXPR:EXPR},
6514 // where EXPR follows $(()) rules
6515 loc = str = stackblock() + strloc;
6516 /* Read POS in ${var:POS:LEN} */
6517 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6518 len = str - startp - 1;
6520 /* *loc != '\0', guaranteed by parser */
6524 /* Adjust the length by the number of escapes */
6525 for (ptr = startp; ptr < (str - 1); ptr++) {
6526 if ((unsigned char)*ptr == CTLESC) {
6534 if (*loc++ == ':') {
6538 /* Skip POS in ${var:POS:LEN} */
6540 while (*loc && *loc != ':') {
6542 * bash complains on: var=qwe; echo ${var:1a:123}
6544 ash_msg_and_raise_error(msg_illnum, str);
6548 if (*loc++ == ':') {
6553 /* ${VAR:$((-n)):l} starts n chars from the end */
6554 pos = orig_len + pos;
6556 if ((unsigned)pos >= orig_len) {
6557 /* apart from obvious ${VAR:999999:l},
6558 * covers ${VAR:$((-9999999)):l} - result is ""
6564 if (len > (orig_len - pos))
6565 len = orig_len - pos;
6567 for (str = startp; pos; str++, pos--) {
6568 if (quotes && (unsigned char)*str == CTLESC)
6571 for (loc = startp; len; len--) {
6572 if (quotes && (unsigned char)*str == CTLESC)
6577 amount = loc - expdest;
6578 STADJUST(amount, expdest);
6583 resetloc = expdest - (char *)stackblock();
6585 /* We'll comeback here if we grow the stack while handling
6586 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6587 * stack will need rebasing, and we'll need to remove our work
6590 IF_ASH_BASH_COMPAT(restart:)
6592 amount = expdest - ((char *)stackblock() + resetloc);
6593 STADJUST(-amount, expdest);
6594 startp = (char *)stackblock() + startloc;
6597 rmescend = (char *)stackblock() + strloc;
6599 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6600 if (rmesc != startp) {
6602 startp = (char *)stackblock() + startloc;
6606 str = (char *)stackblock() + strloc;
6608 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6609 * The result is a_\_z_c (not a\_\_z_c)!
6611 * The search pattern and replace string treat backslashes differently!
6612 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6613 * and string. It's only used on the first call.
6615 preglob(str, IF_ASH_BASH_COMPAT(
6616 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6617 RMESCAPE_SLASH :) 0);
6619 #if ENABLE_ASH_BASH_COMPAT
6620 workloc = expdest - (char *)stackblock();
6621 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6625 repl = strchr(str, CTLESC);
6631 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6633 /* If there's no pattern to match, return the expansion unmolested */
6642 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6643 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6645 /* No match, advance */
6646 char *restart_detect = stackblock();
6648 STPUTC(*idx, expdest);
6649 if (quotes && (unsigned char)*idx == CTLESC) {
6652 STPUTC(*idx, expdest);
6654 if (stackblock() != restart_detect)
6659 /* continue; - prone to quadratic behavior, smarter code: */
6662 if (str[0] == '*') {
6663 /* Pattern is "*foo". If "*foo" does not match "long_string",
6664 * it would never match "ong_string" etc, no point in trying.
6671 if (subtype == VSREPLACEALL) {
6673 if (quotes && (unsigned char)*idx == CTLESC)
6682 //bb_error_msg("repl:'%s'", repl);
6683 for (loc = (char*)repl; *loc; loc++) {
6684 char *restart_detect = stackblock();
6685 if (quotes && *loc == '\\') {
6686 STPUTC(CTLESC, expdest);
6689 STPUTC(*loc, expdest);
6690 if (stackblock() != restart_detect)
6695 if (subtype == VSREPLACE) {
6696 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6698 char *restart_detect = stackblock();
6699 STPUTC(*idx, expdest);
6700 if (stackblock() != restart_detect)
6709 /* We've put the replaced text into a buffer at workloc, now
6710 * move it to the right place and adjust the stack.
6712 STPUTC('\0', expdest);
6713 startp = (char *)stackblock() + startloc;
6714 memmove(startp, (char *)stackblock() + workloc, len + 1);
6715 //bb_error_msg("startp:'%s'", startp);
6716 amount = expdest - (startp + len);
6717 STADJUST(-amount, expdest);
6720 #endif /* ENABLE_ASH_BASH_COMPAT */
6722 subtype -= VSTRIMRIGHT;
6724 if (subtype < 0 || subtype > 7)
6727 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6728 zero = subtype >> 1;
6729 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6730 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6732 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6735 memmove(startp, loc, str - loc);
6736 loc = startp + (str - loc) - 1;
6739 amount = loc - expdest;
6740 STADJUST(amount, expdest);
6746 * Add the value of a specialized variable to the stack string.
6747 * name parameter (examples):
6748 * ash -c 'echo $1' name:'1='
6749 * ash -c 'echo $qwe' name:'qwe='
6750 * ash -c 'echo $$' name:'$='
6751 * ash -c 'echo ${$}' name:'$='
6752 * ash -c 'echo ${$##q}' name:'$=q'
6753 * ash -c 'echo ${#$}' name:'$='
6754 * note: examples with bad shell syntax:
6755 * ash -c 'echo ${#$1}' name:'$=1'
6756 * ash -c 'echo ${#1#}' name:'1=#'
6758 static NOINLINE ssize_t
6759 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6766 int quoted = *quotedp;
6767 int subtype = varflags & VSTYPE;
6768 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6769 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6772 sep = (flags & EXP_FULL) << CHAR_BIT;
6773 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6783 num = shellparam.nparam;
6791 goto check_1char_name;
6793 expdest = makestrspace(NOPTS, expdest);
6794 for (i = NOPTS - 1; i >= 0; i--) {
6796 USTPUTC(optletters(i), expdest);
6802 /* handles cases similar to ${#$1} */
6803 if (name[2] != '\0')
6804 raise_error_syntax("bad substitution");
6817 sep |= ifsset() ? ifsval()[0] : ' ';
6824 while ((p = *ap++) != NULL) {
6825 len += strtodest(p, syntax, quotes);
6829 memtodest(&sepc, 1, syntax, quotes);
6844 num = atoi(name); /* number(name) fails on ${N#str} etc */
6845 if (num < 0 || num > shellparam.nparam)
6847 p = num ? shellparam.p[num - 1] : arg0;
6850 /* NB: name has form "VAR=..." */
6852 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6853 * which should be considered before we check variables. */
6855 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6859 str = var_str_list->text;
6860 eq = strchr(str, '=');
6861 if (!eq) /* stop at first non-assignment */
6864 if (name_len == (unsigned)(eq - str)
6865 && strncmp(str, name, name_len) == 0
6868 /* goto value; - WRONG! */
6869 /* think "A=1 A=2 B=$A" */
6871 var_str_list = var_str_list->next;
6872 } while (var_str_list);
6876 p = lookupvar(name);
6881 len = strtodest(p, syntax, quotes);
6882 #if ENABLE_UNICODE_SUPPORT
6883 if (subtype == VSLENGTH && len > 0) {
6884 reinit_unicode_for_ash();
6885 if (unicode_status == UNICODE_ON) {
6886 STADJUST(-len, expdest);
6888 len = unicode_strlen(p);
6896 STADJUST(-len, expdest);
6901 * Expand a variable, and return a pointer to the next character in the
6905 evalvar(char *p, int flag, struct strlist *var_str_list)
6916 varflags = (unsigned char) *p++;
6917 subtype = varflags & VSTYPE;
6920 raise_error_syntax("bad substitution");
6922 quoted = flag & EXP_QUOTED;
6924 easy = (!quoted || (*var == '@' && shellparam.nparam));
6925 startloc = expdest - (char *)stackblock();
6926 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6929 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6930 if (varflags & VSNUL)
6933 if (subtype == VSPLUS) {
6934 varlen = -1 - varlen;
6938 if (subtype == VSMINUS) {
6943 flag | EXP_TILDE | EXP_WORD,
6951 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6955 subevalvar(p, var, 0, subtype, startloc, varflags,
6956 flag & ~QUOTES_ESC, var_str_list);
6959 * Remove any recorded regions beyond
6962 removerecordregions(startloc);
6966 if (varlen < 0 && uflag)
6967 varunset(p, var, 0, 0);
6969 if (subtype == VSLENGTH) {
6970 cvtnum(varlen > 0 ? varlen : 0);
6974 if (subtype == VSNORMAL) {
6978 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6987 case VSTRIMRIGHTMAX:
6988 #if ENABLE_ASH_BASH_COMPAT
7001 * Terminate the string and start recording the pattern
7004 STPUTC('\0', expdest);
7005 patloc = expdest - (char *)stackblock();
7006 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7007 startloc, varflags, flag, var_str_list)) {
7008 int amount = expdest - (
7009 (char *)stackblock() + patloc - 1
7011 STADJUST(-amount, expdest);
7013 /* Remove any recorded regions beyond start of variable */
7014 removerecordregions(startloc);
7019 if (subtype != VSNORMAL) { /* skip to end of alternative */
7022 unsigned char c = *p++;
7025 else if (c == CTLBACKQ) {
7027 argbackq = argbackq->next;
7028 } else if (c == CTLVAR) {
7029 if ((*p++ & VSTYPE) != VSNORMAL)
7031 } else if (c == CTLENDVAR) {
7041 * Add a file name to the list.
7044 addfname(const char *name)
7048 sp = stzalloc(sizeof(*sp));
7049 sp->text = sstrdup(name);
7051 exparg.lastp = &sp->next;
7054 /* If we want to use glob() from libc... */
7055 #if !ENABLE_ASH_INTERNAL_GLOB
7057 /* Add the result of glob() to the list */
7059 addglob(const glob_t *pglob)
7061 char **p = pglob->gl_pathv;
7068 expandmeta(struct strlist *str /*, int flag*/)
7070 /* TODO - EXP_REDIR */
7080 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7095 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7096 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7097 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7099 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7100 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7101 // Which means you need to unescape the string, right? Not so fast:
7102 // if there _is_ a file named "file\?" (with backslash), it is returned
7103 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7104 // You DONT KNOW by looking at the result whether you need to unescape it.
7106 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7107 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7108 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7109 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7110 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7111 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7112 i = glob(p, 0, NULL, &pglob);
7113 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7118 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7119 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7120 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7132 *exparg.lastp = str;
7133 rmescapes(str->text, 0);
7134 exparg.lastp = &str->next;
7136 default: /* GLOB_NOSPACE */
7139 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7146 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7149 * Do metacharacter (i.e. *, ?, [...]) expansion.
7152 expmeta(char *expdir, char *enddir, char *name)
7168 for (p = name; esc = 0, *p; p += esc + 1) {
7169 if (*p == '*' || *p == '?')
7171 else if (*p == '[') {
7178 if (*q == '/' || *q == '\0')
7188 if (p[esc] == '/') {
7191 start = p + esc + 1;
7195 if (metaflag == 0) { /* we've reached the end of the file name */
7196 if (enddir != expdir)
7204 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7215 } while (p < start);
7217 if (enddir == expdir) {
7219 } else if (enddir == expdir + 1 && *expdir == '/') {
7228 if (enddir != expdir)
7230 if (*endname == 0) {
7243 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7244 if (dp->d_name[0] == '.' && !matchdot)
7246 if (pmatch(start, dp->d_name)) {
7248 strcpy(enddir, dp->d_name);
7251 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7254 expmeta(expdir, p, endname);
7260 endname[-esc - 1] = esc ? '\\' : '/';
7263 static struct strlist *
7264 msort(struct strlist *list, int len)
7266 struct strlist *p, *q = NULL;
7267 struct strlist **lpp;
7275 for (n = half; --n >= 0;) {
7279 q->next = NULL; /* terminate first half of list */
7280 q = msort(list, half); /* sort first half of list */
7281 p = msort(p, len - half); /* sort second half */
7284 #if ENABLE_LOCALE_SUPPORT
7285 if (strcoll(p->text, q->text) < 0)
7287 if (strcmp(p->text, q->text) < 0)
7311 * Sort the results of file name expansion. It calculates the number of
7312 * strings to sort and then calls msort (short for merge sort) to do the
7315 static struct strlist *
7316 expsort(struct strlist *str)
7322 for (sp = str; sp; sp = sp->next)
7324 return msort(str, len);
7328 expandmeta(struct strlist *str /*, int flag*/)
7330 static const char metachars[] ALIGN1 = {
7333 /* TODO - EXP_REDIR */
7337 struct strlist **savelastp;
7343 if (!strpbrk(str->text, metachars))
7345 savelastp = exparg.lastp;
7348 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7350 int i = strlen(str->text);
7351 //BUGGY estimation of how long expanded name can be
7352 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7354 expmeta(expdir, expdir, p);
7359 if (exparg.lastp == savelastp) {
7364 *exparg.lastp = str;
7365 rmescapes(str->text, 0);
7366 exparg.lastp = &str->next;
7368 *exparg.lastp = NULL;
7369 *savelastp = sp = expsort(*savelastp);
7370 while (sp->next != NULL)
7372 exparg.lastp = &sp->next;
7377 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7380 * Perform variable substitution and command substitution on an argument,
7381 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7382 * perform splitting and file name expansion. When arglist is NULL, perform
7383 * here document expansion.
7386 expandarg(union node *arg, struct arglist *arglist, int flag)
7391 argbackq = arg->narg.backquote;
7392 STARTSTACKSTR(expdest);
7393 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7394 argstr(arg->narg.text, flag,
7395 /* var_str_list: */ arglist ? arglist->list : NULL);
7396 p = _STPUTC('\0', expdest);
7398 if (arglist == NULL) {
7399 /* here document expanded */
7402 p = grabstackstr(p);
7403 TRACE(("expandarg: p:'%s'\n", p));
7404 exparg.lastp = &exparg.list;
7408 if (flag & EXP_FULL) {
7409 ifsbreakup(p, &exparg);
7410 *exparg.lastp = NULL;
7411 exparg.lastp = &exparg.list;
7412 expandmeta(exparg.list /*, flag*/);
7414 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7416 TRACE(("expandarg: rmescapes:'%s'\n", p));
7418 sp = stzalloc(sizeof(*sp));
7421 exparg.lastp = &sp->next;
7423 *exparg.lastp = NULL;
7425 *arglist->lastp = exparg.list;
7426 arglist->lastp = exparg.lastp;
7434 * Expand shell variables and backquotes inside a here document.
7437 expandhere(union node *arg, int fd)
7439 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7440 full_write(fd, stackblock(), expdest - (char *)stackblock());
7444 * Returns true if the pattern matches the string.
7447 patmatch(char *pattern, const char *string)
7449 return pmatch(preglob(pattern, 0), string);
7453 * See if a pattern matches in a case statement.
7456 casematch(union node *pattern, char *val)
7458 struct stackmark smark;
7461 setstackmark(&smark);
7462 argbackq = pattern->narg.backquote;
7463 STARTSTACKSTR(expdest);
7464 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7465 /* var_str_list: */ NULL);
7466 STACKSTRNUL(expdest);
7468 result = patmatch(stackblock(), val);
7469 popstackmark(&smark);
7474 /* ============ find_command */
7478 int (*builtin)(int, char **) FAST_FUNC;
7479 /* unsigned flags; */
7481 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7482 /* "regular" builtins always take precedence over commands,
7483 * regardless of PATH=....%builtin... position */
7484 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7485 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7488 smallint cmdtype; /* CMDxxx */
7491 /* index >= 0 for commands without path (slashes) */
7492 /* (TODO: what exactly does the value mean? PATH position?) */
7493 /* index == -1 for commands with slashes */
7494 /* index == (-2 - applet_no) for NOFORK applets */
7495 const struct builtincmd *cmd;
7496 struct funcnode *func;
7499 /* values of cmdtype */
7500 #define CMDUNKNOWN -1 /* no entry in table for command */
7501 #define CMDNORMAL 0 /* command is an executable program */
7502 #define CMDFUNCTION 1 /* command is a shell function */
7503 #define CMDBUILTIN 2 /* command is a shell builtin */
7505 /* action to find_command() */
7506 #define DO_ERR 0x01 /* prints errors */
7507 #define DO_ABS 0x02 /* checks absolute paths */
7508 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7509 #define DO_ALTPATH 0x08 /* using alternate path */
7510 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7512 static void find_command(char *, struct cmdentry *, int, const char *);
7515 /* ============ Hashing commands */
7518 * When commands are first encountered, they are entered in a hash table.
7519 * This ensures that a full path search will not have to be done for them
7520 * on each invocation.
7522 * We should investigate converting to a linear search, even though that
7523 * would make the command name "hash" a misnomer.
7527 struct tblentry *next; /* next entry in hash chain */
7528 union param param; /* definition of builtin function */
7529 smallint cmdtype; /* CMDxxx */
7530 char rehash; /* if set, cd done since entry created */
7531 char cmdname[1]; /* name of command */
7534 static struct tblentry **cmdtable;
7535 #define INIT_G_cmdtable() do { \
7536 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7539 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7543 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7545 #if ENABLE_FEATURE_SH_STANDALONE
7546 if (applet_no >= 0) {
7547 if (APPLET_IS_NOEXEC(applet_no)) {
7551 run_applet_no_and_exit(applet_no, argv);
7553 /* re-exec ourselves with the new arguments */
7554 execve(bb_busybox_exec_path, argv, envp);
7555 /* If they called chroot or otherwise made the binary no longer
7556 * executable, fall through */
7563 execve(cmd, argv, envp);
7564 } while (errno == EINTR);
7566 execve(cmd, argv, envp);
7568 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7569 /* Run "cmd" as a shell script:
7570 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7571 * "If the execve() function fails with ENOEXEC, the shell
7572 * shall execute a command equivalent to having a shell invoked
7573 * with the command name as its first operand,
7574 * with any remaining arguments passed to the new shell"
7576 * That is, do not use $SHELL, user's shell, or /bin/sh;
7577 * just call ourselves.
7579 * Note that bash reads ~80 chars of the file, and if it sees
7580 * a zero byte before it sees newline, it doesn't try to
7581 * interpret it, but fails with "cannot execute binary file"
7582 * message and exit code 126. For one, this prevents attempts
7583 * to interpret foreign ELF binaries as shell scripts.
7586 cmd = (char*) bb_busybox_exec_path;
7587 /* NB: this is only possible because all callers of shellexec()
7588 * ensure that the argv[-1] slot exists!
7591 argv[0] = (char*) "ash";
7597 * Exec a program. Never returns. If you change this routine, you may
7598 * have to change the find_command routine as well.
7599 * argv[-1] must exist and be writable! See tryexec() for why.
7601 static void shellexec(char **, const char *, int) NORETURN;
7603 shellexec(char **argv, const char *path, int idx)
7609 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7611 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7612 if (strchr(argv[0], '/') != NULL
7613 #if ENABLE_FEATURE_SH_STANDALONE
7614 || (applet_no = find_applet_by_name(argv[0])) >= 0
7617 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7618 if (applet_no >= 0) {
7619 /* We tried execing ourself, but it didn't work.
7620 * Maybe /proc/self/exe doesn't exist?
7629 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7630 if (--idx < 0 && pathopt == NULL) {
7631 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7632 if (errno != ENOENT && errno != ENOTDIR)
7639 /* Map to POSIX errors */
7651 exitstatus = exerrno;
7652 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7653 argv[0], e, suppress_int));
7654 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7659 printentry(struct tblentry *cmdp)
7665 idx = cmdp->param.index;
7668 name = path_advance(&path, cmdp->cmdname);
7670 } while (--idx >= 0);
7671 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7675 * Clear out command entries. The argument specifies the first entry in
7676 * PATH which has changed.
7679 clearcmdentry(int firstchange)
7681 struct tblentry **tblp;
7682 struct tblentry **pp;
7683 struct tblentry *cmdp;
7686 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7688 while ((cmdp = *pp) != NULL) {
7689 if ((cmdp->cmdtype == CMDNORMAL &&
7690 cmdp->param.index >= firstchange)
7691 || (cmdp->cmdtype == CMDBUILTIN &&
7692 builtinloc >= firstchange)
7705 * Locate a command in the command hash table. If "add" is nonzero,
7706 * add the command to the table if it is not already present. The
7707 * variable "lastcmdentry" is set to point to the address of the link
7708 * pointing to the entry, so that delete_cmd_entry can delete the
7711 * Interrupts must be off if called with add != 0.
7713 static struct tblentry **lastcmdentry;
7715 static struct tblentry *
7716 cmdlookup(const char *name, int add)
7718 unsigned int hashval;
7720 struct tblentry *cmdp;
7721 struct tblentry **pp;
7724 hashval = (unsigned char)*p << 4;
7726 hashval += (unsigned char)*p++;
7728 pp = &cmdtable[hashval % CMDTABLESIZE];
7729 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7730 if (strcmp(cmdp->cmdname, name) == 0)
7734 if (add && cmdp == NULL) {
7735 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7737 /* + 1 - already done because
7738 * tblentry::cmdname is char[1] */);
7739 /*cmdp->next = NULL; - ckzalloc did it */
7740 cmdp->cmdtype = CMDUNKNOWN;
7741 strcpy(cmdp->cmdname, name);
7748 * Delete the command entry returned on the last lookup.
7751 delete_cmd_entry(void)
7753 struct tblentry *cmdp;
7756 cmdp = *lastcmdentry;
7757 *lastcmdentry = cmdp->next;
7758 if (cmdp->cmdtype == CMDFUNCTION)
7759 freefunc(cmdp->param.func);
7765 * Add a new command entry, replacing any existing command entry for
7766 * the same name - except special builtins.
7769 addcmdentry(char *name, struct cmdentry *entry)
7771 struct tblentry *cmdp;
7773 cmdp = cmdlookup(name, 1);
7774 if (cmdp->cmdtype == CMDFUNCTION) {
7775 freefunc(cmdp->param.func);
7777 cmdp->cmdtype = entry->cmdtype;
7778 cmdp->param = entry->u;
7782 static int FAST_FUNC
7783 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7785 struct tblentry **pp;
7786 struct tblentry *cmdp;
7788 struct cmdentry entry;
7791 if (nextopt("r") != '\0') {
7796 if (*argptr == NULL) {
7797 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7798 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7799 if (cmdp->cmdtype == CMDNORMAL)
7807 while ((name = *argptr) != NULL) {
7808 cmdp = cmdlookup(name, 0);
7810 && (cmdp->cmdtype == CMDNORMAL
7811 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7815 find_command(name, &entry, DO_ERR, pathval());
7816 if (entry.cmdtype == CMDUNKNOWN)
7824 * Called when a cd is done. Marks all commands so the next time they
7825 * are executed they will be rehashed.
7830 struct tblentry **pp;
7831 struct tblentry *cmdp;
7833 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7834 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7835 if (cmdp->cmdtype == CMDNORMAL
7836 || (cmdp->cmdtype == CMDBUILTIN
7837 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7847 * Fix command hash table when PATH changed.
7848 * Called before PATH is changed. The argument is the new value of PATH;
7849 * pathval() still returns the old value at this point.
7850 * Called with interrupts off.
7852 static void FAST_FUNC
7853 changepath(const char *new)
7861 firstchange = 9999; /* assume no change */
7867 if ((*old == '\0' && *new == ':')
7868 || (*old == ':' && *new == '\0')
7872 old = new; /* ignore subsequent differences */
7876 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7883 if (builtinloc < 0 && idx_bltin >= 0)
7884 builtinloc = idx_bltin; /* zap builtins */
7885 if (builtinloc >= 0 && idx_bltin < 0)
7887 clearcmdentry(firstchange);
7888 builtinloc = idx_bltin;
7913 #if ENABLE_ASH_BASH_COMPAT
7924 typedef smallint token_id_t;
7926 /* Nth bit indicates if token marks the end of a list */
7929 /* 0 */ | (1u << TEOF)
7930 /* 1 */ | (0u << TNL)
7931 /* 2 */ | (0u << TREDIR)
7932 /* 3 */ | (0u << TWORD)
7933 /* 4 */ | (0u << TSEMI)
7934 /* 5 */ | (0u << TBACKGND)
7935 /* 6 */ | (0u << TAND)
7936 /* 7 */ | (0u << TOR)
7937 /* 8 */ | (0u << TPIPE)
7938 /* 9 */ | (0u << TLP)
7939 /* 10 */ | (1u << TRP)
7940 /* 11 */ | (1u << TENDCASE)
7941 /* 12 */ | (1u << TENDBQUOTE)
7942 /* 13 */ | (0u << TNOT)
7943 /* 14 */ | (0u << TCASE)
7944 /* 15 */ | (1u << TDO)
7945 /* 16 */ | (1u << TDONE)
7946 /* 17 */ | (1u << TELIF)
7947 /* 18 */ | (1u << TELSE)
7948 /* 19 */ | (1u << TESAC)
7949 /* 20 */ | (1u << TFI)
7950 /* 21 */ | (0u << TFOR)
7951 #if ENABLE_ASH_BASH_COMPAT
7952 /* 22 */ | (0u << TFUNCTION)
7954 /* 23 */ | (0u << TIF)
7955 /* 24 */ | (0u << TIN)
7956 /* 25 */ | (1u << TTHEN)
7957 /* 26 */ | (0u << TUNTIL)
7958 /* 27 */ | (0u << TWHILE)
7959 /* 28 */ | (0u << TBEGIN)
7960 /* 29 */ | (1u << TEND)
7961 , /* thus far 29 bits used */
7964 static const char *const tokname_array[] = {
7978 #define KWDOFFSET 13
7979 /* the following are keywords */
7989 #if ENABLE_ASH_BASH_COMPAT
8001 /* Wrapper around strcmp for qsort/bsearch/... */
8003 pstrcmp(const void *a, const void *b)
8005 return strcmp((char*)a, *(char**)b);
8008 static const char *const *
8009 findkwd(const char *s)
8011 return bsearch(s, tokname_array + KWDOFFSET,
8012 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8013 sizeof(tokname_array[0]), pstrcmp);
8017 * Locate and print what a word is...
8020 describe_command(char *command, const char *path, int describe_command_verbose)
8022 struct cmdentry entry;
8023 struct tblentry *cmdp;
8024 #if ENABLE_ASH_ALIAS
8025 const struct alias *ap;
8028 path = path ? path : pathval();
8030 if (describe_command_verbose) {
8034 /* First look at the keywords */
8035 if (findkwd(command)) {
8036 out1str(describe_command_verbose ? " is a shell keyword" : command);
8040 #if ENABLE_ASH_ALIAS
8041 /* Then look at the aliases */
8042 ap = lookupalias(command, 0);
8044 if (!describe_command_verbose) {
8049 out1fmt(" is an alias for %s", ap->val);
8053 /* Then check if it is a tracked alias */
8054 cmdp = cmdlookup(command, 0);
8056 entry.cmdtype = cmdp->cmdtype;
8057 entry.u = cmdp->param;
8059 /* Finally use brute force */
8060 find_command(command, &entry, DO_ABS, path);
8063 switch (entry.cmdtype) {
8065 int j = entry.u.index;
8071 p = path_advance(&path, command);
8075 if (describe_command_verbose) {
8077 (cmdp ? " a tracked alias for" : nullstr), p
8086 if (describe_command_verbose) {
8087 out1str(" is a shell function");
8094 if (describe_command_verbose) {
8095 out1fmt(" is a %sshell builtin",
8096 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8097 "special " : nullstr
8105 if (describe_command_verbose) {
8106 out1str(": not found\n");
8115 static int FAST_FUNC
8116 typecmd(int argc UNUSED_PARAM, char **argv)
8122 /* type -p ... ? (we don't bother checking for 'p') */
8123 if (argv[1] && argv[1][0] == '-') {
8128 err |= describe_command(argv[i++], NULL, verbose);
8133 #if ENABLE_ASH_CMDCMD
8134 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8136 parse_command_args(char **argv, const char **path)
8149 if (c == '-' && !*cp) {
8157 *path = bb_default_path;
8160 /* run 'typecmd' for other options */
8169 static int FAST_FUNC
8170 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8178 const char *path = NULL;
8180 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8181 * never reaches this function.
8184 while ((c = nextopt("pvV")) != '\0')
8186 verify |= VERIFY_VERBOSE;
8188 /*verify |= VERIFY_BRIEF*/;
8194 path = bb_default_path;
8196 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8198 if (/*verify && */ cmd)
8199 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8206 /*static int funcblocksize; // size of structures in function */
8207 /*static int funcstringsize; // size of strings in node */
8208 static void *funcblock; /* block to allocate function from */
8209 static char *funcstring_end; /* end of block to allocate strings from */
8211 /* flags in argument to evaltree */
8212 #define EV_EXIT 01 /* exit after evaluating tree */
8213 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8215 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8216 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8217 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8218 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8219 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8220 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8221 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8222 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8223 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8224 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8225 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8226 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8227 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8228 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8229 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8230 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8231 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8232 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8233 #if ENABLE_ASH_BASH_COMPAT
8234 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8236 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8237 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8238 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8239 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8240 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8241 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8242 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8243 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8244 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8247 static int calcsize(int funcblocksize, union node *n);
8250 sizenodelist(int funcblocksize, struct nodelist *lp)
8253 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8254 funcblocksize = calcsize(funcblocksize, lp->n);
8257 return funcblocksize;
8261 calcsize(int funcblocksize, union node *n)
8264 return funcblocksize;
8265 funcblocksize += nodesize[n->type];
8268 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8269 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8270 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8273 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8278 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8279 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8286 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8287 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8290 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8291 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8292 funcblocksize = calcsize(funcblocksize, n->nif.test);
8295 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8296 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8297 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8300 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8301 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8304 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8305 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8306 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8310 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8311 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8312 funcblocksize = calcsize(funcblocksize, n->narg.next);
8315 #if ENABLE_ASH_BASH_COMPAT
8322 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8323 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8327 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8328 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8332 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8333 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8336 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8339 return funcblocksize;
8343 nodeckstrdup(char *s)
8345 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8346 return strcpy(funcstring_end, s);
8349 static union node *copynode(union node *);
8351 static struct nodelist *
8352 copynodelist(struct nodelist *lp)
8354 struct nodelist *start;
8355 struct nodelist **lpp;
8360 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8361 (*lpp)->n = copynode(lp->n);
8363 lpp = &(*lpp)->next;
8370 copynode(union node *n)
8377 funcblock = (char *) funcblock + nodesize[n->type];
8381 new->ncmd.redirect = copynode(n->ncmd.redirect);
8382 new->ncmd.args = copynode(n->ncmd.args);
8383 new->ncmd.assign = copynode(n->ncmd.assign);
8386 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8387 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8392 new->nredir.redirect = copynode(n->nredir.redirect);
8393 new->nredir.n = copynode(n->nredir.n);
8400 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8401 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8404 new->nif.elsepart = copynode(n->nif.elsepart);
8405 new->nif.ifpart = copynode(n->nif.ifpart);
8406 new->nif.test = copynode(n->nif.test);
8409 new->nfor.var = nodeckstrdup(n->nfor.var);
8410 new->nfor.body = copynode(n->nfor.body);
8411 new->nfor.args = copynode(n->nfor.args);
8414 new->ncase.cases = copynode(n->ncase.cases);
8415 new->ncase.expr = copynode(n->ncase.expr);
8418 new->nclist.body = copynode(n->nclist.body);
8419 new->nclist.pattern = copynode(n->nclist.pattern);
8420 new->nclist.next = copynode(n->nclist.next);
8424 new->narg.backquote = copynodelist(n->narg.backquote);
8425 new->narg.text = nodeckstrdup(n->narg.text);
8426 new->narg.next = copynode(n->narg.next);
8429 #if ENABLE_ASH_BASH_COMPAT
8436 new->nfile.fname = copynode(n->nfile.fname);
8437 new->nfile.fd = n->nfile.fd;
8438 new->nfile.next = copynode(n->nfile.next);
8442 new->ndup.vname = copynode(n->ndup.vname);
8443 new->ndup.dupfd = n->ndup.dupfd;
8444 new->ndup.fd = n->ndup.fd;
8445 new->ndup.next = copynode(n->ndup.next);
8449 new->nhere.doc = copynode(n->nhere.doc);
8450 new->nhere.fd = n->nhere.fd;
8451 new->nhere.next = copynode(n->nhere.next);
8454 new->nnot.com = copynode(n->nnot.com);
8457 new->type = n->type;
8462 * Make a copy of a parse tree.
8464 static struct funcnode *
8465 copyfunc(union node *n)
8470 /*funcstringsize = 0;*/
8471 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8472 f = ckzalloc(blocksize /* + funcstringsize */);
8473 funcblock = (char *) f + offsetof(struct funcnode, n);
8474 funcstring_end = (char *) f + blocksize;
8476 /* f->count = 0; - ckzalloc did it */
8481 * Define a shell function.
8484 defun(union node *func)
8486 struct cmdentry entry;
8489 entry.cmdtype = CMDFUNCTION;
8490 entry.u.func = copyfunc(func);
8491 addcmdentry(func->narg.text, &entry);
8495 /* Reasons for skipping commands (see comment on breakcmd routine) */
8496 #define SKIPBREAK (1 << 0)
8497 #define SKIPCONT (1 << 1)
8498 #define SKIPFUNC (1 << 2)
8499 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8500 static int skipcount; /* number of levels to skip */
8501 static int funcnest; /* depth of function calls */
8502 static int loopnest; /* current loop nesting level */
8504 /* Forward decl way out to parsing code - dotrap needs it */
8505 static int evalstring(char *s, int flags);
8507 /* Called to execute a trap.
8508 * Single callsite - at the end of evaltree().
8509 * If we return non-zero, evaltree raises EXEXIT exception.
8511 * Perhaps we should avoid entering new trap handlers
8512 * while we are executing a trap handler. [is it a TODO?]
8519 uint8_t last_status;
8524 last_status = exitstatus;
8528 TRACE(("dotrap entered\n"));
8529 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8541 /* non-trapped SIGINT is handled separately by raise_interrupt,
8542 * don't upset it by resetting gotsig[SIGINT-1] */
8543 if (sig == SIGINT && !p)
8546 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8552 exitstatus = last_status;
8553 TRACE(("dotrap returns\n"));
8556 /* forward declarations - evaluation is fairly recursive business... */
8557 static int evalloop(union node *, int);
8558 static int evalfor(union node *, int);
8559 static int evalcase(union node *, int);
8560 static int evalsubshell(union node *, int);
8561 static void expredir(union node *);
8562 static int evalpipe(union node *, int);
8563 static int evalcommand(union node *, int);
8564 static int evalbltin(const struct builtincmd *, int, char **, int);
8565 static void prehash(union node *);
8568 * Evaluate a parse tree. The value is left in the global variable
8572 evaltree(union node *n, int flags)
8575 int (*evalfn)(union node *, int);
8579 TRACE(("evaltree(NULL) called\n"));
8582 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8589 out1fmt("Node type = %d\n", n->type);
8594 status = !evaltree(n->nnot.com, EV_TESTED);
8597 expredir(n->nredir.redirect);
8598 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8600 status = evaltree(n->nredir.n, flags & EV_TESTED);
8602 if (n->nredir.redirect)
8603 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8606 evalfn = evalcommand;
8608 if (eflag && !(flags & EV_TESTED))
8620 evalfn = evalsubshell;
8633 #error NAND + 1 != NOR
8635 #if NOR + 1 != NSEMI
8636 #error NOR + 1 != NSEMI
8638 unsigned is_or = n->type - NAND;
8641 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8643 if ((!status) == is_or || evalskip)
8649 status = evalfn(n, flags);
8653 status = evaltree(n->nif.test, EV_TESTED);
8660 if (n->nif.elsepart) {
8661 n = n->nif.elsepart;
8668 /* Not necessary. To test it:
8669 * "false; f() { qwerty; }; echo $?" should print 0.
8673 exitstatus = status;
8677 /* Order of checks below is important:
8678 * signal handlers trigger before exit caused by "set -e".
8682 if (checkexit & status)
8683 raise_exception(EXEXIT);
8684 if (flags & EV_EXIT)
8685 raise_exception(EXEXIT);
8687 TRACE(("leaving evaltree (no interrupts)\n"));
8691 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8694 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8699 int skip = evalskip;
8706 if (--skipcount <= 0) {
8717 evalloop(union node *n, int flags)
8728 i = evaltree(n->nbinary.ch1, EV_TESTED);
8730 if (skip == SKIPFUNC)
8734 if (n->type != NWHILE)
8738 status = evaltree(n->nbinary.ch2, flags);
8740 } while (!(skip & ~SKIPCONT));
8747 evalfor(union node *n, int flags)
8749 struct arglist arglist;
8752 struct stackmark smark;
8755 setstackmark(&smark);
8756 arglist.list = NULL;
8757 arglist.lastp = &arglist.list;
8758 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8759 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8761 *arglist.lastp = NULL;
8765 for (sp = arglist.list; sp; sp = sp->next) {
8766 setvar0(n->nfor.var, sp->text);
8767 status = evaltree(n->nfor.body, flags);
8768 if (skiploop() & ~SKIPCONT)
8772 popstackmark(&smark);
8778 evalcase(union node *n, int flags)
8782 struct arglist arglist;
8783 struct stackmark smark;
8786 setstackmark(&smark);
8787 arglist.list = NULL;
8788 arglist.lastp = &arglist.list;
8789 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8790 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8791 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8792 if (casematch(patp, arglist.list->text)) {
8793 /* Ensure body is non-empty as otherwise
8794 * EV_EXIT may prevent us from setting the
8797 if (evalskip == 0 && cp->nclist.body) {
8798 status = evaltree(cp->nclist.body, flags);
8805 popstackmark(&smark);
8811 * Kick off a subshell to evaluate a tree.
8814 evalsubshell(union node *n, int flags)
8817 int backgnd = (n->type == NBACKGND);
8820 expredir(n->nredir.redirect);
8821 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8824 jp = makejob(/*n,*/ 1);
8825 if (forkshell(jp, n, backgnd) == 0) {
8830 flags &= ~EV_TESTED;
8832 redirect(n->nredir.redirect, 0);
8833 evaltreenr(n->nredir.n, flags);
8839 status = waitforjob(jp);
8845 * Compute the names of the files in a redirection list.
8847 static void fixredir(union node *, const char *, int);
8849 expredir(union node *n)
8853 for (redir = n; redir; redir = redir->nfile.next) {
8857 fn.lastp = &fn.list;
8858 switch (redir->type) {
8862 #if ENABLE_ASH_BASH_COMPAT
8867 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8868 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8869 #if ENABLE_ASH_BASH_COMPAT
8873 // By the design of stack allocator, the loop of this kind:
8874 // while true; do while true; do break; done </dev/null; done
8875 // will look like a memory leak: ash plans to free expfname's
8876 // of "/dev/null" as soon as it finishes running the loop
8877 // (in this case, never).
8878 // This "fix" is wrong:
8879 if (redir->nfile.expfname)
8880 stunalloc(redir->nfile.expfname);
8881 // It results in corrupted state of stacked allocations.
8883 redir->nfile.expfname = fn.list->text;
8886 case NTOFD: /* >& */
8887 if (redir->ndup.vname) {
8888 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8889 if (fn.list == NULL)
8890 ash_msg_and_raise_error("redir error");
8891 #if ENABLE_ASH_BASH_COMPAT
8892 //FIXME: we used expandarg with different args!
8893 if (!isdigit_str9(fn.list->text)) {
8894 /* >&file, not >&fd */
8895 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8896 ash_msg_and_raise_error("redir error");
8898 goto store_expfname;
8901 fixredir(redir, fn.list->text, 1);
8909 * Evaluate a pipeline. All the processes in the pipeline are children
8910 * of the process creating the pipeline. (This differs from some versions
8911 * of the shell, which make the last process in a pipeline the parent
8915 evalpipe(union node *n, int flags)
8918 struct nodelist *lp;
8924 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8926 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8930 jp = makejob(/*n,*/ pipelen);
8932 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8936 if (pipe(pip) < 0) {
8938 ash_msg_and_raise_error("pipe call failed");
8941 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8955 evaltreenr(lp->n, flags);
8962 /* Don't want to trigger debugging */
8966 if (n->npipe.pipe_backgnd == 0) {
8967 status = waitforjob(jp);
8968 TRACE(("evalpipe: job done exit status %d\n", status));
8976 * Controls whether the shell is interactive or not.
8979 setinteractive(int on)
8981 static smallint is_interactive;
8983 if (++on == is_interactive)
8985 is_interactive = on;
8989 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8990 if (is_interactive > 1) {
8991 /* Looks like they want an interactive shell */
8992 static smallint did_banner;
8995 /* note: ash and hush share this string */
8996 out1fmt("\n\n%s %s\n"
8997 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9000 "built-in shell (ash)"
9014 setinteractive(iflag);
9016 #if ENABLE_FEATURE_EDITING_VI
9018 line_input_state->flags |= VI_MODE;
9020 line_input_state->flags &= ~VI_MODE;
9022 viflag = 0; /* forcibly keep the option off */
9026 static struct localvar *localvars;
9029 * Called after a function returns.
9030 * Interrupts must be off.
9035 struct localvar *lvp;
9038 while ((lvp = localvars) != NULL) {
9039 localvars = lvp->next;
9041 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9042 if (vp == NULL) { /* $- saved */
9043 memcpy(optlist, lvp->text, sizeof(optlist));
9044 free((char*)lvp->text);
9046 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9047 unsetvar(vp->var_text);
9050 vp->var_func(var_end(lvp->text));
9051 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9052 free((char*)vp->var_text);
9053 vp->flags = lvp->flags;
9054 vp->var_text = lvp->text;
9061 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9063 volatile struct shparam saveparam;
9064 struct localvar *volatile savelocalvars;
9065 struct jmploc *volatile savehandler;
9066 struct jmploc jmploc;
9069 saveparam = shellparam;
9070 savelocalvars = localvars;
9071 savehandler = exception_handler;
9072 e = setjmp(jmploc.loc);
9077 exception_handler = &jmploc;
9079 shellparam.malloced = 0;
9083 shellparam.nparam = argc - 1;
9084 shellparam.p = argv + 1;
9085 #if ENABLE_ASH_GETOPTS
9086 shellparam.optind = 1;
9087 shellparam.optoff = -1;
9089 evaltree(func->n.narg.next, flags & EV_TESTED);
9095 localvars = savelocalvars;
9096 freeparam(&shellparam);
9097 shellparam = saveparam;
9098 exception_handler = savehandler;
9100 evalskip &= ~SKIPFUNC;
9105 * Make a variable a local variable. When a variable is made local, it's
9106 * value and flags are saved in a localvar structure. The saved values
9107 * will be restored when the shell function returns. We handle the name
9108 * "-" as a special case: it makes changes to "set +-options" local
9109 * (options will be restored on return from the function).
9114 struct localvar *lvp;
9117 char *eq = strchr(name, '=');
9120 /* Cater for duplicate "local". Examples:
9121 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9122 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9126 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9130 * it's a duplicate "local VAR" declaration, do nothing
9137 lvp = ckzalloc(sizeof(*lvp));
9138 if (LONE_DASH(name)) {
9140 p = ckmalloc(sizeof(optlist));
9141 lvp->text = memcpy(p, optlist, sizeof(optlist));
9144 vpp = hashvar(name);
9145 vp = *findvar(vpp, name);
9147 /* variable did not exist yet */
9149 setvareq(name, VSTRFIXED);
9151 setvar(name, NULL, VSTRFIXED);
9152 vp = *vpp; /* the new variable */
9153 lvp->flags = VUNSET;
9155 lvp->text = vp->var_text;
9156 lvp->flags = vp->flags;
9157 /* make sure neither "struct var" nor string gets freed
9158 * during (un)setting:
9160 vp->flags |= VSTRFIXED|VTEXTFIXED;
9164 /* "local VAR" unsets VAR: */
9165 setvar0(name, NULL);
9169 lvp->next = localvars;
9176 * The "local" command.
9178 static int FAST_FUNC
9179 localcmd(int argc UNUSED_PARAM, char **argv)
9184 ash_msg_and_raise_error("not in a function");
9187 while ((name = *argv++) != NULL) {
9193 static int FAST_FUNC
9194 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9199 static int FAST_FUNC
9200 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9205 static int FAST_FUNC
9206 execcmd(int argc UNUSED_PARAM, char **argv)
9209 iflag = 0; /* exit on error */
9212 /* We should set up signals for "exec CMD"
9213 * the same way as for "CMD" without "exec".
9214 * But optschanged->setinteractive->setsignal
9215 * still thought we are a root shell. Therefore, for example,
9216 * SIGQUIT is still set to IGN. Fix it:
9220 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9221 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9222 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9224 shellexec(argv + 1, pathval(), 0);
9231 * The return command.
9233 static int FAST_FUNC
9234 returncmd(int argc UNUSED_PARAM, char **argv)
9237 * If called outside a function, do what ksh does;
9238 * skip the rest of the file.
9240 evalskip = SKIPFUNC;
9241 return argv[1] ? number(argv[1]) : exitstatus;
9244 /* Forward declarations for builtintab[] */
9245 static int breakcmd(int, char **) FAST_FUNC;
9246 static int dotcmd(int, char **) FAST_FUNC;
9247 static int evalcmd(int, char **, int) FAST_FUNC;
9248 static int exitcmd(int, char **) FAST_FUNC;
9249 static int exportcmd(int, char **) FAST_FUNC;
9250 #if ENABLE_ASH_GETOPTS
9251 static int getoptscmd(int, char **) FAST_FUNC;
9254 static int helpcmd(int, char **) FAST_FUNC;
9257 static int historycmd(int, char **) FAST_FUNC;
9259 #if ENABLE_SH_MATH_SUPPORT
9260 static int letcmd(int, char **) FAST_FUNC;
9262 static int readcmd(int, char **) FAST_FUNC;
9263 static int setcmd(int, char **) FAST_FUNC;
9264 static int shiftcmd(int, char **) FAST_FUNC;
9265 static int timescmd(int, char **) FAST_FUNC;
9266 static int trapcmd(int, char **) FAST_FUNC;
9267 static int umaskcmd(int, char **) FAST_FUNC;
9268 static int unsetcmd(int, char **) FAST_FUNC;
9269 static int ulimitcmd(int, char **) FAST_FUNC;
9271 #define BUILTIN_NOSPEC "0"
9272 #define BUILTIN_SPECIAL "1"
9273 #define BUILTIN_REGULAR "2"
9274 #define BUILTIN_SPEC_REG "3"
9275 #define BUILTIN_ASSIGN "4"
9276 #define BUILTIN_SPEC_ASSG "5"
9277 #define BUILTIN_REG_ASSG "6"
9278 #define BUILTIN_SPEC_REG_ASSG "7"
9280 /* Stubs for calling non-FAST_FUNC's */
9281 #if ENABLE_ASH_BUILTIN_ECHO
9282 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9284 #if ENABLE_ASH_BUILTIN_PRINTF
9285 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9287 #if ENABLE_ASH_BUILTIN_TEST
9288 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9291 /* Keep these in proper order since it is searched via bsearch() */
9292 static const struct builtincmd builtintab[] = {
9293 { BUILTIN_SPEC_REG "." , dotcmd },
9294 { BUILTIN_SPEC_REG ":" , truecmd },
9295 #if ENABLE_ASH_BUILTIN_TEST
9296 { BUILTIN_REGULAR "[" , testcmd },
9297 # if ENABLE_ASH_BASH_COMPAT
9298 { BUILTIN_REGULAR "[[" , testcmd },
9301 #if ENABLE_ASH_ALIAS
9302 { BUILTIN_REG_ASSG "alias" , aliascmd },
9305 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9307 { BUILTIN_SPEC_REG "break" , breakcmd },
9308 { BUILTIN_REGULAR "cd" , cdcmd },
9309 { BUILTIN_NOSPEC "chdir" , cdcmd },
9310 #if ENABLE_ASH_CMDCMD
9311 { BUILTIN_REGULAR "command" , commandcmd },
9313 { BUILTIN_SPEC_REG "continue", breakcmd },
9314 #if ENABLE_ASH_BUILTIN_ECHO
9315 { BUILTIN_REGULAR "echo" , echocmd },
9317 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9318 { BUILTIN_SPEC_REG "exec" , execcmd },
9319 { BUILTIN_SPEC_REG "exit" , exitcmd },
9320 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9321 { BUILTIN_REGULAR "false" , falsecmd },
9323 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9325 #if ENABLE_ASH_GETOPTS
9326 { BUILTIN_REGULAR "getopts" , getoptscmd },
9328 { BUILTIN_NOSPEC "hash" , hashcmd },
9330 { BUILTIN_NOSPEC "help" , helpcmd },
9333 { BUILTIN_NOSPEC "history" , historycmd },
9336 { BUILTIN_REGULAR "jobs" , jobscmd },
9337 { BUILTIN_REGULAR "kill" , killcmd },
9339 #if ENABLE_SH_MATH_SUPPORT
9340 { BUILTIN_NOSPEC "let" , letcmd },
9342 { BUILTIN_ASSIGN "local" , localcmd },
9343 #if ENABLE_ASH_BUILTIN_PRINTF
9344 { BUILTIN_REGULAR "printf" , printfcmd },
9346 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9347 { BUILTIN_REGULAR "read" , readcmd },
9348 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9349 { BUILTIN_SPEC_REG "return" , returncmd },
9350 { BUILTIN_SPEC_REG "set" , setcmd },
9351 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9352 #if ENABLE_ASH_BASH_COMPAT
9353 { BUILTIN_SPEC_REG "source" , dotcmd },
9355 #if ENABLE_ASH_BUILTIN_TEST
9356 { BUILTIN_REGULAR "test" , testcmd },
9358 { BUILTIN_SPEC_REG "times" , timescmd },
9359 { BUILTIN_SPEC_REG "trap" , trapcmd },
9360 { BUILTIN_REGULAR "true" , truecmd },
9361 { BUILTIN_NOSPEC "type" , typecmd },
9362 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9363 { BUILTIN_REGULAR "umask" , umaskcmd },
9364 #if ENABLE_ASH_ALIAS
9365 { BUILTIN_REGULAR "unalias" , unaliascmd },
9367 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9368 { BUILTIN_REGULAR "wait" , waitcmd },
9371 /* Should match the above table! */
9372 #define COMMANDCMD (builtintab + \
9374 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9375 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9376 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9377 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9378 /* break cd cddir */ 3)
9379 #define EVALCMD (COMMANDCMD + \
9380 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9381 /* continue */ 1 + \
9382 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9384 #define EXECCMD (EVALCMD + \
9388 * Search the table of builtin commands.
9391 pstrcmp1(const void *a, const void *b)
9393 return strcmp((char*)a, *(char**)b + 1);
9395 static struct builtincmd *
9396 find_builtin(const char *name)
9398 struct builtincmd *bp;
9401 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9408 * Execute a simple command.
9411 isassignment(const char *p)
9413 const char *q = endofname(p);
9418 static int FAST_FUNC
9419 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9421 /* Preserve exitstatus of a previous possible redirection
9422 * as POSIX mandates */
9423 return back_exitstatus;
9426 evalcommand(union node *cmd, int flags)
9428 static const struct builtincmd null_bltin = {
9429 "\0\0", bltincmd /* why three NULs? */
9431 struct stackmark smark;
9433 struct arglist arglist;
9434 struct arglist varlist;
9437 const struct strlist *sp;
9438 struct cmdentry cmdentry;
9445 struct builtincmd *bcmd;
9446 smallint cmd_is_exec;
9447 smallint pseudovarflag = 0;
9449 /* First expand the arguments. */
9450 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9451 setstackmark(&smark);
9452 back_exitstatus = 0;
9454 cmdentry.cmdtype = CMDBUILTIN;
9455 cmdentry.u.cmd = &null_bltin;
9456 varlist.lastp = &varlist.list;
9457 *varlist.lastp = NULL;
9458 arglist.lastp = &arglist.list;
9459 *arglist.lastp = NULL;
9462 if (cmd->ncmd.args) {
9463 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9464 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9467 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9468 struct strlist **spp;
9470 spp = arglist.lastp;
9471 if (pseudovarflag && isassignment(argp->narg.text))
9472 expandarg(argp, &arglist, EXP_VARTILDE);
9474 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9476 for (sp = *spp; sp; sp = sp->next)
9480 /* Reserve one extra spot at the front for shellexec. */
9481 nargv = stalloc(sizeof(char *) * (argc + 2));
9483 for (sp = arglist.list; sp; sp = sp->next) {
9484 TRACE(("evalcommand arg: %s\n", sp->text));
9485 *nargv++ = sp->text;
9490 if (iflag && funcnest == 0 && argc > 0)
9491 lastarg = nargv[-1];
9494 expredir(cmd->ncmd.redirect);
9495 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9497 path = vpath.var_text;
9498 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9499 struct strlist **spp;
9502 spp = varlist.lastp;
9503 expandarg(argp, &varlist, EXP_VARTILDE);
9506 * Modify the command lookup path, if a PATH= assignment
9510 if (varcmp(p, path) == 0)
9514 /* Print the command if xflag is set. */
9517 const char *p = " %s" + 1;
9519 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9521 for (n = 0; n < 2; n++) {
9523 fdprintf(preverrout_fd, p, sp->text);
9529 safe_write(preverrout_fd, "\n", 1);
9535 /* Now locate the command. */
9537 int cmd_flag = DO_ERR;
9538 #if ENABLE_ASH_CMDCMD
9539 const char *oldpath = path + 5;
9543 find_command(argv[0], &cmdentry, cmd_flag, path);
9544 if (cmdentry.cmdtype == CMDUNKNOWN) {
9545 flush_stdout_stderr();
9550 /* implement bltin and command here */
9551 if (cmdentry.cmdtype != CMDBUILTIN)
9554 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9555 if (cmdentry.u.cmd == EXECCMD)
9557 #if ENABLE_ASH_CMDCMD
9558 if (cmdentry.u.cmd == COMMANDCMD) {
9560 nargv = parse_command_args(argv, &path);
9563 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9564 * nargv => "PROG". path is updated if -p.
9566 argc -= nargv - argv;
9568 cmd_flag |= DO_NOFUNC;
9576 /* We have a redirection error. */
9578 raise_exception(EXERROR);
9580 exitstatus = status;
9584 /* Execute the command. */
9585 switch (cmdentry.cmdtype) {
9588 #if ENABLE_FEATURE_SH_NOFORK
9589 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9590 * around run_nofork_applet() call.
9591 * (2) Should this check also be done in forkshell()?
9592 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9594 /* find_command() encodes applet_no as (-2 - applet_no) */
9595 int applet_no = (- cmdentry.u.index - 2);
9596 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9597 listsetvar(varlist.list, VEXPORT|VSTACK);
9598 /* run <applet>_main() */
9599 status = run_nofork_applet(applet_no, argv);
9603 /* Can we avoid forking off? For example, very last command
9604 * in a script or a subshell does not need forking,
9605 * we can just exec it.
9607 if (!(flags & EV_EXIT) || may_have_traps) {
9608 /* No, forking off a child is necessary */
9610 jp = makejob(/*cmd,*/ 1);
9611 if (forkshell(jp, cmd, FORK_FG) != 0) {
9613 status = waitforjob(jp);
9615 TRACE(("forked child exited with %d\n", status));
9620 /* fall through to exec'ing external program */
9622 listsetvar(varlist.list, VEXPORT|VSTACK);
9623 shellexec(argv, path, cmdentry.u.index);
9627 cmdenviron = varlist.list;
9629 struct strlist *list = cmdenviron;
9631 if (spclbltin > 0 || argc == 0) {
9633 if (cmd_is_exec && argc > 1)
9636 listsetvar(list, i);
9638 /* Tight loop with builtins only:
9639 * "while kill -0 $child; do true; done"
9640 * will never exit even if $child died, unless we do this
9641 * to reap the zombie and make kill detect that it's gone: */
9642 dowait(DOWAIT_NONBLOCK, NULL);
9644 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9645 if (exception_type == EXERROR && spclbltin <= 0) {
9650 longjmp(exception_handler->loc, 1);
9655 listsetvar(varlist.list, 0);
9656 /* See above for the rationale */
9657 dowait(DOWAIT_NONBLOCK, NULL);
9658 if (evalfun(cmdentry.u.func, argc, argv, flags))
9661 status = exitstatus;
9666 if (cmd->ncmd.redirect)
9667 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9669 /* dsl: I think this is intended to be used to support
9670 * '_' in 'vi' command mode during line editing...
9671 * However I implemented that within libedit itself.
9673 setvar0("_", lastarg);
9675 popstackmark(&smark);
9681 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9683 char *volatile savecmdname;
9684 struct jmploc *volatile savehandler;
9685 struct jmploc jmploc;
9689 savecmdname = commandname;
9690 savehandler = exception_handler;
9691 i = setjmp(jmploc.loc);
9694 exception_handler = &jmploc;
9695 commandname = argv[0];
9697 optptr = NULL; /* initialize nextopt */
9699 status = evalcmd(argc, argv, flags);
9701 status = (*cmd->builtin)(argc, argv);
9702 flush_stdout_stderr();
9703 status |= ferror(stdout);
9704 exitstatus = status;
9707 commandname = savecmdname;
9708 exception_handler = savehandler;
9714 goodname(const char *p)
9716 return endofname(p)[0] == '\0';
9721 * Search for a command. This is called before we fork so that the
9722 * location of the command will be available in the parent as well as
9723 * the child. The check for "goodname" is an overly conservative
9724 * check that the name will not be subject to expansion.
9727 prehash(union node *n)
9729 struct cmdentry entry;
9731 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9732 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9736 /* ============ Builtin commands
9738 * Builtin commands whose functions are closely tied to evaluation
9739 * are implemented here.
9743 * Handle break and continue commands. Break, continue, and return are
9744 * all handled by setting the evalskip flag. The evaluation routines
9745 * above all check this flag, and if it is set they start skipping
9746 * commands rather than executing them. The variable skipcount is
9747 * the number of loops to break/continue, or the number of function
9748 * levels to return. (The latter is always 1.) It should probably
9749 * be an error to break out of more loops than exist, but it isn't
9750 * in the standard shell so we don't make it one here.
9752 static int FAST_FUNC
9753 breakcmd(int argc UNUSED_PARAM, char **argv)
9755 int n = argv[1] ? number(argv[1]) : 1;
9758 ash_msg_and_raise_error(msg_illnum, argv[1]);
9762 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9770 * This implements the input routines used by the parser.
9774 INPUT_PUSH_FILE = 1,
9775 INPUT_NOFILE_OK = 2,
9778 static smallint checkkwd;
9779 /* values of checkkwd variable */
9780 #define CHKALIAS 0x1
9785 * Push a string back onto the input at this current parsefile level.
9786 * We handle aliases this way.
9788 #if !ENABLE_ASH_ALIAS
9789 #define pushstring(s, ap) pushstring(s)
9792 pushstring(char *s, struct alias *ap)
9799 if (g_parsefile->strpush) {
9800 sp = ckzalloc(sizeof(*sp));
9801 sp->prev = g_parsefile->strpush;
9803 sp = &(g_parsefile->basestrpush);
9805 g_parsefile->strpush = sp;
9806 sp->prev_string = g_parsefile->next_to_pgetc;
9807 sp->prev_left_in_line = g_parsefile->left_in_line;
9808 sp->unget = g_parsefile->unget;
9809 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9810 #if ENABLE_ASH_ALIAS
9813 ap->flag |= ALIASINUSE;
9817 g_parsefile->next_to_pgetc = s;
9818 g_parsefile->left_in_line = len;
9819 g_parsefile->unget = 0;
9826 struct strpush *sp = g_parsefile->strpush;
9829 #if ENABLE_ASH_ALIAS
9831 if (g_parsefile->next_to_pgetc[-1] == ' '
9832 || g_parsefile->next_to_pgetc[-1] == '\t'
9834 checkkwd |= CHKALIAS;
9836 if (sp->string != sp->ap->val) {
9839 sp->ap->flag &= ~ALIASINUSE;
9840 if (sp->ap->flag & ALIASDEAD) {
9841 unalias(sp->ap->name);
9845 g_parsefile->next_to_pgetc = sp->prev_string;
9846 g_parsefile->left_in_line = sp->prev_left_in_line;
9847 g_parsefile->unget = sp->unget;
9848 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9849 g_parsefile->strpush = sp->prev;
9850 if (sp != &(g_parsefile->basestrpush))
9859 char *buf = g_parsefile->buf;
9861 g_parsefile->next_to_pgetc = buf;
9862 #if ENABLE_FEATURE_EDITING
9864 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9865 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9868 # if ENABLE_ASH_IDLE_TIMEOUT
9870 const char *tmout_var = lookupvar("TMOUT");
9872 timeout = atoi(tmout_var) * 1000;
9878 # if ENABLE_FEATURE_TAB_COMPLETION
9879 line_input_state->path_lookup = pathval();
9881 reinit_unicode_for_ash();
9882 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9884 /* ^C pressed, "convert" to SIGINT */
9885 write(STDOUT_FILENO, "^C", 2);
9892 exitstatus = 128 + SIGINT;
9898 /* Ctrl+D pressed */
9901 # if ENABLE_ASH_IDLE_TIMEOUT
9902 else if (errno == EAGAIN && timeout > 0) {
9903 puts("\007timed out waiting for input: auto-logout");
9910 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9913 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9915 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9916 int flags = fcntl(0, F_GETFL);
9917 if (flags >= 0 && (flags & O_NONBLOCK)) {
9918 flags &= ~O_NONBLOCK;
9919 if (fcntl(0, F_SETFL, flags) >= 0) {
9920 out2str("sh: turning off NDELAY mode\n");
9931 * Refill the input buffer and return the next input character:
9933 * 1) If a string was pushed back on the input, pop it;
9934 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9935 * or we are reading from a string so we can't refill the buffer,
9937 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9938 * 4) Process input up to the next newline, deleting nul characters.
9940 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9941 #define pgetc_debug(...) ((void)0)
9942 static int pgetc(void);
9949 if (g_parsefile->strpush) {
9950 #if ENABLE_ASH_ALIAS
9951 if (g_parsefile->left_in_line == -1
9952 && g_parsefile->strpush->ap
9953 && g_parsefile->next_to_pgetc[-1] != ' '
9954 && g_parsefile->next_to_pgetc[-1] != '\t'
9956 pgetc_debug("preadbuffer PEOA");
9963 /* on both branches above g_parsefile->left_in_line < 0.
9964 * "pgetc" needs refilling.
9967 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9968 * pungetc() may increment it a few times.
9969 * Assuming it won't increment it to less than -90.
9971 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9972 pgetc_debug("preadbuffer PEOF1");
9973 /* even in failure keep left_in_line and next_to_pgetc
9974 * in lock step, for correct multi-layer pungetc.
9975 * left_in_line was decremented before preadbuffer(),
9976 * must inc next_to_pgetc: */
9977 g_parsefile->next_to_pgetc++;
9981 more = g_parsefile->left_in_buffer;
9983 flush_stdout_stderr();
9987 /* don't try reading again */
9988 g_parsefile->left_in_line = -99;
9989 pgetc_debug("preadbuffer PEOF2");
9990 g_parsefile->next_to_pgetc++;
9995 /* Find out where's the end of line.
9996 * Set g_parsefile->left_in_line
9997 * and g_parsefile->left_in_buffer acordingly.
9998 * NUL chars are deleted.
10000 q = g_parsefile->next_to_pgetc;
10008 memmove(q, q + 1, more);
10012 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10018 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10019 if (g_parsefile->left_in_line < 0)
10024 g_parsefile->left_in_buffer = more;
10029 out2str(g_parsefile->next_to_pgetc);
10033 pgetc_debug("preadbuffer at %d:%p'%s'",
10034 g_parsefile->left_in_line,
10035 g_parsefile->next_to_pgetc,
10036 g_parsefile->next_to_pgetc);
10037 return (unsigned char)*g_parsefile->next_to_pgetc++;
10043 g_parsefile->linno++;
10044 setprompt_if(doprompt, 2);
10049 g_parsefile->linno++;
10050 needprompt = doprompt;
10058 pgetc_debug("pgetc at %d:%p'%s'",
10059 g_parsefile->left_in_line,
10060 g_parsefile->next_to_pgetc,
10061 g_parsefile->next_to_pgetc);
10062 if (g_parsefile->unget)
10063 return g_parsefile->lastc[--g_parsefile->unget];
10065 if (--g_parsefile->left_in_line >= 0)
10066 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10070 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10071 g_parsefile->lastc[0] = c;
10076 #if ENABLE_ASH_ALIAS
10078 pgetc_without_PEOA(void)
10082 pgetc_debug("pgetc at %d:%p'%s'",
10083 g_parsefile->left_in_line,
10084 g_parsefile->next_to_pgetc,
10085 g_parsefile->next_to_pgetc);
10087 } while (c == PEOA);
10091 # define pgetc_without_PEOA() pgetc()
10095 * Read a line from the script.
10098 pfgets(char *line, int len)
10104 while (--nleft > 0) {
10105 c = pgetc_without_PEOA();
10120 * Undo a call to pgetc. Only two characters may be pushed back.
10121 * PEOF may be pushed back.
10126 g_parsefile->unget++;
10129 /* This one eats backslash+newline */
10135 while ((c = pgetc()) == '\\') {
10136 if (pgetc() != '\n') {
10148 * To handle the "." command, a stack of input files is used. Pushfile
10149 * adds a new entry to the stack and popfile restores the previous level.
10154 struct parsefile *pf;
10156 pf = ckzalloc(sizeof(*pf));
10157 pf->prev = g_parsefile;
10159 /*pf->strpush = NULL; - ckzalloc did it */
10160 /*pf->basestrpush.prev = NULL;*/
10168 struct parsefile *pf = g_parsefile;
10174 if (pf->pf_fd >= 0)
10177 while (pf->strpush)
10179 g_parsefile = pf->prev;
10185 * Return to top level.
10190 while (g_parsefile != &basepf)
10195 * Close the file(s) that the shell is reading commands from. Called
10196 * after a fork is done.
10202 if (g_parsefile->pf_fd > 0) {
10203 close(g_parsefile->pf_fd);
10204 g_parsefile->pf_fd = 0;
10209 * Like setinputfile, but takes an open file descriptor. Call this with
10213 setinputfd(int fd, int push)
10217 g_parsefile->buf = NULL;
10219 g_parsefile->pf_fd = fd;
10220 if (g_parsefile->buf == NULL)
10221 g_parsefile->buf = ckmalloc(IBUFSIZ);
10222 g_parsefile->left_in_buffer = 0;
10223 g_parsefile->left_in_line = 0;
10224 g_parsefile->linno = 1;
10228 * Set the input to take input from a file. If push is set, push the
10229 * old input onto the stack first.
10232 setinputfile(const char *fname, int flags)
10237 fd = open(fname, O_RDONLY);
10239 if (flags & INPUT_NOFILE_OK)
10242 ash_msg_and_raise_error("can't open '%s'", fname);
10247 close_on_exec_on(fd);
10248 setinputfd(fd, flags & INPUT_PUSH_FILE);
10255 * Like setinputfile, but takes input from a string.
10258 setinputstring(char *string)
10262 g_parsefile->next_to_pgetc = string;
10263 g_parsefile->left_in_line = strlen(string);
10264 g_parsefile->buf = NULL;
10265 g_parsefile->linno = 1;
10271 * Routines to check for mail.
10274 #if ENABLE_ASH_MAIL
10276 /* Hash of mtimes of mailboxes */
10277 static unsigned mailtime_hash;
10278 /* Set if MAIL or MAILPATH is changed. */
10279 static smallint mail_var_path_changed;
10282 * Print appropriate message(s) if mail has arrived.
10283 * If mail_var_path_changed is set,
10284 * then the value of MAIL has mail_var_path_changed,
10285 * so we just update the values.
10294 struct stackmark smark;
10297 setstackmark(&smark);
10298 mpath = mpathset() ? mpathval() : mailval();
10301 p = path_advance(&mpath, nullstr);
10306 for (q = p; *q; q++)
10312 q[-1] = '\0'; /* delete trailing '/' */
10313 if (stat(p, &statb) < 0) {
10316 /* Very simplistic "hash": just a sum of all mtimes */
10317 new_hash += (unsigned)statb.st_mtime;
10319 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10320 if (mailtime_hash != 0)
10321 out2str("you have mail\n");
10322 mailtime_hash = new_hash;
10324 mail_var_path_changed = 0;
10325 popstackmark(&smark);
10328 static void FAST_FUNC
10329 changemail(const char *val UNUSED_PARAM)
10331 mail_var_path_changed = 1;
10334 #endif /* ASH_MAIL */
10337 /* ============ ??? */
10340 * Set the shell parameters.
10343 setparam(char **argv)
10349 for (nparam = 0; argv[nparam]; nparam++)
10351 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10353 *ap++ = ckstrdup(*argv++);
10356 freeparam(&shellparam);
10357 shellparam.malloced = 1;
10358 shellparam.nparam = nparam;
10359 shellparam.p = newparam;
10360 #if ENABLE_ASH_GETOPTS
10361 shellparam.optind = 1;
10362 shellparam.optoff = -1;
10367 * Process shell options. The global variable argptr contains a pointer
10368 * to the argument list; we advance it past the options.
10370 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10371 * For a non-interactive shell, an error condition encountered
10372 * by a special built-in ... shall cause the shell to write a diagnostic message
10373 * to standard error and exit as shown in the following table:
10374 * Error Special Built-In
10376 * Utility syntax error (option or operand error) Shall exit
10378 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10379 * we see that bash does not do that (set "finishes" with error code 1 instead,
10380 * and shell continues), and people rely on this behavior!
10382 * set -o barfoo 2>/dev/null
10385 * Oh well. Let's mimic that.
10388 plus_minus_o(char *name, int val)
10393 for (i = 0; i < NOPTS; i++) {
10394 if (strcmp(name, optnames(i)) == 0) {
10399 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10402 for (i = 0; i < NOPTS; i++) {
10404 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10406 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10412 setoption(int flag, int val)
10416 for (i = 0; i < NOPTS; i++) {
10417 if (optletters(i) == flag) {
10422 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10426 options(int cmdline)
10434 while ((p = *argptr) != NULL) {
10436 if (c != '-' && c != '+')
10439 val = 0; /* val = 0 if c == '+' */
10442 if (p[0] == '\0' || LONE_DASH(p)) {
10444 /* "-" means turn off -x and -v */
10447 /* "--" means reset params */
10448 else if (*argptr == NULL)
10451 break; /* "-" or "--" terminates options */
10454 /* first char was + or - */
10455 while ((c = *p++) != '\0') {
10456 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10457 if (c == 'c' && cmdline) {
10458 minusc = p; /* command is after shell args */
10459 } else if (c == 'o') {
10460 if (plus_minus_o(*argptr, val)) {
10461 /* it already printed err message */
10462 return 1; /* error */
10466 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10468 /* bash does not accept +-login, we also won't */
10469 } else if (cmdline && val && (c == '-')) { /* long options */
10470 if (strcmp(p, "login") == 0)
10482 * The shift builtin command.
10484 static int FAST_FUNC
10485 shiftcmd(int argc UNUSED_PARAM, char **argv)
10492 n = number(argv[1]);
10493 if (n > shellparam.nparam)
10494 n = 0; /* bash compat, was = shellparam.nparam; */
10496 shellparam.nparam -= n;
10497 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10498 if (shellparam.malloced)
10501 ap2 = shellparam.p;
10502 while ((*ap2++ = *ap1++) != NULL)
10504 #if ENABLE_ASH_GETOPTS
10505 shellparam.optind = 1;
10506 shellparam.optoff = -1;
10513 * POSIX requires that 'set' (but not export or readonly) output the
10514 * variables in lexicographic order - by the locale's collating order (sigh).
10515 * Maybe we could keep them in an ordered balanced binary tree
10516 * instead of hashed lists.
10517 * For now just roll 'em through qsort for printing...
10520 showvars(const char *sep_prefix, int on, int off)
10523 char **ep, **epend;
10525 ep = listvars(on, off, &epend);
10526 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10528 sep = *sep_prefix ? " " : sep_prefix;
10530 for (; ep < epend; ep++) {
10534 p = strchrnul(*ep, '=');
10537 q = single_quote(++p);
10538 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10544 * The set command builtin.
10546 static int FAST_FUNC
10547 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10552 return showvars(nullstr, 0, VUNSET);
10555 retval = options(/*cmdline:*/ 0);
10556 if (retval == 0) { /* if no parse error... */
10558 if (*argptr != NULL) {
10566 #if ENABLE_ASH_RANDOM_SUPPORT
10567 static void FAST_FUNC
10568 change_random(const char *value)
10572 if (value == NULL) {
10573 /* "get", generate */
10574 t = next_random(&random_gen);
10575 /* set without recursion */
10576 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10577 vrandom.flags &= ~VNOFUNC;
10580 t = strtoul(value, NULL, 10);
10581 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10586 #if ENABLE_ASH_GETOPTS
10588 getopts(char *optstr, char *optvar, char **optfirst)
10595 int ind = shellparam.optind;
10596 int off = shellparam.optoff;
10600 shellparam.optind = -1;
10601 optnext = optfirst + ind - 1;
10603 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10606 p = optnext[-1] + off;
10607 if (p == NULL || *p == '\0') {
10608 /* Current word is done, advance */
10610 if (p == NULL || *p != '-' || *++p == '\0') {
10617 if (LONE_DASH(p)) /* check for "--" */
10622 for (q = optstr; *q != c;) {
10624 if (optstr[0] == ':') {
10626 /*sbuf[1] = '\0'; - already is */
10627 setvar0("OPTARG", sbuf);
10629 fprintf(stderr, "Illegal option -%c\n", c);
10630 unsetvar("OPTARG");
10640 if (*p == '\0' && (p = *optnext) == NULL) {
10641 if (optstr[0] == ':') {
10643 /*sbuf[1] = '\0'; - already is */
10644 setvar0("OPTARG", sbuf);
10647 fprintf(stderr, "No arg for -%c option\n", c);
10648 unsetvar("OPTARG");
10656 setvar0("OPTARG", p);
10659 setvar0("OPTARG", nullstr);
10661 ind = optnext - optfirst + 1;
10662 setvar("OPTIND", itoa(ind), VNOFUNC);
10664 /*sbuf[1] = '\0'; - already is */
10665 setvar0(optvar, sbuf);
10667 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10668 shellparam.optind = ind;
10674 * The getopts builtin. Shellparam.optnext points to the next argument
10675 * to be processed. Shellparam.optptr points to the next character to
10676 * be processed in the current argument. If shellparam.optnext is NULL,
10677 * then it's the first time getopts has been called.
10679 static int FAST_FUNC
10680 getoptscmd(int argc, char **argv)
10685 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10687 optbase = shellparam.p;
10688 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10689 shellparam.optind = 1;
10690 shellparam.optoff = -1;
10693 optbase = &argv[3];
10694 if ((unsigned)shellparam.optind > argc - 2) {
10695 shellparam.optind = 1;
10696 shellparam.optoff = -1;
10700 return getopts(argv[1], argv[2], optbase);
10702 #endif /* ASH_GETOPTS */
10705 /* ============ Shell parser */
10708 struct heredoc *next; /* next here document in list */
10709 union node *here; /* redirection node */
10710 char *eofmark; /* string indicating end of input */
10711 smallint striptabs; /* if set, strip leading tabs */
10714 static smallint tokpushback; /* last token pushed back */
10715 static smallint quoteflag; /* set if (part of) last token was quoted */
10716 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10717 static struct heredoc *heredoclist; /* list of here documents to read */
10718 static char *wordtext; /* text of last word returned by readtoken */
10719 static struct nodelist *backquotelist;
10720 static union node *redirnode;
10721 static struct heredoc *heredoc;
10723 static const char *
10724 tokname(char *buf, int tok)
10727 return tokname_array[tok];
10728 sprintf(buf, "\"%s\"", tokname_array[tok]);
10732 /* raise_error_unexpected_syntax:
10733 * Called when an unexpected token is read during the parse. The argument
10734 * is the token that is expected, or -1 if more than one type of token can
10735 * occur at this point.
10737 static void raise_error_unexpected_syntax(int) NORETURN;
10739 raise_error_unexpected_syntax(int token)
10745 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10747 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10748 raise_error_syntax(msg);
10752 #define EOFMARKLEN 79
10754 /* parsing is heavily cross-recursive, need these forward decls */
10755 static union node *andor(void);
10756 static union node *pipeline(void);
10757 static union node *parse_command(void);
10758 static void parseheredoc(void);
10759 static int peektoken(void);
10760 static int readtoken(void);
10762 static union node *
10765 union node *n1, *n2, *n3;
10770 switch (peektoken()) {
10778 if (!n1 && (nlflag & 1))
10784 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10785 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10791 if (tok == TBACKGND) {
10792 if (n2->type == NPIPE) {
10793 n2->npipe.pipe_backgnd = 1;
10795 if (n2->type != NREDIR) {
10796 n3 = stzalloc(sizeof(struct nredir));
10798 /*n3->nredir.redirect = NULL; - stzalloc did it */
10801 n2->type = NBACKGND;
10807 n3 = stzalloc(sizeof(struct nbinary));
10809 n3->nbinary.ch1 = n1;
10810 n3->nbinary.ch2 = n2;
10823 raise_error_unexpected_syntax(-1);
10830 static union node *
10833 union node *n1, *n2, *n3;
10841 } else if (t == TOR) {
10847 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10849 n3 = stzalloc(sizeof(struct nbinary));
10851 n3->nbinary.ch1 = n1;
10852 n3->nbinary.ch2 = n2;
10857 static union node *
10860 union node *n1, *n2, *pipenode;
10861 struct nodelist *lp, *prev;
10865 TRACE(("pipeline: entered\n"));
10866 if (readtoken() == TNOT) {
10868 checkkwd = CHKKWD | CHKALIAS;
10871 n1 = parse_command();
10872 if (readtoken() == TPIPE) {
10873 pipenode = stzalloc(sizeof(struct npipe));
10874 pipenode->type = NPIPE;
10875 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10876 lp = stzalloc(sizeof(struct nodelist));
10877 pipenode->npipe.cmdlist = lp;
10881 lp = stzalloc(sizeof(struct nodelist));
10882 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10883 lp->n = parse_command();
10885 } while (readtoken() == TPIPE);
10891 n2 = stzalloc(sizeof(struct nnot));
10899 static union node *
10904 n = stzalloc(sizeof(struct narg));
10906 /*n->narg.next = NULL; - stzalloc did it */
10907 n->narg.text = wordtext;
10908 n->narg.backquote = backquotelist;
10913 fixredir(union node *n, const char *text, int err)
10917 TRACE(("Fix redir %s %d\n", text, err));
10919 n->ndup.vname = NULL;
10921 fd = bb_strtou(text, NULL, 10);
10922 if (!errno && fd >= 0)
10923 n->ndup.dupfd = fd;
10924 else if (LONE_DASH(text))
10925 n->ndup.dupfd = -1;
10928 raise_error_syntax("bad fd number");
10929 n->ndup.vname = makename();
10934 * Returns true if the text contains nothing to expand (no dollar signs
10938 noexpand(const char *text)
10942 while ((c = *text++) != '\0') {
10943 if (c == CTLQUOTEMARK)
10947 else if (SIT(c, BASESYNTAX) == CCTL)
10956 union node *n = redirnode;
10958 if (readtoken() != TWORD)
10959 raise_error_unexpected_syntax(-1);
10960 if (n->type == NHERE) {
10961 struct heredoc *here = heredoc;
10965 if (quoteflag == 0)
10967 TRACE(("Here document %d\n", n->type));
10968 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10969 raise_error_syntax("illegal eof marker for << redirection");
10970 rmescapes(wordtext, 0);
10971 here->eofmark = wordtext;
10973 if (heredoclist == NULL)
10974 heredoclist = here;
10976 for (p = heredoclist; p->next; p = p->next)
10980 } else if (n->type == NTOFD || n->type == NFROMFD) {
10981 fixredir(n, wordtext, 0);
10983 n->nfile.fname = makename();
10987 static union node *
10990 union node *args, **app;
10991 union node *n = NULL;
10992 union node *vars, **vpp;
10993 union node **rpp, *redir;
10995 #if ENABLE_ASH_BASH_COMPAT
10996 smallint double_brackets_flag = 0;
10997 smallint function_flag = 0;
11007 savecheckkwd = CHKALIAS;
11010 checkkwd = savecheckkwd;
11013 #if ENABLE_ASH_BASH_COMPAT
11015 if (peektoken() != TWORD)
11016 raise_error_unexpected_syntax(TWORD);
11019 case TAND: /* "&&" */
11020 case TOR: /* "||" */
11021 if (!double_brackets_flag) {
11025 wordtext = (char *) (t == TAND ? "-a" : "-o");
11028 n = stzalloc(sizeof(struct narg));
11030 /*n->narg.next = NULL; - stzalloc did it */
11031 n->narg.text = wordtext;
11032 #if ENABLE_ASH_BASH_COMPAT
11033 if (strcmp("[[", wordtext) == 0)
11034 double_brackets_flag = 1;
11035 else if (strcmp("]]", wordtext) == 0)
11036 double_brackets_flag = 0;
11038 n->narg.backquote = backquotelist;
11039 if (savecheckkwd && isassignment(wordtext)) {
11041 vpp = &n->narg.next;
11044 app = &n->narg.next;
11047 #if ENABLE_ASH_BASH_COMPAT
11048 if (function_flag) {
11049 checkkwd = CHKNL | CHKKWD;
11050 switch (peektoken()) {
11062 if (strcmp("[[", wordtext) == 0)
11066 raise_error_unexpected_syntax(-1);
11072 *rpp = n = redirnode;
11073 rpp = &n->nfile.next;
11074 parsefname(); /* read name of redirection file */
11077 IF_ASH_BASH_COMPAT(do_func:)
11078 if (args && app == &args->narg.next
11081 struct builtincmd *bcmd;
11084 /* We have a function */
11085 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11086 raise_error_unexpected_syntax(TRP);
11087 name = n->narg.text;
11088 if (!goodname(name)
11089 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11091 raise_error_syntax("bad function name");
11094 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11095 n->narg.next = parse_command();
11098 IF_ASH_BASH_COMPAT(function_flag = 0;)
11109 n = stzalloc(sizeof(struct ncmd));
11111 n->ncmd.args = args;
11112 n->ncmd.assign = vars;
11113 n->ncmd.redirect = redir;
11117 static union node *
11118 parse_command(void)
11120 union node *n1, *n2;
11121 union node *ap, **app;
11122 union node *cp, **cpp;
11123 union node *redir, **rpp;
11130 switch (readtoken()) {
11132 raise_error_unexpected_syntax(-1);
11135 n1 = stzalloc(sizeof(struct nif));
11137 n1->nif.test = list(0);
11138 if (readtoken() != TTHEN)
11139 raise_error_unexpected_syntax(TTHEN);
11140 n1->nif.ifpart = list(0);
11142 while (readtoken() == TELIF) {
11143 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11144 n2 = n2->nif.elsepart;
11146 n2->nif.test = list(0);
11147 if (readtoken() != TTHEN)
11148 raise_error_unexpected_syntax(TTHEN);
11149 n2->nif.ifpart = list(0);
11151 if (lasttoken == TELSE)
11152 n2->nif.elsepart = list(0);
11154 n2->nif.elsepart = NULL;
11162 n1 = stzalloc(sizeof(struct nbinary));
11163 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11164 n1->nbinary.ch1 = list(0);
11167 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11168 got == TWORD ? wordtext : ""));
11169 raise_error_unexpected_syntax(TDO);
11171 n1->nbinary.ch2 = list(0);
11176 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11177 raise_error_syntax("bad for loop variable");
11178 n1 = stzalloc(sizeof(struct nfor));
11180 n1->nfor.var = wordtext;
11181 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11182 if (readtoken() == TIN) {
11184 while (readtoken() == TWORD) {
11185 n2 = stzalloc(sizeof(struct narg));
11187 /*n2->narg.next = NULL; - stzalloc did it */
11188 n2->narg.text = wordtext;
11189 n2->narg.backquote = backquotelist;
11191 app = &n2->narg.next;
11194 n1->nfor.args = ap;
11195 if (lasttoken != TNL && lasttoken != TSEMI)
11196 raise_error_unexpected_syntax(-1);
11198 n2 = stzalloc(sizeof(struct narg));
11200 /*n2->narg.next = NULL; - stzalloc did it */
11201 n2->narg.text = (char *)dolatstr;
11202 /*n2->narg.backquote = NULL;*/
11203 n1->nfor.args = n2;
11205 * Newline or semicolon here is optional (but note
11206 * that the original Bourne shell only allowed NL).
11208 if (lasttoken != TSEMI)
11211 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11212 if (readtoken() != TDO)
11213 raise_error_unexpected_syntax(TDO);
11214 n1->nfor.body = list(0);
11218 n1 = stzalloc(sizeof(struct ncase));
11220 if (readtoken() != TWORD)
11221 raise_error_unexpected_syntax(TWORD);
11222 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11224 /*n2->narg.next = NULL; - stzalloc did it */
11225 n2->narg.text = wordtext;
11226 n2->narg.backquote = backquotelist;
11227 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11228 if (readtoken() != TIN)
11229 raise_error_unexpected_syntax(TIN);
11230 cpp = &n1->ncase.cases;
11232 checkkwd = CHKNL | CHKKWD;
11234 while (t != TESAC) {
11235 if (lasttoken == TLP)
11237 *cpp = cp = stzalloc(sizeof(struct nclist));
11239 app = &cp->nclist.pattern;
11241 *app = ap = stzalloc(sizeof(struct narg));
11243 /*ap->narg.next = NULL; - stzalloc did it */
11244 ap->narg.text = wordtext;
11245 ap->narg.backquote = backquotelist;
11246 if (readtoken() != TPIPE)
11248 app = &ap->narg.next;
11251 //ap->narg.next = NULL;
11252 if (lasttoken != TRP)
11253 raise_error_unexpected_syntax(TRP);
11254 cp->nclist.body = list(2);
11256 cpp = &cp->nclist.next;
11258 checkkwd = CHKNL | CHKKWD;
11262 raise_error_unexpected_syntax(TENDCASE);
11269 n1 = stzalloc(sizeof(struct nredir));
11270 n1->type = NSUBSHELL;
11271 n1->nredir.n = list(0);
11272 /*n1->nredir.redirect = NULL; - stzalloc did it */
11279 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11283 return simplecmd();
11286 if (readtoken() != t)
11287 raise_error_unexpected_syntax(t);
11290 /* Now check for redirection which may follow command */
11291 checkkwd = CHKKWD | CHKALIAS;
11293 while (readtoken() == TREDIR) {
11294 *rpp = n2 = redirnode;
11295 rpp = &n2->nfile.next;
11301 if (n1->type != NSUBSHELL) {
11302 n2 = stzalloc(sizeof(struct nredir));
11307 n1->nredir.redirect = redir;
11312 #if ENABLE_ASH_BASH_COMPAT
11314 decode_dollar_squote(void)
11316 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11322 p = strchr(C_escapes, c);
11327 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11331 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11333 } else if (c == 'x') { /* \xHH */
11337 } while (isxdigit(c) && --cnt);
11339 if (cnt == 3) { /* \x but next char is "bad" */
11343 } else { /* simple seq like \\ or \t */
11348 c = bb_process_escape_sequence((void*)&p);
11349 } else { /* unrecognized "\z": print both chars unless ' or " */
11350 if (c != '\'' && c != '"') {
11352 c |= 0x100; /* "please encode \, then me" */
11360 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11361 * is not NULL, read a here document. In the latter case, eofmark is the
11362 * word which marks the end of the document and striptabs is true if
11363 * leading tabs should be stripped from the document. The argument c
11364 * is the first character of the input token or document.
11366 * Because C does not have internal subroutines, I have simulated them
11367 * using goto's to implement the subroutine linkage. The following macros
11368 * will run code that appears at the end of readtoken1.
11370 #define CHECKEND() {goto checkend; checkend_return:;}
11371 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11372 #define PARSESUB() {goto parsesub; parsesub_return:;}
11373 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11374 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11375 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11377 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11379 /* NB: syntax parameter fits into smallint */
11380 /* c parameter is an unsigned char or PEOF or PEOA */
11383 char line[EOFMARKLEN + 1];
11384 struct nodelist *bqlist;
11388 IF_SH_MATH_SUPPORT(smallint prevsyntax;) /* syntax before arithmetic */
11389 #if ENABLE_ASH_EXPAND_PRMT
11390 smallint pssyntax; /* we are expanding a prompt string */
11392 int varnest; /* levels of variables expansion */
11393 IF_SH_MATH_SUPPORT(int arinest;) /* levels of arithmetic expansion */
11394 IF_SH_MATH_SUPPORT(int parenlevel;) /* levels of parens in arithmetic */
11395 int dqvarnest; /* levels of variables expansion within double quotes */
11397 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11399 startlinno = g_parsefile->linno;
11402 IF_SH_MATH_SUPPORT(prevsyntax = 0;)
11403 #if ENABLE_ASH_EXPAND_PRMT
11404 pssyntax = (syntax == PSSYNTAX);
11408 dblquote = (syntax == DQSYNTAX);
11410 IF_SH_MATH_SUPPORT(arinest = 0;)
11411 IF_SH_MATH_SUPPORT(parenlevel = 0;)
11414 STARTSTACKSTR(out);
11416 /* For each line, until end of word */
11417 CHECKEND(); /* set c to PEOF if at end of here document */
11418 for (;;) { /* until end of line or end of word */
11419 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11420 switch (SIT(c, syntax)) {
11421 case CNL: /* '\n' */
11422 if (syntax == BASESYNTAX)
11423 goto endword; /* exit outer loop */
11427 goto loop; /* continue outer loop */
11432 #if ENABLE_ASH_BASH_COMPAT
11433 if (c == '\\' && bash_dollar_squote) {
11434 c = decode_dollar_squote();
11436 /* skip $'\000', $'\x00' (like bash) */
11440 /* Unknown escape. Encode as '\z' */
11441 c = (unsigned char)c;
11442 if (eofmark == NULL || dblquote)
11443 USTPUTC(CTLESC, out);
11444 USTPUTC('\\', out);
11448 if (eofmark == NULL || dblquote)
11449 USTPUTC(CTLESC, out);
11452 case CBACK: /* backslash */
11453 c = pgetc_without_PEOA();
11455 USTPUTC(CTLESC, out);
11456 USTPUTC('\\', out);
11458 } else if (c == '\n') {
11461 #if ENABLE_ASH_EXPAND_PRMT
11462 if (c == '$' && pssyntax) {
11463 USTPUTC(CTLESC, out);
11464 USTPUTC('\\', out);
11467 /* Backslash is retained if we are in "str" and next char isn't special */
11472 && (c != '"' || eofmark != NULL)
11474 USTPUTC('\\', out);
11476 USTPUTC(CTLESC, out);
11484 if (eofmark == NULL) {
11485 USTPUTC(CTLQUOTEMARK, out);
11493 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11494 if (eofmark != NULL && varnest == 0) {
11497 if (dqvarnest == 0) {
11498 syntax = BASESYNTAX;
11505 case CVAR: /* '$' */
11506 PARSESUB(); /* parse substitution */
11508 case CENDVAR: /* '}' */
11511 if (dqvarnest > 0) {
11518 #if ENABLE_SH_MATH_SUPPORT
11519 case CLP: /* '(' in arithmetic */
11523 case CRP: /* ')' in arithmetic */
11524 if (parenlevel > 0) {
11527 if (pgetc_eatbnl() == ')') {
11529 if (--arinest == 0) {
11530 syntax = prevsyntax;
11534 * unbalanced parens
11535 * (don't 2nd guess - no error)
11543 case CBQUOTE: /* '`' */
11547 goto endword; /* exit outer loop */
11551 if (varnest == 0) {
11552 #if ENABLE_ASH_BASH_COMPAT
11554 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11555 if (pgetc() == '>')
11556 c = 0x100 + '>'; /* flag &> */
11560 goto endword; /* exit outer loop */
11562 IF_ASH_ALIAS(if (c != PEOA))
11569 #if ENABLE_SH_MATH_SUPPORT
11570 if (syntax == ARISYNTAX)
11571 raise_error_syntax("missing '))'");
11573 if (syntax != BASESYNTAX && eofmark == NULL)
11574 raise_error_syntax("unterminated quoted string");
11575 if (varnest != 0) {
11576 startlinno = g_parsefile->linno;
11578 raise_error_syntax("missing '}'");
11580 USTPUTC('\0', out);
11581 len = out - (char *)stackblock();
11582 out = stackblock();
11583 if (eofmark == NULL) {
11584 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11587 if (isdigit_str9(out)) {
11588 PARSEREDIR(); /* passed as params: out, c */
11589 lasttoken = TREDIR;
11592 /* else: non-number X seen, interpret it
11593 * as "NNNX>file" = "NNNX >file" */
11597 quoteflag = quotef;
11598 backquotelist = bqlist;
11599 grabstackblock(len);
11603 /* end of readtoken routine */
11606 * Check to see whether we are at the end of the here document. When this
11607 * is called, c is set to the first character of the next input line. If
11608 * we are at the end of the here document, this routine sets the c to PEOF.
11612 #if ENABLE_ASH_ALIAS
11614 c = pgetc_without_PEOA();
11617 while (c == '\t') {
11618 c = pgetc_without_PEOA();
11621 if (c == *eofmark) {
11622 if (pfgets(line, sizeof(line)) != NULL) {
11627 for (q = eofmark + 1;; p++, q++) {
11631 if (!*q || cc != *q)
11638 pushstring(line, NULL);
11643 goto checkend_return;
11647 * Parse a redirection operator. The variable "out" points to a string
11648 * specifying the fd to be redirected. The variable "c" contains the
11649 * first character of the redirection operator.
11652 /* out is already checked to be a valid number or "" */
11653 int fd = (*out == '\0' ? -1 : atoi(out));
11656 np = stzalloc(sizeof(struct nfile));
11661 np->type = NAPPEND;
11663 np->type = NCLOBBER;
11666 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11672 #if ENABLE_ASH_BASH_COMPAT
11673 else if (c == 0x100 + '>') { /* this flags &> redirection */
11675 pgetc(); /* this is '>', no need to check */
11679 else { /* c == '<' */
11680 /*np->nfile.fd = 0; - stzalloc did it */
11684 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11685 np = stzalloc(sizeof(struct nhere));
11686 /*np->nfile.fd = 0; - stzalloc did it */
11689 heredoc = stzalloc(sizeof(struct heredoc));
11690 heredoc->here = np;
11693 heredoc->striptabs = 1;
11695 /*heredoc->striptabs = 0; - stzalloc did it */
11701 np->type = NFROMFD;
11705 np->type = NFROMTO;
11717 goto parseredir_return;
11721 * Parse a substitution. At this point, we have read the dollar sign
11722 * and nothing else.
11725 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11726 * (assuming ascii char codes, as the original implementation did) */
11727 #define is_special(c) \
11728 (((unsigned)(c) - 33 < 32) \
11729 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11731 unsigned char subtype;
11734 c = pgetc_eatbnl();
11735 if (c > 255 /* PEOA or PEOF */
11736 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11738 #if ENABLE_ASH_BASH_COMPAT
11739 if (syntax != DQSYNTAX && c == '\'')
11740 bash_dollar_squote = 1;
11745 } else if (c == '(') {
11746 /* $(command) or $((arith)) */
11747 if (pgetc_eatbnl() == '(') {
11748 #if ENABLE_SH_MATH_SUPPORT
11751 raise_error_syntax("you disabled math support for $((arith)) syntax");
11758 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11759 USTPUTC(CTLVAR, out);
11760 typeloc = out - (char *)stackblock();
11762 subtype = VSNORMAL;
11764 c = pgetc_eatbnl();
11769 /* $[{[#]]NAME[}] */
11772 c = pgetc_eatbnl();
11773 } while (is_in_name(c));
11774 } else if (isdigit(c)) {
11775 /* $[{[#]]NUM[}] */
11778 c = pgetc_eatbnl();
11779 } while (isdigit(c));
11780 } else if (is_special(c)) {
11781 /* $[{[#]]<specialchar>[}] */
11784 c = pgetc_eatbnl();
11785 if (!subtype && cc == '#') {
11786 subtype = VSLENGTH;
11787 if (c == '_' || isalnum(c))
11790 c = pgetc_eatbnl();
11791 if (cc == '}' || c != '}') {
11802 if (c != '}' && subtype == VSLENGTH) {
11803 /* ${#VAR didn't end with } */
11807 if (subtype == 0) {
11808 static const char types[] ALIGN1 = "}-+?=";
11809 /* ${VAR...} but not $VAR or ${#VAR} */
11810 /* c == first char after VAR */
11813 c = pgetc_eatbnl();
11814 #if ENABLE_ASH_BASH_COMPAT
11815 /* This check is only needed to not misinterpret
11816 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11819 if (!strchr(types, c)) {
11820 subtype = VSSUBSTR;
11822 break; /* "goto badsub" is bigger (!) */
11828 const char *p = strchr(types, c);
11831 subtype |= p - types + VSNORMAL;
11837 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11838 c = pgetc_eatbnl();
11844 #if ENABLE_ASH_BASH_COMPAT
11846 /* ${v/[/]pattern/repl} */
11847 //TODO: encode pattern and repl separately.
11848 // Currently ${v/$var_with_slash/repl} is horribly broken
11849 subtype = VSREPLACE;
11850 c = pgetc_eatbnl();
11853 subtype++; /* VSREPLACEALL */
11861 ((unsigned char *)stackblock())[typeloc] = subtype;
11862 if (subtype != VSNORMAL) {
11869 goto parsesub_return;
11873 * Called to parse command substitutions. Newstyle is set if the command
11874 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11875 * list of commands (passed by reference), and savelen is the number of
11876 * characters on the top of the stack which must be preserved.
11879 struct nodelist **nlpp;
11883 smallint saveprompt = 0;
11886 savelen = out - (char *)stackblock();
11889 * FIXME: this can allocate very large block on stack and SEGV.
11891 * echo "..<100kbytes>..`true` $(true) `true` ..."
11892 * allocates 100kb for every command subst. With about
11893 * a hundred command substitutions stack overflows.
11894 * With larger prepended string, SEGV happens sooner.
11896 str = alloca(savelen);
11897 memcpy(str, stackblock(), savelen);
11901 /* We must read until the closing backquote, giving special
11902 * treatment to some slashes, and then push the string and
11903 * reread it as input, interpreting it normally.
11909 STARTSTACKSTR(pout);
11913 setprompt_if(needprompt, 2);
11924 * If eating a newline, avoid putting
11925 * the newline into the new character
11926 * stream (via the STPUTC after the
11931 if (pc != '\\' && pc != '`' && pc != '$'
11932 && (!dblquote || pc != '"')
11934 STPUTC('\\', pout);
11936 if (pc <= 255 /* not PEOA or PEOF */) {
11942 IF_ASH_ALIAS(case PEOA:)
11943 startlinno = g_parsefile->linno;
11944 raise_error_syntax("EOF in backquote substitution");
11956 STPUTC('\0', pout);
11957 psavelen = pout - (char *)stackblock();
11958 if (psavelen > 0) {
11959 pstr = grabstackstr(pout);
11960 setinputstring(pstr);
11965 nlpp = &(*nlpp)->next;
11966 *nlpp = stzalloc(sizeof(**nlpp));
11967 /* (*nlpp)->next = NULL; - stzalloc did it */
11970 saveprompt = doprompt;
11977 doprompt = saveprompt;
11978 else if (readtoken() != TRP)
11979 raise_error_unexpected_syntax(TRP);
11984 * Start reading from old file again, ignoring any pushed back
11985 * tokens left from the backquote parsing
11990 while (stackblocksize() <= savelen)
11992 STARTSTACKSTR(out);
11994 memcpy(out, str, savelen);
11995 STADJUST(savelen, out);
11997 USTPUTC(CTLBACKQ, out);
11999 goto parsebackq_oldreturn;
12000 goto parsebackq_newreturn;
12003 #if ENABLE_SH_MATH_SUPPORT
12005 * Parse an arithmetic expansion (indicate start of one and set state)
12008 if (++arinest == 1) {
12009 prevsyntax = syntax;
12010 syntax = ARISYNTAX;
12012 USTPUTC(CTLARI, out);
12013 goto parsearith_return;
12016 } /* end of readtoken */
12019 * Read the next input token.
12020 * If the token is a word, we set backquotelist to the list of cmds in
12021 * backquotes. We set quoteflag to true if any part of the word was
12023 * If the token is TREDIR, then we set redirnode to a structure containing
12025 * In all cases, the variable startlinno is set to the number of the line
12026 * on which the token starts.
12028 * [Change comment: here documents and internal procedures]
12029 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12030 * word parsing code into a separate routine. In this case, readtoken
12031 * doesn't need to have any internal procedures, but parseword does.
12032 * We could also make parseoperator in essence the main routine, and
12033 * have parseword (readtoken1?) handle both words and redirection.]
12035 #define NEW_xxreadtoken
12036 #ifdef NEW_xxreadtoken
12037 /* singles must be first! */
12038 static const char xxreadtoken_chars[7] ALIGN1 = {
12039 '\n', '(', ')', /* singles */
12040 '&', '|', ';', /* doubles */
12044 #define xxreadtoken_singles 3
12045 #define xxreadtoken_doubles 3
12047 static const char xxreadtoken_tokens[] ALIGN1 = {
12048 TNL, TLP, TRP, /* only single occurrence allowed */
12049 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12050 TEOF, /* corresponds to trailing nul */
12051 TAND, TOR, TENDCASE /* if double occurrence */
12063 setprompt_if(needprompt, 2);
12064 startlinno = g_parsefile->linno;
12065 for (;;) { /* until token or start of word found */
12067 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12071 while ((c = pgetc()) != '\n' && c != PEOF)
12074 } else if (c == '\\') {
12075 if (pgetc() != '\n') {
12077 break; /* return readtoken1(...) */
12083 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12089 p = strchr(xxreadtoken_chars, c);
12091 break; /* return readtoken1(...) */
12093 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12095 if (cc == c) { /* double occurrence? */
12096 p += xxreadtoken_doubles + 1;
12099 #if ENABLE_ASH_BASH_COMPAT
12100 if (c == '&' && cc == '>') /* &> */
12101 break; /* return readtoken1(...) */
12106 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12111 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12113 #else /* old xxreadtoken */
12114 #define RETURN(token) return lasttoken = token
12124 setprompt_if(needprompt, 2);
12125 startlinno = g_parsefile->linno;
12126 for (;;) { /* until token or start of word found */
12129 case ' ': case '\t':
12130 IF_ASH_ALIAS(case PEOA:)
12133 while ((c = pgetc()) != '\n' && c != PEOF)
12138 if (pgetc() == '\n') {
12150 if (pgetc() == '&')
12155 if (pgetc() == '|')
12160 if (pgetc() == ';')
12173 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12176 #endif /* old xxreadtoken */
12182 int kwd = checkkwd;
12184 smallint alreadyseen = tokpushback;
12187 #if ENABLE_ASH_ALIAS
12203 if (t != TWORD || quoteflag) {
12208 * check for keywords
12210 if (kwd & CHKKWD) {
12211 const char *const *pp;
12213 pp = findkwd(wordtext);
12215 lasttoken = t = pp - tokname_array;
12216 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12221 if (checkkwd & CHKALIAS) {
12222 #if ENABLE_ASH_ALIAS
12224 ap = lookupalias(wordtext, 1);
12227 pushstring(ap->val, ap);
12237 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12239 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12255 * Read and parse a command. Returns NODE_EOF on end of file.
12256 * (NULL is a valid parse tree indicating a blank line.)
12258 static union node *
12259 parsecmd(int interact)
12264 doprompt = interact;
12265 setprompt_if(doprompt, doprompt);
12271 * Input any here documents.
12276 struct heredoc *here;
12279 here = heredoclist;
12280 heredoclist = NULL;
12283 setprompt_if(needprompt, 2);
12284 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12285 here->eofmark, here->striptabs);
12286 n = stzalloc(sizeof(struct narg));
12287 n->narg.type = NARG;
12288 /*n->narg.next = NULL; - stzalloc did it */
12289 n->narg.text = wordtext;
12290 n->narg.backquote = backquotelist;
12291 here->here->nhere.doc = n;
12298 * called by editline -- any expansions to the prompt should be added here.
12300 #if ENABLE_ASH_EXPAND_PRMT
12301 static const char *
12302 expandstr(const char *ps)
12307 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12308 * and token processing _can_ alter it (delete NULs etc). */
12309 setinputstring((char *)ps);
12311 saveprompt = doprompt;
12313 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12314 doprompt = saveprompt;
12318 n.narg.type = NARG;
12319 n.narg.next = NULL;
12320 n.narg.text = wordtext;
12321 n.narg.backquote = backquotelist;
12323 expandarg(&n, NULL, EXP_QUOTED);
12324 return stackblock();
12329 * Execute a command or commands contained in a string.
12332 evalstring(char *s, int flags)
12334 struct jmploc *volatile savehandler;
12335 struct jmploc jmploc;
12339 struct stackmark smark;
12344 setstackmark(&smark);
12347 /* On exception inside execution loop, we must popfile().
12348 * Try interactively:
12350 * command eval "a=b" # throws "is read only" error
12351 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12352 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12354 savehandler = exception_handler;
12355 ex = setjmp(jmploc.loc);
12358 exception_handler = &jmploc;
12360 while ((n = parsecmd(0)) != NODE_EOF) {
12363 i = evaltree(n, flags);
12366 popstackmark(&smark);
12371 popstackmark(&smark);
12375 exception_handler = savehandler;
12377 longjmp(exception_handler->loc, ex);
12383 * The eval command.
12385 static int FAST_FUNC
12386 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12395 STARTSTACKSTR(concat);
12397 concat = stack_putstr(p, concat);
12401 STPUTC(' ', concat);
12403 STPUTC('\0', concat);
12404 p = grabstackstr(concat);
12406 return evalstring(p, flags & EV_TESTED);
12412 * Read and execute commands.
12413 * "Top" is nonzero for the top level command loop;
12414 * it turns on prompting if the shell is interactive.
12420 struct stackmark smark;
12425 TRACE(("cmdloop(%d) called\n", top));
12429 setstackmark(&smark);
12432 showjobs(SHOW_CHANGED|SHOW_STDERR);
12435 if (iflag && top) {
12439 n = parsecmd(inter);
12441 if (DEBUG > 2 && debug && (n != NODE_EOF))
12444 if (n == NODE_EOF) {
12445 if (!top || numeof >= 50)
12447 if (!stoppedjobs()) {
12450 out2str("\nUse \"exit\" to leave shell.\n");
12453 } else if (nflag == 0) {
12456 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12459 i = evaltree(n, 0);
12463 popstackmark(&smark);
12467 evalskip &= ~SKIPFUNC;
12475 * Take commands from a file. To be compatible we should do a path
12476 * search for the file, which is necessary to find sub-commands.
12479 find_dot_file(char *name)
12482 const char *path = pathval();
12485 /* don't try this for absolute or relative paths */
12486 if (strchr(name, '/'))
12489 /* IIRC standards do not say whether . is to be searched.
12490 * And it is even smaller this way, making it unconditional for now:
12492 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12497 while ((fullname = path_advance(&path, name)) != NULL) {
12499 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12501 * Don't bother freeing here, since it will
12502 * be freed by the caller.
12506 if (fullname != name)
12507 stunalloc(fullname);
12510 /* not found in the PATH */
12511 ash_msg_and_raise_error("%s: not found", name);
12515 static int FAST_FUNC
12516 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12518 /* "false; . empty_file; echo $?" should print 0, not 1: */
12522 struct strlist *sp;
12523 volatile struct shparam saveparam;
12525 for (sp = cmdenviron; sp; sp = sp->next)
12526 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12528 nextopt(nullstr); /* handle possible "--" */
12532 /* bash says: "bash: .: filename argument required" */
12533 return 2; /* bash compat */
12536 /* This aborts if file isn't found, which is POSIXly correct.
12537 * bash returns exitcode 1 instead.
12539 fullname = find_dot_file(argv[0]);
12541 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12543 saveparam = shellparam;
12544 shellparam.malloced = 0;
12548 shellparam.nparam = argc;
12549 shellparam.p = argv;
12552 /* This aborts if file can't be opened, which is POSIXly correct.
12553 * bash returns exitcode 1 instead.
12555 setinputfile(fullname, INPUT_PUSH_FILE);
12556 commandname = fullname;
12557 status = cmdloop(0);
12561 freeparam(&shellparam);
12562 shellparam = saveparam;
12568 static int FAST_FUNC
12569 exitcmd(int argc UNUSED_PARAM, char **argv)
12574 exitstatus = number(argv[1]);
12575 raise_exception(EXEXIT);
12580 * Read a file containing shell functions.
12583 readcmdfile(char *name)
12585 setinputfile(name, INPUT_PUSH_FILE);
12591 /* ============ find_command inplementation */
12594 * Resolve a command name. If you change this routine, you may have to
12595 * change the shellexec routine as well.
12598 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12600 struct tblentry *cmdp;
12607 struct builtincmd *bcmd;
12609 /* If name contains a slash, don't use PATH or hash table */
12610 if (strchr(name, '/') != NULL) {
12611 entry->u.index = -1;
12612 if (act & DO_ABS) {
12613 while (stat(name, &statb) < 0) {
12615 if (errno == EINTR)
12618 entry->cmdtype = CMDUNKNOWN;
12622 entry->cmdtype = CMDNORMAL;
12626 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12628 updatetbl = (path == pathval());
12631 if (strstr(path, "%builtin") != NULL)
12632 act |= DO_ALTBLTIN;
12635 /* If name is in the table, check answer will be ok */
12636 cmdp = cmdlookup(name, 0);
12637 if (cmdp != NULL) {
12640 switch (cmdp->cmdtype) {
12658 } else if (cmdp->rehash == 0)
12659 /* if not invalidated by cd, we're done */
12663 /* If %builtin not in path, check for builtin next */
12664 bcmd = find_builtin(name);
12666 if (IS_BUILTIN_REGULAR(bcmd))
12667 goto builtin_success;
12668 if (act & DO_ALTPATH) {
12669 if (!(act & DO_ALTBLTIN))
12670 goto builtin_success;
12671 } else if (builtinloc <= 0) {
12672 goto builtin_success;
12676 #if ENABLE_FEATURE_SH_STANDALONE
12678 int applet_no = find_applet_by_name(name);
12679 if (applet_no >= 0) {
12680 entry->cmdtype = CMDNORMAL;
12681 entry->u.index = -2 - applet_no;
12687 /* We have to search path. */
12688 prev = -1; /* where to start */
12689 if (cmdp && cmdp->rehash) { /* doing a rehash */
12690 if (cmdp->cmdtype == CMDBUILTIN)
12693 prev = cmdp->param.index;
12699 while ((fullname = path_advance(&path, name)) != NULL) {
12700 stunalloc(fullname);
12701 /* NB: code below will still use fullname
12702 * despite it being "unallocated" */
12705 if (prefix(pathopt, "builtin")) {
12707 goto builtin_success;
12710 if ((act & DO_NOFUNC)
12711 || !prefix(pathopt, "func")
12712 ) { /* ignore unimplemented options */
12716 /* if rehash, don't redo absolute path names */
12717 if (fullname[0] == '/' && idx <= prev) {
12720 TRACE(("searchexec \"%s\": no change\n", name));
12723 while (stat(fullname, &statb) < 0) {
12725 if (errno == EINTR)
12728 if (errno != ENOENT && errno != ENOTDIR)
12732 e = EACCES; /* if we fail, this will be the error */
12733 if (!S_ISREG(statb.st_mode))
12735 if (pathopt) { /* this is a %func directory */
12736 stalloc(strlen(fullname) + 1);
12737 /* NB: stalloc will return space pointed by fullname
12738 * (because we don't have any intervening allocations
12739 * between stunalloc above and this stalloc) */
12740 readcmdfile(fullname);
12741 cmdp = cmdlookup(name, 0);
12742 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12743 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12744 stunalloc(fullname);
12747 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12749 entry->cmdtype = CMDNORMAL;
12750 entry->u.index = idx;
12754 cmdp = cmdlookup(name, 1);
12755 cmdp->cmdtype = CMDNORMAL;
12756 cmdp->param.index = idx;
12761 /* We failed. If there was an entry for this command, delete it */
12762 if (cmdp && updatetbl)
12763 delete_cmd_entry();
12765 ash_msg("%s: %s", name, errmsg(e, "not found"));
12766 entry->cmdtype = CMDUNKNOWN;
12771 entry->cmdtype = CMDBUILTIN;
12772 entry->u.cmd = bcmd;
12776 cmdp = cmdlookup(name, 1);
12777 cmdp->cmdtype = CMDBUILTIN;
12778 cmdp->param.cmd = bcmd;
12782 entry->cmdtype = cmdp->cmdtype;
12783 entry->u = cmdp->param;
12788 * The trap builtin.
12790 static int FAST_FUNC
12791 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12795 int signo, exitcode;
12800 for (signo = 0; signo < NSIG; signo++) {
12801 char *tr = trap_ptr[signo];
12803 /* note: bash adds "SIG", but only if invoked
12804 * as "bash". If called as "sh", or if set -o posix,
12805 * then it prints short signal names.
12806 * We are printing short names: */
12807 out1fmt("trap -- %s %s\n",
12809 get_signame(signo));
12810 /* trap_ptr != trap only if we are in special-cased `trap` code.
12811 * In this case, we will exit very soon, no need to free(). */
12812 /* if (trap_ptr != trap && tp[0]) */
12817 if (trap_ptr != trap) {
12830 signo = get_signum(*ap);
12832 /* Mimic bash message exactly */
12833 ash_msg("%s: invalid signal specification", *ap);
12839 if (LONE_DASH(action))
12842 if (action[0]) /* not NULL and not "" and not "-" */
12843 may_have_traps = 1;
12844 action = ckstrdup(action);
12848 trap[signo] = action;
12859 /* ============ Builtins */
12861 #if ENABLE_ASH_HELP
12862 static int FAST_FUNC
12863 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12869 "Built-in commands:\n"
12870 "------------------\n");
12871 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12872 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12873 builtintab[i].name + 1);
12879 # if ENABLE_FEATURE_SH_STANDALONE
12881 const char *a = applet_names;
12883 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12888 while (*a++ != '\0')
12893 newline_and_flush(stdout);
12894 return EXIT_SUCCESS;
12899 static int FAST_FUNC
12900 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12902 show_history(line_input_state);
12903 return EXIT_SUCCESS;
12908 * The export and readonly commands.
12910 static int FAST_FUNC
12911 exportcmd(int argc UNUSED_PARAM, char **argv)
12921 /* "readonly" in bash accepts, but ignores -n.
12922 * We do the same: it saves a conditional in nextopt's param.
12925 while ((opt = nextopt("np")) != '\0') {
12927 flag_off = VEXPORT;
12930 if (argv[0][0] == 'r') {
12932 flag_off = 0; /* readonly ignores -n */
12934 flag_off = ~flag_off;
12936 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12942 p = strchr(name, '=');
12946 vp = *findvar(hashvar(name), name);
12948 vp->flags = ((vp->flags | flag) & flag_off);
12952 setvar(name, p, (flag & flag_off));
12953 } while ((name = *++aptr) != NULL);
12958 /* No arguments. Show the list of exported or readonly vars.
12961 showvars(argv[0], flag, 0);
12966 * Delete a function if it exists.
12969 unsetfunc(const char *name)
12971 struct tblentry *cmdp;
12973 cmdp = cmdlookup(name, 0);
12974 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12975 delete_cmd_entry();
12979 * The unset builtin command. We unset the function before we unset the
12980 * variable to allow a function to be unset when there is a readonly variable
12981 * with the same name.
12983 static int FAST_FUNC
12984 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12991 while ((i = nextopt("vf")) != 0) {
12995 for (ap = argptr; *ap; ap++) {
13008 static const unsigned char timescmd_str[] ALIGN1 = {
13009 ' ', offsetof(struct tms, tms_utime),
13010 '\n', offsetof(struct tms, tms_stime),
13011 ' ', offsetof(struct tms, tms_cutime),
13012 '\n', offsetof(struct tms, tms_cstime),
13015 static int FAST_FUNC
13016 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13018 unsigned long clk_tck, s, t;
13019 const unsigned char *p;
13022 clk_tck = bb_clk_tck();
13027 t = *(clock_t *)(((char *) &buf) + p[1]);
13030 out1fmt("%lum%lu.%03lus%c",
13032 (t * 1000) / clk_tck,
13040 #if ENABLE_SH_MATH_SUPPORT
13042 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13043 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13045 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13047 static int FAST_FUNC
13048 letcmd(int argc UNUSED_PARAM, char **argv)
13054 ash_msg_and_raise_error("expression expected");
13056 i = ash_arith(*argv);
13064 * The read builtin. Options:
13065 * -r Do not interpret '\' specially
13066 * -s Turn off echo (tty only)
13067 * -n NCHARS Read NCHARS max
13068 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13069 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13070 * -u FD Read from given FD instead of fd 0
13071 * This uses unbuffered input, which may be avoidable in some cases.
13072 * TODO: bash also has:
13073 * -a ARRAY Read into array[0],[1],etc
13074 * -d DELIM End on DELIM char, not newline
13075 * -e Use line editing (tty only)
13077 static int FAST_FUNC
13078 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13080 char *opt_n = NULL;
13081 char *opt_p = NULL;
13082 char *opt_t = NULL;
13083 char *opt_u = NULL;
13084 int read_flags = 0;
13088 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13097 read_flags |= BUILTIN_READ_SILENT;
13103 read_flags |= BUILTIN_READ_RAW;
13113 /* "read -s" needs to save/restore termios, can't allow ^C
13114 * to jump out of it.
13117 r = shell_builtin_read(setvar0,
13119 bltinlookup("IFS"), /* can be NULL */
13128 if ((uintptr_t)r > 1)
13129 ash_msg_and_raise_error(r);
13131 return (uintptr_t)r;
13134 static int FAST_FUNC
13135 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13137 static const char permuser[3] ALIGN1 = "ogu";
13140 int symbolic_mode = 0;
13142 while (nextopt("S") != '\0') {
13151 if (*argptr == NULL) {
13152 if (symbolic_mode) {
13153 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13160 *p++ = permuser[i];
13162 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13163 if (!(mask & 0400)) *p++ = 'r';
13164 if (!(mask & 0200)) *p++ = 'w';
13165 if (!(mask & 0100)) *p++ = 'x';
13173 out1fmt("%04o\n", mask);
13176 char *modestr = *argptr;
13177 /* numeric umasks are taken as-is */
13178 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13179 if (!isdigit(modestr[0]))
13181 mask = bb_parse_mode(modestr, mask);
13182 if ((unsigned)mask > 0777) {
13183 ash_msg_and_raise_error("illegal mode: %s", modestr);
13185 if (!isdigit(modestr[0]))
13192 static int FAST_FUNC
13193 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13195 return shell_builtin_ulimit(argv);
13198 /* ============ main() and helpers */
13201 * Called to exit the shell.
13210 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13211 save_history(line_input_state);
13213 status = exitstatus;
13214 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13215 if (setjmp(loc.loc)) {
13216 if (exception_type == EXEXIT)
13217 status = exitstatus;
13220 exception_handler = &loc;
13226 /*free(p); - we'll exit soon */
13229 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13230 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13233 flush_stdout_stderr();
13241 /* we will never free this */
13242 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13244 sigmode[SIGCHLD - 1] = S_DFL;
13245 setsignal(SIGCHLD);
13247 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13248 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13250 signal(SIGHUP, SIG_DFL);
13255 struct stat st1, st2;
13258 for (envp = environ; envp && *envp; envp++) {
13259 p = endofname(*envp);
13260 if (p != *envp && *p == '=') {
13261 setvareq(*envp, VEXPORT|VTEXTFIXED);
13265 setvareq((char*)defoptindvar, VTEXTFIXED);
13267 setvar0("PPID", utoa(getppid()));
13268 #if ENABLE_ASH_BASH_COMPAT
13269 p = lookupvar("SHLVL");
13270 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13271 if (!lookupvar("HOSTNAME")) {
13272 struct utsname uts;
13274 setvar0("HOSTNAME", uts.nodename);
13277 p = lookupvar("PWD");
13279 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13280 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13290 //usage:#define ash_trivial_usage
13291 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13292 //usage:#define ash_full_usage "\n\n"
13293 //usage: "Unix shell interpreter"
13295 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13296 //usage:# define sh_trivial_usage ash_trivial_usage
13297 //usage:# define sh_full_usage ash_full_usage
13299 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13300 //usage:# define bash_trivial_usage ash_trivial_usage
13301 //usage:# define bash_full_usage ash_full_usage
13305 * Process the shell command line arguments.
13308 procargs(char **argv)
13311 const char *xminusc;
13316 /* if (xargv[0]) - mmm, this is always true! */
13318 for (i = 0; i < NOPTS; i++)
13321 if (options(/*cmdline:*/ 1)) {
13322 /* it already printed err message */
13323 raise_exception(EXERROR);
13327 if (*xargv == NULL) {
13329 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13332 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13336 for (i = 0; i < NOPTS; i++)
13337 if (optlist[i] == 2)
13342 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13347 } else if (!sflag) {
13348 setinputfile(*xargv, 0);
13351 commandname = arg0;
13354 shellparam.p = xargv;
13355 #if ENABLE_ASH_GETOPTS
13356 shellparam.optind = 1;
13357 shellparam.optoff = -1;
13359 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13361 shellparam.nparam++;
13368 * Read /etc/profile, ~/.profile, $ENV.
13371 read_profile(const char *name)
13373 name = expandstr(name);
13374 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13381 * This routine is called when an error or an interrupt occurs in an
13382 * interactive shell and control is returned to the main command loop.
13383 * (In dash, this function is auto-generated by build machinery).
13392 /* from expand.c: */
13395 /* from input.c: */
13396 g_parsefile->left_in_buffer = 0;
13397 g_parsefile->left_in_line = 0; /* clear input buffer */
13400 /* from redir.c: */
13402 popredir(/*drop:*/ 0, /*restore:*/ 0);
13406 static short profile_buf[16384];
13407 extern int etext();
13411 * Main routine. We initialize things, parse the arguments, execute
13412 * profiles if we're a login shell, and then call cmdloop to execute
13413 * commands. The setjmp call sets up the location to jump to when an
13414 * exception occurs. When an exception occurs the variable "state"
13415 * is used to figure out how far we had gotten.
13417 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13418 int ash_main(int argc UNUSED_PARAM, char **argv)
13420 volatile smallint state;
13421 struct jmploc jmploc;
13422 struct stackmark smark;
13424 /* Initialize global data */
13428 #if ENABLE_ASH_ALIAS
13434 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13437 #if ENABLE_FEATURE_EDITING
13438 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13441 if (setjmp(jmploc.loc)) {
13447 e = exception_type;
13449 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13453 newline_and_flush(stderr);
13456 popstackmark(&smark);
13457 FORCE_INT_ON; /* enable interrupts */
13466 exception_handler = &jmploc;
13467 rootpid = getpid();
13470 setstackmark(&smark);
13473 TRACE(("Shell args: "));
13474 trace_puts_args(argv);
13477 if (argv[0] && argv[0][0] == '-')
13483 read_profile("/etc/profile");
13486 hp = lookupvar("HOME");
13488 read_profile("$HOME/.profile");
13494 getuid() == geteuid() && getgid() == getegid() &&
13498 const char *shinit = lookupvar("ENV");
13499 if (shinit != NULL && *shinit != '\0')
13500 read_profile(shinit);
13502 popstackmark(&smark);
13506 /* evalstring pushes parsefile stack.
13507 * Ensure we don't falsely claim that 0 (stdin)
13508 * is one of stacked source fds.
13509 * Testcase: ash -c 'exec 1>&0' must not complain. */
13510 // if (!sflag) g_parsefile->pf_fd = -1;
13511 // ^^ not necessary since now we special-case fd 0
13512 // in is_hidden_fd() to not be considered "hidden fd"
13513 evalstring(minusc, 0);
13516 if (sflag || minusc == NULL) {
13517 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13519 const char *hp = lookupvar("HISTFILE");
13521 hp = lookupvar("HOME");
13523 hp = concat_path_file(hp, ".ash_history");
13524 setvar0("HISTFILE", hp);
13526 hp = lookupvar("HISTFILE");
13530 line_input_state->hist_file = hp;
13531 # if ENABLE_FEATURE_SH_HISTFILESIZE
13532 hp = lookupvar("HISTFILESIZE");
13533 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13537 state4: /* XXX ??? - why isn't this before the "if" statement */
13545 extern void _mcleanup(void);
13549 TRACE(("End of main reached\n"));
13556 * Copyright (c) 1989, 1991, 1993, 1994
13557 * The Regents of the University of California. All rights reserved.
13559 * This code is derived from software contributed to Berkeley by
13560 * Kenneth Almquist.
13562 * Redistribution and use in source and binary forms, with or without
13563 * modification, are permitted provided that the following conditions
13565 * 1. Redistributions of source code must retain the above copyright
13566 * notice, this list of conditions and the following disclaimer.
13567 * 2. Redistributions in binary form must reproduce the above copyright
13568 * notice, this list of conditions and the following disclaimer in the
13569 * documentation and/or other materials provided with the distribution.
13570 * 3. Neither the name of the University nor the names of its contributors
13571 * may be used to endorse or promote products derived from this software
13572 * without specific prior written permission.
13574 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13575 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13576 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13577 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13578 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13579 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13580 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13581 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13582 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13583 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF