1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
43 #include <sys/utsname.h> /* for setting $HOSTNAME */
45 #include "busybox.h" /* for applet_names */
47 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
48 /* Bionic at least up to version 24 has no glob() */
49 # undef ENABLE_ASH_INTERNAL_GLOB
50 # define ENABLE_ASH_INTERNAL_GLOB 1
53 #if !ENABLE_ASH_INTERNAL_GLOB
58 #include "shell_common.h"
59 #if ENABLE_SH_MATH_SUPPORT
62 #if ENABLE_ASH_RANDOM_SUPPORT
65 # define CLEAR_RANDOM_T(rnd) ((void)0)
68 #include "NUM_APPLETS.h"
70 /* STANDALONE does not make sense, and won't compile */
71 # undef CONFIG_FEATURE_SH_STANDALONE
72 # undef ENABLE_FEATURE_SH_STANDALONE
73 # undef IF_FEATURE_SH_STANDALONE
74 # undef IF_NOT_FEATURE_SH_STANDALONE
75 # define ENABLE_FEATURE_SH_STANDALONE 0
76 # define IF_FEATURE_SH_STANDALONE(...)
77 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
81 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
85 # error "Do not even bother, ash will not run on NOMMU machine"
91 //config: depends on !NOMMU
93 //config: Tha 'ash' shell adds about 60k in the default configuration and is
94 //config: the most complete and most pedantically correct shell included with
95 //config: busybox. This shell is actually a derivative of the Debian 'dash'
96 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
97 //config: (written by Kenneth Almquist) from NetBSD.
99 //config:config ASH_OPTIMIZE_FOR_SIZE
100 //config: bool "Optimize for size instead of speed"
102 //config: depends on ASH
104 //config: Compile ash for reduced size at the price of speed.
106 //config:config ASH_INTERNAL_GLOB
107 //config: bool "Use internal glob() implementation"
109 //config: depends on ASH
111 //config: Do not use glob() function from libc, use internal implementation.
112 //config: Use this if you are getting "glob.h: No such file or directory"
113 //config: or similar build errors.
115 //config:config ASH_RANDOM_SUPPORT
116 //config: bool "Pseudorandom generator and $RANDOM variable"
118 //config: depends on ASH
120 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
121 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
122 //config: You can reset the generator by using a specified start value.
123 //config: After "unset RANDOM" the generator will switch off and this
124 //config: variable will no longer have special treatment.
126 //config:config ASH_EXPAND_PRMT
127 //config: bool "Expand prompt string"
129 //config: depends on ASH
131 //config: "PS#" may contain volatile content, such as backquote commands.
132 //config: This option recreates the prompt string from the environment
133 //config: variable each time it is displayed.
135 //config:config ASH_BASH_COMPAT
136 //config: bool "bash-compatible extensions"
138 //config: depends on ASH
140 //config: Enable bash-compatible extensions.
142 //config:config ASH_IDLE_TIMEOUT
143 //config: bool "Idle timeout variable"
145 //config: depends on ASH
147 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
149 //config:config ASH_JOB_CONTROL
150 //config: bool "Job control"
152 //config: depends on ASH
154 //config: Enable job control in the ash shell.
156 //config:config ASH_ALIAS
157 //config: bool "Alias support"
159 //config: depends on ASH
161 //config: Enable alias support in the ash shell.
163 //config:config ASH_GETOPTS
164 //config: bool "Builtin getopt to parse positional parameters"
166 //config: depends on ASH
168 //config: Enable support for getopts builtin in ash.
170 //config:config ASH_BUILTIN_ECHO
171 //config: bool "Builtin version of 'echo'"
173 //config: depends on ASH
175 //config: Enable support for echo builtin in ash.
177 //config:config ASH_BUILTIN_PRINTF
178 //config: bool "Builtin version of 'printf'"
180 //config: depends on ASH
182 //config: Enable support for printf builtin in ash.
184 //config:config ASH_BUILTIN_TEST
185 //config: bool "Builtin version of 'test'"
187 //config: depends on ASH
189 //config: Enable support for test builtin in ash.
191 //config:config ASH_HELP
192 //config: bool "help builtin"
194 //config: depends on ASH
196 //config: Enable help builtin in ash.
198 //config:config ASH_CMDCMD
199 //config: bool "'command' command to override shell builtins"
201 //config: depends on ASH
203 //config: Enable support for the ash 'command' builtin, which allows
204 //config: you to run the specified command with the specified arguments,
205 //config: even when there is an ash builtin command with the same name.
207 //config:config ASH_MAIL
208 //config: bool "Check for new mail on interactive shells"
210 //config: depends on ASH
212 //config: Enable "check for new mail" function in the ash shell.
215 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
216 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
217 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
219 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
220 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
223 /* ============ Hash table sizes. Configurable. */
227 #define CMDTABLESIZE 31 /* should be prime */
230 /* ============ Shell options */
232 static const char *const optletters_optnames[] = {
247 #if ENABLE_ASH_BASH_COMPAT
256 #define optletters(n) optletters_optnames[n][0]
257 #define optnames(n) (optletters_optnames[n] + 1)
259 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
262 /* ============ Misc data */
264 #define msg_illnum "Illegal number: %s"
267 * We enclose jmp_buf in a structure so that we can declare pointers to
268 * jump locations. The global variable handler contains the location to
269 * jump to when an exception occurs, and the global variable exception_type
270 * contains a code identifying the exception. To implement nested
271 * exception handlers, the user should save the value of handler on entry
272 * to an inner scope, set handler to point to a jmploc structure for the
273 * inner scope, and restore handler on exit from the scope.
279 struct globals_misc {
280 uint8_t exitstatus; /* exit status of last command */
281 uint8_t back_exitstatus;/* exit status of backquoted command */
282 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
283 int rootpid; /* pid of main shell */
284 /* shell level: 0 for the main shell, 1 for its children, and so on */
286 #define rootshell (!shlvl)
287 char *minusc; /* argument to -c option */
289 char *curdir; // = nullstr; /* current working directory */
290 char *physdir; // = nullstr; /* physical working directory */
292 char *arg0; /* value of $0 */
294 struct jmploc *exception_handler;
296 volatile int suppress_int; /* counter */
297 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
298 /* last pending signal */
299 volatile /*sig_atomic_t*/ smallint pending_sig;
300 smallint exception_type; /* kind of exception (0..5) */
302 #define EXINT 0 /* SIGINT received */
303 #define EXERROR 1 /* a generic error */
304 #define EXEXIT 4 /* exit the shell */
305 #define EXSIG 5 /* trapped signal in wait(1) */
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 pending_sig (G_misc.pending_sig )
375 #define isloginsh (G_misc.isloginsh )
376 #define nullstr (G_misc.nullstr )
377 #define optlist (G_misc.optlist )
378 #define sigmode (G_misc.sigmode )
379 #define gotsig (G_misc.gotsig )
380 #define may_have_traps (G_misc.may_have_traps )
381 #define trap (G_misc.trap )
382 #define trap_ptr (G_misc.trap_ptr )
383 #define random_gen (G_misc.random_gen )
384 #define backgndpid (G_misc.backgndpid )
385 #define INIT_G_misc() do { \
386 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
394 /* ============ DEBUG */
396 static void trace_printf(const char *fmt, ...);
397 static void trace_vprintf(const char *fmt, va_list va);
398 # define TRACE(param) trace_printf param
399 # define TRACEV(param) trace_vprintf param
400 # define close(fd) do { \
402 if (close(dfd) < 0) \
403 bb_error_msg("bug on %d: closing %d(0x%x)", \
404 __LINE__, dfd, dfd); \
407 # define TRACE(param)
408 # define TRACEV(param)
412 /* ============ Utility functions */
413 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
414 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
417 isdigit_str9(const char *str)
419 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
420 while (--maxlen && isdigit(*str))
422 return (*str == '\0');
426 var_end(const char *var)
435 /* ============ Interrupts / exceptions */
437 static void exitshell(void) NORETURN;
440 * These macros allow the user to suspend the handling of interrupt signals
441 * over a period of time. This is similar to SIGHOLD or to sigblock, but
442 * much more efficient and portable. (But hacking the kernel is so much
443 * more fun than worrying about efficiency and portability. :-))
445 #define INT_OFF do { \
451 * Called to raise an exception. Since C doesn't include exceptions, we
452 * just do a longjmp to the exception handler. The type of exception is
453 * stored in the global variable "exception_type".
455 static void raise_exception(int) NORETURN;
457 raise_exception(int e)
460 if (exception_handler == NULL)
465 longjmp(exception_handler->loc, 1);
468 #define raise_exception(e) do { \
469 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
470 raise_exception(e); \
475 * Called when a SIGINT is received. (If the user specifies
476 * that SIGINT is to be trapped or ignored using the trap builtin, then
477 * this routine is not called.) Suppressint is nonzero when interrupts
478 * are held using the INT_OFF macro. (The test for iflag is just
479 * defensive programming.)
481 static void raise_interrupt(void) NORETURN;
483 raise_interrupt(void)
488 /* Signal is not automatically unmasked after it is raised,
489 * do it ourself - unmask all signals */
490 sigprocmask_allsigs(SIG_UNBLOCK);
491 /* pending_sig = 0; - now done in signal_handler() */
494 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
495 if (!(rootshell && iflag)) {
496 /* Kill ourself with SIGINT */
497 signal(SIGINT, SIG_DFL);
502 /* bash: ^C even on empty command line sets $? */
503 exitstatus = SIGINT + 128;
504 raise_exception(ex_type);
508 #define raise_interrupt() do { \
509 TRACE(("raising interrupt on line %d\n", __LINE__)); \
514 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
518 if (--suppress_int == 0 && pending_int) {
522 #define INT_ON int_on()
523 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
531 #define FORCE_INT_ON force_int_on()
533 #define SAVE_INT(v) ((v) = suppress_int)
535 #define RESTORE_INT(v) do { \
537 suppress_int = (v); \
538 if (suppress_int == 0 && pending_int) \
543 /* ============ Stdout/stderr output */
546 outstr(const char *p, FILE *file)
554 flush_stdout_stderr(void)
561 /* Was called outcslow(c,FILE*), but c was always '\n' */
563 newline_and_flush(FILE *dest)
571 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
573 out1fmt(const char *fmt, ...)
580 r = vprintf(fmt, ap);
586 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
588 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
595 ret = vsnprintf(outbuf, length, fmt, ap);
602 out1str(const char *p)
608 out2str(const char *p)
611 flush_stdout_stderr();
615 /* ============ Parser structures */
617 /* control characters in argument strings */
618 #define CTL_FIRST CTLESC
619 #define CTLESC ((unsigned char)'\201') /* escape next character */
620 #define CTLVAR ((unsigned char)'\202') /* variable defn */
621 #define CTLENDVAR ((unsigned char)'\203')
622 #define CTLBACKQ ((unsigned char)'\204')
623 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
624 #define CTLENDARI ((unsigned char)'\207')
625 #define CTLQUOTEMARK ((unsigned char)'\210')
626 #define CTL_LAST CTLQUOTEMARK
628 /* variable substitution byte (follows CTLVAR) */
629 #define VSTYPE 0x0f /* type of variable substitution */
630 #define VSNUL 0x10 /* colon--treat the empty string as unset */
632 /* values of VSTYPE field */
633 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
634 #define VSMINUS 0x2 /* ${var-text} */
635 #define VSPLUS 0x3 /* ${var+text} */
636 #define VSQUESTION 0x4 /* ${var?message} */
637 #define VSASSIGN 0x5 /* ${var=text} */
638 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
639 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
640 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
641 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
642 #define VSLENGTH 0xa /* ${#var} */
643 #if ENABLE_ASH_BASH_COMPAT
644 #define VSSUBSTR 0xc /* ${var:position:length} */
645 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
646 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
649 static const char dolatstr[] ALIGN1 = {
650 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
652 #define DOLATSTRLEN 6
671 #if ENABLE_ASH_BASH_COMPAT
688 smallint type; /* Nxxxx */
691 union node *redirect;
696 smallint pipe_backgnd;
697 struct nodelist *cmdlist;
703 union node *redirect;
716 union node *elsepart;
743 struct nodelist *backquote;
746 /* nfile and ndup layout must match!
747 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
748 * that it is actually NTO2 (>&file), and change its type.
765 char *_unused_expfname;
784 struct nredir nredir;
785 struct nbinary nbinary;
789 struct nclist nclist;
798 * NODE_EOF is returned by parsecmd when it encounters an end of file.
799 * It must be distinct from NULL.
801 #define NODE_EOF ((union node *) -1L)
804 struct nodelist *next;
817 freefunc(struct funcnode *f)
819 if (f && --f->count < 0)
824 /* ============ Debugging output */
828 static FILE *tracefile;
831 trace_printf(const char *fmt, ...)
838 fprintf(tracefile, "%u ", (int) time(NULL));
840 fprintf(tracefile, "[%u] ", (int) getpid());
842 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
844 vfprintf(tracefile, fmt, va);
849 trace_vprintf(const char *fmt, va_list va)
854 fprintf(tracefile, "%u ", (int) time(NULL));
856 fprintf(tracefile, "[%u] ", (int) getpid());
858 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
859 vfprintf(tracefile, fmt, va);
863 trace_puts(const char *s)
871 trace_puts_quoted(char *s)
878 putc('"', tracefile);
879 for (p = s; *p; p++) {
880 switch ((unsigned char)*p) {
881 case '\n': c = 'n'; goto backslash;
882 case '\t': c = 't'; goto backslash;
883 case '\r': c = 'r'; goto backslash;
884 case '\"': c = '\"'; goto backslash;
885 case '\\': c = '\\'; goto backslash;
886 case CTLESC: c = 'e'; goto backslash;
887 case CTLVAR: c = 'v'; goto backslash;
888 case CTLBACKQ: c = 'q'; goto backslash;
890 putc('\\', tracefile);
894 if (*p >= ' ' && *p <= '~')
897 putc('\\', tracefile);
898 putc((*p >> 6) & 03, tracefile);
899 putc((*p >> 3) & 07, tracefile);
900 putc(*p & 07, tracefile);
905 putc('"', tracefile);
909 trace_puts_args(char **ap)
916 trace_puts_quoted(*ap);
918 putc('\n', tracefile);
921 putc(' ', tracefile);
936 /* leave open because libedit might be using it */
939 strcpy(s, "./trace");
941 if (!freopen(s, "a", tracefile)) {
942 fprintf(stderr, "Can't re-open %s\n", s);
947 tracefile = fopen(s, "a");
948 if (tracefile == NULL) {
949 fprintf(stderr, "Can't open %s\n", s);
955 flags = fcntl(fileno(tracefile), F_GETFL);
957 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
959 setlinebuf(tracefile);
960 fputs("\nTracing started.\n", tracefile);
964 indent(int amount, char *pfx, FILE *fp)
968 for (i = 0; i < amount; i++) {
969 if (pfx && i == amount - 1)
975 /* little circular references here... */
976 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
979 sharg(union node *arg, FILE *fp)
982 struct nodelist *bqlist;
983 unsigned char subtype;
985 if (arg->type != NARG) {
986 out1fmt("<node type %d>\n", arg->type);
989 bqlist = arg->narg.backquote;
990 for (p = arg->narg.text; *p; p++) {
991 switch ((unsigned char)*p) {
1000 if (subtype == VSLENGTH)
1008 if (subtype & VSNUL)
1011 switch (subtype & VSTYPE) {
1037 case VSTRIMRIGHTMAX:
1044 out1fmt("<subtype %d>", subtype);
1053 shtree(bqlist->n, -1, NULL, fp);
1064 shcmd(union node *cmd, FILE *fp)
1072 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1078 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1082 switch (np->nfile.type) {
1083 case NTO: s = ">>"+1; dftfd = 1; break;
1084 case NCLOBBER: s = ">|"; dftfd = 1; break;
1085 case NAPPEND: s = ">>"; dftfd = 1; break;
1086 #if ENABLE_ASH_BASH_COMPAT
1089 case NTOFD: s = ">&"; dftfd = 1; break;
1090 case NFROM: s = "<"; break;
1091 case NFROMFD: s = "<&"; break;
1092 case NFROMTO: s = "<>"; break;
1093 default: s = "*error*"; break;
1095 if (np->nfile.fd != dftfd)
1096 fprintf(fp, "%d", np->nfile.fd);
1098 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1099 fprintf(fp, "%d", np->ndup.dupfd);
1101 sharg(np->nfile.fname, fp);
1108 shtree(union node *n, int ind, char *pfx, FILE *fp)
1110 struct nodelist *lp;
1116 indent(ind, pfx, fp);
1118 if (n == NODE_EOF) {
1133 shtree(n->nbinary.ch1, ind, NULL, fp);
1136 shtree(n->nbinary.ch2, ind, NULL, fp);
1144 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1145 shtree(lp->n, 0, NULL, fp);
1149 if (n->npipe.pipe_backgnd)
1155 fprintf(fp, "<node type %d>", n->type);
1163 showtree(union node *n)
1165 trace_puts("showtree called\n");
1166 shtree(n, 1, NULL, stderr);
1172 /* ============ Parser data */
1175 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1178 struct strlist *next;
1185 struct strpush *prev; /* preceding string on stack */
1187 int prev_left_in_line;
1188 #if ENABLE_ASH_ALIAS
1189 struct alias *ap; /* if push was associated with an alias */
1191 char *string; /* remember the string since it may change */
1193 /* Remember last two characters for pungetc. */
1196 /* Number of outstanding calls to pungetc. */
1201 struct parsefile *prev; /* preceding file on stack */
1202 int linno; /* current line */
1203 int pf_fd; /* file descriptor (or -1 if string) */
1204 int left_in_line; /* number of chars left in this line */
1205 int left_in_buffer; /* number of chars left in this buffer past the line */
1206 char *next_to_pgetc; /* next char in buffer */
1207 char *buf; /* input buffer */
1208 struct strpush *strpush; /* for pushing strings at this level */
1209 struct strpush basestrpush; /* so pushing one is fast */
1211 /* Remember last two characters for pungetc. */
1214 /* Number of outstanding calls to pungetc. */
1218 static struct parsefile basepf; /* top level input file */
1219 static struct parsefile *g_parsefile = &basepf; /* current input file */
1220 static int startlinno; /* line # where last token started */
1221 static char *commandname; /* currently executing command */
1222 static struct strlist *cmdenviron; /* environment for builtin command */
1225 /* ============ Message printing */
1228 ash_vmsg(const char *msg, va_list ap)
1230 fprintf(stderr, "%s: ", arg0);
1232 if (strcmp(arg0, commandname))
1233 fprintf(stderr, "%s: ", commandname);
1234 if (!iflag || g_parsefile->pf_fd > 0)
1235 fprintf(stderr, "line %d: ", startlinno);
1237 vfprintf(stderr, msg, ap);
1238 newline_and_flush(stderr);
1242 * Exverror is called to raise the error exception. If the second argument
1243 * is not NULL then error prints an error message using printf style
1244 * formatting. It then raises the error exception.
1246 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1248 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1252 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1254 TRACE(("\") pid=%d\n", getpid()));
1256 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1261 flush_stdout_stderr();
1262 raise_exception(cond);
1266 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1268 ash_msg_and_raise_error(const char *msg, ...)
1273 ash_vmsg_and_raise(EXERROR, msg, ap);
1278 static void raise_error_syntax(const char *) NORETURN;
1280 raise_error_syntax(const char *msg)
1282 ash_msg_and_raise_error("syntax error: %s", msg);
1286 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1288 ash_msg_and_raise(int cond, const char *msg, ...)
1293 ash_vmsg_and_raise(cond, msg, ap);
1299 * error/warning routines for external builtins
1302 ash_msg(const char *fmt, ...)
1312 * Return a string describing an error. The returned string may be a
1313 * pointer to a static buffer that will be overwritten on the next call.
1314 * Action describes the operation that got the error.
1317 errmsg(int e, const char *em)
1319 if (e == ENOENT || e == ENOTDIR) {
1326 /* ============ Memory allocation */
1329 /* I consider these wrappers nearly useless:
1330 * ok, they return you to nearest exception handler, but
1331 * how much memory do you leak in the process, making
1332 * memory starvation worse?
1335 ckrealloc(void * p, size_t nbytes)
1337 p = realloc(p, nbytes);
1339 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1344 ckmalloc(size_t nbytes)
1346 return ckrealloc(NULL, nbytes);
1350 ckzalloc(size_t nbytes)
1352 return memset(ckmalloc(nbytes), 0, nbytes);
1356 ckstrdup(const char *s)
1358 char *p = strdup(s);
1360 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1364 /* Using bbox equivalents. They exit if out of memory */
1365 # define ckrealloc xrealloc
1366 # define ckmalloc xmalloc
1367 # define ckzalloc xzalloc
1368 # define ckstrdup xstrdup
1372 * It appears that grabstackstr() will barf with such alignments
1373 * because stalloc() will return a string allocated in a new stackblock.
1375 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1377 /* Most machines require the value returned from malloc to be aligned
1378 * in some way. The following macro will get this right
1379 * on many machines. */
1380 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1381 /* Minimum size of a block */
1382 MINSIZE = SHELL_ALIGN(504),
1385 struct stack_block {
1386 struct stack_block *prev;
1387 char space[MINSIZE];
1391 struct stack_block *stackp;
1397 struct globals_memstack {
1398 struct stack_block *g_stackp; // = &stackbase;
1399 char *g_stacknxt; // = stackbase.space;
1400 char *sstrend; // = stackbase.space + MINSIZE;
1401 size_t g_stacknleft; // = MINSIZE;
1402 int herefd; // = -1;
1403 struct stack_block stackbase;
1405 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1406 #define G_memstack (*ash_ptr_to_globals_memstack)
1407 #define g_stackp (G_memstack.g_stackp )
1408 #define g_stacknxt (G_memstack.g_stacknxt )
1409 #define sstrend (G_memstack.sstrend )
1410 #define g_stacknleft (G_memstack.g_stacknleft)
1411 #define herefd (G_memstack.herefd )
1412 #define stackbase (G_memstack.stackbase )
1413 #define INIT_G_memstack() do { \
1414 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1416 g_stackp = &stackbase; \
1417 g_stacknxt = stackbase.space; \
1418 g_stacknleft = MINSIZE; \
1419 sstrend = stackbase.space + MINSIZE; \
1424 #define stackblock() ((void *)g_stacknxt)
1425 #define stackblocksize() g_stacknleft
1428 * Parse trees for commands are allocated in lifo order, so we use a stack
1429 * to make this more efficient, and also to avoid all sorts of exception
1430 * handling code to handle interrupts in the middle of a parse.
1432 * The size 504 was chosen because the Ultrix malloc handles that size
1436 stalloc(size_t nbytes)
1441 aligned = SHELL_ALIGN(nbytes);
1442 if (aligned > g_stacknleft) {
1445 struct stack_block *sp;
1447 blocksize = aligned;
1448 if (blocksize < MINSIZE)
1449 blocksize = MINSIZE;
1450 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1451 if (len < blocksize)
1452 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1455 sp->prev = g_stackp;
1456 g_stacknxt = sp->space;
1457 g_stacknleft = blocksize;
1458 sstrend = g_stacknxt + blocksize;
1463 g_stacknxt += aligned;
1464 g_stacknleft -= aligned;
1469 stzalloc(size_t nbytes)
1471 return memset(stalloc(nbytes), 0, nbytes);
1478 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1479 write(STDERR_FILENO, "stunalloc\n", 10);
1483 g_stacknleft += g_stacknxt - (char *)p;
1488 * Like strdup but works with the ash stack.
1491 sstrdup(const char *p)
1493 size_t len = strlen(p) + 1;
1494 return memcpy(stalloc(len), p, len);
1498 grabstackblock(size_t len)
1500 len = SHELL_ALIGN(len);
1502 g_stacknleft -= len;
1506 pushstackmark(struct stackmark *mark, size_t len)
1508 mark->stackp = g_stackp;
1509 mark->stacknxt = g_stacknxt;
1510 mark->stacknleft = g_stacknleft;
1511 grabstackblock(len);
1515 setstackmark(struct stackmark *mark)
1517 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1521 popstackmark(struct stackmark *mark)
1523 struct stack_block *sp;
1529 while (g_stackp != mark->stackp) {
1531 g_stackp = sp->prev;
1534 g_stacknxt = mark->stacknxt;
1535 g_stacknleft = mark->stacknleft;
1536 sstrend = mark->stacknxt + mark->stacknleft;
1541 * When the parser reads in a string, it wants to stick the string on the
1542 * stack and only adjust the stack pointer when it knows how big the
1543 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1544 * of space on top of the stack and stackblocklen returns the length of
1545 * this block. Growstackblock will grow this space by at least one byte,
1546 * possibly moving it (like realloc). Grabstackblock actually allocates the
1547 * part of the block that has been used.
1550 growstackblock(void)
1554 newlen = g_stacknleft * 2;
1555 if (newlen < g_stacknleft)
1556 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1560 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1561 struct stack_block *sp;
1562 struct stack_block *prevstackp;
1567 prevstackp = sp->prev;
1568 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1569 sp = ckrealloc(sp, grosslen);
1570 sp->prev = prevstackp;
1572 g_stacknxt = sp->space;
1573 g_stacknleft = newlen;
1574 sstrend = sp->space + newlen;
1577 char *oldspace = g_stacknxt;
1578 size_t oldlen = g_stacknleft;
1579 char *p = stalloc(newlen);
1581 /* free the space we just allocated */
1582 g_stacknxt = memcpy(p, oldspace, oldlen);
1583 g_stacknleft += newlen;
1588 * The following routines are somewhat easier to use than the above.
1589 * The user declares a variable of type STACKSTR, which may be declared
1590 * to be a register. The macro STARTSTACKSTR initializes things. Then
1591 * the user uses the macro STPUTC to add characters to the string. In
1592 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1593 * grown as necessary. When the user is done, she can just leave the
1594 * string there and refer to it using stackblock(). Or she can allocate
1595 * the space for it using grabstackstr(). If it is necessary to allow
1596 * someone else to use the stack temporarily and then continue to grow
1597 * the string, the user should use grabstack to allocate the space, and
1598 * then call ungrabstr(p) to return to the previous mode of operation.
1600 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1601 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1602 * is space for at least one character.
1607 size_t len = stackblocksize();
1608 if (herefd >= 0 && len >= 1024) {
1609 full_write(herefd, stackblock(), len);
1610 return stackblock();
1613 return (char *)stackblock() + len;
1617 * Called from CHECKSTRSPACE.
1620 makestrspace(size_t newlen, char *p)
1622 size_t len = p - g_stacknxt;
1628 size = stackblocksize();
1630 if (nleft >= newlen)
1634 return (char *)stackblock() + len;
1638 stack_nputstr(const char *s, size_t n, char *p)
1640 p = makestrspace(n, p);
1641 p = (char *)memcpy(p, s, n) + n;
1646 stack_putstr(const char *s, char *p)
1648 return stack_nputstr(s, strlen(s), p);
1652 _STPUTC(int c, char *p)
1660 #define STARTSTACKSTR(p) ((p) = stackblock())
1661 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1662 #define CHECKSTRSPACE(n, p) do { \
1665 size_t m = sstrend - q; \
1667 (p) = makestrspace(l, q); \
1669 #define USTPUTC(c, p) (*(p)++ = (c))
1670 #define STACKSTRNUL(p) do { \
1671 if ((p) == sstrend) \
1672 (p) = growstackstr(); \
1675 #define STUNPUTC(p) (--(p))
1676 #define STTOPC(p) ((p)[-1])
1677 #define STADJUST(amount, p) ((p) += (amount))
1679 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1680 #define ungrabstackstr(s, p) stunalloc(s)
1681 #define stackstrend() ((void *)sstrend)
1684 /* ============ String helpers */
1687 * prefix -- see if pfx is a prefix of string.
1690 prefix(const char *string, const char *pfx)
1693 if (*pfx++ != *string++)
1696 return (char *) string;
1700 * Check for a valid number. This should be elsewhere.
1703 is_number(const char *p)
1708 } while (*++p != '\0');
1713 * Convert a string of digits to an integer, printing an error message on
1717 number(const char *s)
1720 ash_msg_and_raise_error(msg_illnum, s);
1725 * Produce a possibly single quoted string suitable as input to the shell.
1726 * The return string is allocated on the stack.
1729 single_quote(const char *s)
1739 len = strchrnul(s, '\'') - s;
1741 q = p = makestrspace(len + 3, p);
1744 q = (char *)memcpy(q, s, len) + len;
1753 do len++; while (*++s == '\'');
1755 q = p = makestrspace(len + 3, p);
1758 q = (char *)memcpy(q, s - len, len) + len;
1766 return stackblock();
1770 /* ============ nextopt */
1772 static char **argptr; /* argument list for builtin commands */
1773 static char *optionarg; /* set by nextopt (like getopt) */
1774 static char *optptr; /* used by nextopt */
1777 * XXX - should get rid of. Have all builtins use getopt(3).
1778 * The library getopt must have the BSD extension static variable
1779 * "optreset", otherwise it can't be used within the shell safely.
1781 * Standard option processing (a la getopt) for builtin routines.
1782 * The only argument that is passed to nextopt is the option string;
1783 * the other arguments are unnecessary. It returns the character,
1784 * or '\0' on end of input.
1787 nextopt(const char *optstring)
1794 if (p == NULL || *p == '\0') {
1795 /* We ate entire "-param", take next one */
1801 if (*++p == '\0') /* just "-" ? */
1804 if (LONE_DASH(p)) /* "--" ? */
1806 /* p => next "-param" */
1808 /* p => some option char in the middle of a "-param" */
1810 for (q = optstring; *q != c;) {
1812 ash_msg_and_raise_error("illegal option -%c", c);
1820 ash_msg_and_raise_error("no arg for -%c option", c);
1830 /* ============ Shell variables */
1833 * The parsefile structure pointed to by the global variable parsefile
1834 * contains information about the current file being read.
1837 int nparam; /* # of positional parameters (without $0) */
1838 #if ENABLE_ASH_GETOPTS
1839 int optind; /* next parameter to be processed by getopts */
1840 int optoff; /* used by getopts */
1842 unsigned char malloced; /* if parameter list dynamically allocated */
1843 char **p; /* parameter list */
1847 * Free the list of positional parameters.
1850 freeparam(volatile struct shparam *param)
1852 if (param->malloced) {
1854 ap = ap1 = param->p;
1861 #if ENABLE_ASH_GETOPTS
1862 static void FAST_FUNC getoptsreset(const char *value);
1866 struct var *next; /* next entry in hash list */
1867 int flags; /* flags are defined above */
1868 const char *var_text; /* name=value */
1869 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1870 /* the variable gets set/unset */
1874 struct localvar *next; /* next local variable in list */
1875 struct var *vp; /* the variable that was made local */
1876 int flags; /* saved flags */
1877 const char *text; /* saved text */
1881 #define VEXPORT 0x01 /* variable is exported */
1882 #define VREADONLY 0x02 /* variable cannot be modified */
1883 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1884 #define VTEXTFIXED 0x08 /* text is statically allocated */
1885 #define VSTACK 0x10 /* text is allocated on the stack */
1886 #define VUNSET 0x20 /* the variable is not set */
1887 #define VNOFUNC 0x40 /* don't call the callback function */
1888 #define VNOSET 0x80 /* do not set variable - just readonly test */
1889 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1890 #if ENABLE_ASH_RANDOM_SUPPORT
1891 # define VDYNAMIC 0x200 /* dynamic variable */
1897 /* Need to be before varinit_data[] */
1898 #if ENABLE_LOCALE_SUPPORT
1899 static void FAST_FUNC
1900 change_lc_all(const char *value)
1902 if (value && *value != '\0')
1903 setlocale(LC_ALL, value);
1905 static void FAST_FUNC
1906 change_lc_ctype(const char *value)
1908 if (value && *value != '\0')
1909 setlocale(LC_CTYPE, value);
1913 static void chkmail(void);
1914 static void changemail(const char *var_value) FAST_FUNC;
1916 # define chkmail() ((void)0)
1918 static void changepath(const char *) FAST_FUNC;
1919 #if ENABLE_ASH_RANDOM_SUPPORT
1920 static void change_random(const char *) FAST_FUNC;
1923 static const struct {
1925 const char *var_text;
1926 void (*var_func)(const char *) FAST_FUNC;
1927 } varinit_data[] = {
1929 * Note: VEXPORT would not work correctly here for NOFORK applets:
1930 * some environment strings may be constant.
1932 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1934 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1935 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1937 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1938 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1939 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1940 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1941 #if ENABLE_ASH_GETOPTS
1942 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1944 #if ENABLE_ASH_RANDOM_SUPPORT
1945 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1947 #if ENABLE_LOCALE_SUPPORT
1948 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1949 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1951 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1952 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1958 struct globals_var {
1959 struct shparam shellparam; /* $@ current positional parameters */
1960 struct redirtab *redirlist;
1962 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1963 struct var *vartab[VTABSIZE];
1964 struct var varinit[ARRAY_SIZE(varinit_data)];
1966 extern struct globals_var *const ash_ptr_to_globals_var;
1967 #define G_var (*ash_ptr_to_globals_var)
1968 #define shellparam (G_var.shellparam )
1969 //#define redirlist (G_var.redirlist )
1970 #define g_nullredirs (G_var.g_nullredirs )
1971 #define preverrout_fd (G_var.preverrout_fd)
1972 #define vartab (G_var.vartab )
1973 #define varinit (G_var.varinit )
1974 #define INIT_G_var() do { \
1976 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1978 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1979 varinit[i].flags = varinit_data[i].flags; \
1980 varinit[i].var_text = varinit_data[i].var_text; \
1981 varinit[i].var_func = varinit_data[i].var_func; \
1985 #define vifs varinit[0]
1987 # define vmail (&vifs)[1]
1988 # define vmpath (&vmail)[1]
1989 # define vpath (&vmpath)[1]
1991 # define vpath (&vifs)[1]
1993 #define vps1 (&vpath)[1]
1994 #define vps2 (&vps1)[1]
1995 #define vps4 (&vps2)[1]
1996 #if ENABLE_ASH_GETOPTS
1997 # define voptind (&vps4)[1]
1998 # if ENABLE_ASH_RANDOM_SUPPORT
1999 # define vrandom (&voptind)[1]
2002 # if ENABLE_ASH_RANDOM_SUPPORT
2003 # define vrandom (&vps4)[1]
2008 * The following macros access the values of the above variables.
2009 * They have to skip over the name. They return the null string
2010 * for unset variables.
2012 #define ifsval() (vifs.var_text + 4)
2013 #define ifsset() ((vifs.flags & VUNSET) == 0)
2015 # define mailval() (vmail.var_text + 5)
2016 # define mpathval() (vmpath.var_text + 9)
2017 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2019 #define pathval() (vpath.var_text + 5)
2020 #define ps1val() (vps1.var_text + 4)
2021 #define ps2val() (vps2.var_text + 4)
2022 #define ps4val() (vps4.var_text + 4)
2023 #if ENABLE_ASH_GETOPTS
2024 # define optindval() (voptind.var_text + 7)
2027 #if ENABLE_ASH_GETOPTS
2028 static void FAST_FUNC
2029 getoptsreset(const char *value)
2031 shellparam.optind = number(value);
2032 shellparam.optoff = -1;
2037 * Compares two strings up to the first = or '\0'. The first
2038 * string must be terminated by '='; the second may be terminated by
2039 * either '=' or '\0'.
2042 varcmp(const char *p, const char *q)
2046 while ((c = *p) == (d = *q)) {
2047 if (c == '\0' || c == '=')
2061 * Find the appropriate entry in the hash table from the name.
2063 static struct var **
2064 hashvar(const char *p)
2068 hashval = ((unsigned char) *p) << 4;
2069 while (*p && *p != '=')
2070 hashval += (unsigned char) *p++;
2071 return &vartab[hashval % VTABSIZE];
2075 vpcmp(const void *a, const void *b)
2077 return varcmp(*(const char **)a, *(const char **)b);
2081 * This routine initializes the builtin variables.
2091 * PS1 depends on uid
2093 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2094 vps1.var_text = "PS1=\\w \\$ ";
2097 vps1.var_text = "PS1=# ";
2100 end = vp + ARRAY_SIZE(varinit);
2102 vpp = hashvar(vp->var_text);
2105 } while (++vp < end);
2108 static struct var **
2109 findvar(struct var **vpp, const char *name)
2111 for (; *vpp; vpp = &(*vpp)->next) {
2112 if (varcmp((*vpp)->var_text, name) == 0) {
2120 * Find the value of a variable. Returns NULL if not set.
2122 static const char* FAST_FUNC
2123 lookupvar(const char *name)
2127 v = *findvar(hashvar(name), name);
2129 #if ENABLE_ASH_RANDOM_SUPPORT
2131 * Dynamic variables are implemented roughly the same way they are
2132 * in bash. Namely, they're "special" so long as they aren't unset.
2133 * As soon as they're unset, they're no longer dynamic, and dynamic
2134 * lookup will no longer happen at that point. -- PFM.
2136 if (v->flags & VDYNAMIC)
2139 if (!(v->flags & VUNSET))
2140 return var_end(v->var_text);
2146 reinit_unicode_for_ash(void)
2148 /* Unicode support should be activated even if LANG is set
2149 * _during_ shell execution, not only if it was set when
2150 * shell was started. Therefore, re-check LANG every time:
2152 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2153 || ENABLE_UNICODE_USING_LOCALE
2155 const char *s = lookupvar("LC_ALL");
2156 if (!s) s = lookupvar("LC_CTYPE");
2157 if (!s) s = lookupvar("LANG");
2163 * Search the environment of a builtin command.
2166 bltinlookup(const char *name)
2170 for (sp = cmdenviron; sp; sp = sp->next) {
2171 if (varcmp(sp->text, name) == 0)
2172 return var_end(sp->text);
2174 return lookupvar(name);
2178 * Same as setvar except that the variable and value are passed in
2179 * the first argument as name=value. Since the first argument will
2180 * be actually stored in the table, it should not be a string that
2182 * Called with interrupts off.
2185 setvareq(char *s, int flags)
2187 struct var *vp, **vpp;
2190 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2191 vp = *findvar(vpp, s);
2193 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2196 if (flags & VNOSAVE)
2199 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2205 if (vp->var_func && !(flags & VNOFUNC))
2206 vp->var_func(var_end(s));
2208 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2209 free((char*)vp->var_text);
2211 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2213 /* variable s is not found */
2216 vp = ckzalloc(sizeof(*vp));
2218 /*vp->func = NULL; - ckzalloc did it */
2221 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2228 * Set the value of a variable. The flags argument is ored with the
2229 * flags of the variable. If val is NULL, the variable is unset.
2232 setvar(const char *name, const char *val, int flags)
2240 q = endofname(name);
2241 p = strchrnul(q, '=');
2243 if (!namelen || p != q)
2244 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2249 vallen = strlen(val);
2253 nameeq = ckmalloc(namelen + vallen + 2);
2254 p = memcpy(nameeq, name, namelen) + namelen;
2257 p = memcpy(p, val, vallen) + vallen;
2260 setvareq(nameeq, flags | VNOSAVE);
2264 static void FAST_FUNC
2265 setvar0(const char *name, const char *val)
2267 setvar(name, val, 0);
2270 #if ENABLE_ASH_GETOPTS
2272 * Safe version of setvar, returns 1 on success 0 on failure.
2275 setvarsafe(const char *name, const char *val, int flags)
2278 volatile int saveint;
2279 struct jmploc *volatile savehandler = exception_handler;
2280 struct jmploc jmploc;
2283 if (setjmp(jmploc.loc))
2286 exception_handler = &jmploc;
2287 setvar(name, val, flags);
2290 exception_handler = savehandler;
2291 RESTORE_INT(saveint);
2297 * Unset the specified variable.
2300 unsetvar(const char *s)
2306 vpp = findvar(hashvar(s), s);
2310 int flags = vp->flags;
2313 if (flags & VREADONLY)
2315 #if ENABLE_ASH_RANDOM_SUPPORT
2316 vp->flags &= ~VDYNAMIC;
2320 if ((flags & VSTRFIXED) == 0) {
2322 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2323 free((char*)vp->var_text);
2329 vp->flags &= ~VEXPORT;
2339 * Process a linked list of variable assignments.
2342 listsetvar(struct strlist *list_set_var, int flags)
2344 struct strlist *lp = list_set_var;
2350 setvareq(lp->text, flags);
2357 * Generate a list of variables satisfying the given conditions.
2360 listvars(int on, int off, char ***end)
2371 for (vp = *vpp; vp; vp = vp->next) {
2372 if ((vp->flags & mask) == on) {
2373 if (ep == stackstrend())
2374 ep = growstackstr();
2375 *ep++ = (char*)vp->var_text;
2378 } while (++vpp < vartab + VTABSIZE);
2379 if (ep == stackstrend())
2380 ep = growstackstr();
2384 return grabstackstr(ep);
2388 /* ============ Path search helper
2390 * The variable path (passed by reference) should be set to the start
2391 * of the path before the first call; path_advance will update
2392 * this value as it proceeds. Successive calls to path_advance will return
2393 * the possible path expansions in sequence. If an option (indicated by
2394 * a percent sign) appears in the path entry then the global variable
2395 * pathopt will be set to point to it; otherwise pathopt will be set to
2398 static const char *pathopt; /* set by path_advance */
2401 path_advance(const char **path, const char *name)
2411 for (p = start; *p && *p != ':' && *p != '%'; p++)
2413 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2414 while (stackblocksize() < len)
2418 memcpy(q, start, p - start);
2426 while (*p && *p != ':')
2433 return stalloc(len);
2437 /* ============ Prompt */
2439 static smallint doprompt; /* if set, prompt the user */
2440 static smallint needprompt; /* true if interactive and at start of line */
2442 #if ENABLE_FEATURE_EDITING
2443 static line_input_t *line_input_state;
2444 static const char *cmdedit_prompt;
2446 putprompt(const char *s)
2448 if (ENABLE_ASH_EXPAND_PRMT) {
2449 free((char*)cmdedit_prompt);
2450 cmdedit_prompt = ckstrdup(s);
2457 putprompt(const char *s)
2463 #if ENABLE_ASH_EXPAND_PRMT
2464 /* expandstr() needs parsing machinery, so it is far away ahead... */
2465 static const char *expandstr(const char *ps);
2467 #define expandstr(s) s
2471 setprompt_if(smallint do_set, int whichprompt)
2474 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2481 switch (whichprompt) {
2491 #if ENABLE_ASH_EXPAND_PRMT
2492 pushstackmark(&smark, stackblocksize());
2494 putprompt(expandstr(prompt));
2495 #if ENABLE_ASH_EXPAND_PRMT
2496 popstackmark(&smark);
2501 /* ============ The cd and pwd commands */
2503 #define CD_PHYSICAL 1
2513 while ((i = nextopt("LP")) != '\0') {
2515 flags ^= CD_PHYSICAL;
2524 * Update curdir (the name of the current directory) in response to a
2528 updatepwd(const char *dir)
2535 cdcomppath = sstrdup(dir);
2538 if (curdir == nullstr)
2540 new = stack_putstr(curdir, new);
2542 new = makestrspace(strlen(dir) + 2, new);
2543 lim = (char *)stackblock() + 1;
2547 if (new > lim && *lim == '/')
2552 if (dir[1] == '/' && dir[2] != '/') {
2558 p = strtok(cdcomppath, "/");
2562 if (p[1] == '.' && p[2] == '\0') {
2574 new = stack_putstr(p, new);
2577 p = strtok(NULL, "/");
2582 return stackblock();
2586 * Find out what the current directory is. If we already know the current
2587 * directory, this routine returns immediately.
2592 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2593 return dir ? dir : nullstr;
2597 setpwd(const char *val, int setold)
2601 oldcur = dir = curdir;
2604 setvar("OLDPWD", oldcur, VEXPORT);
2607 if (physdir != nullstr) {
2608 if (physdir != oldcur)
2612 if (oldcur == val || !val) {
2618 dir = ckstrdup(val);
2619 if (oldcur != dir && oldcur != nullstr) {
2624 setvar("PWD", dir, VEXPORT);
2627 static void hashcd(void);
2630 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2631 * know that the current directory has changed.
2634 docd(const char *dest, int flags)
2636 const char *dir = NULL;
2639 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2642 if (!(flags & CD_PHYSICAL)) {
2643 dir = updatepwd(dest);
2657 static int FAST_FUNC
2658 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2670 dest = bltinlookup("HOME");
2671 else if (LONE_DASH(dest)) {
2672 dest = bltinlookup("OLDPWD");
2694 path = bltinlookup("CDPATH");
2703 p = path_advance(&path, dest);
2704 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2708 if (!docd(p, flags))
2713 ash_msg_and_raise_error("can't cd to %s", dest);
2716 if (flags & CD_PRINT)
2717 out1fmt("%s\n", curdir);
2721 static int FAST_FUNC
2722 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2725 const char *dir = curdir;
2729 if (physdir == nullstr)
2733 out1fmt("%s\n", dir);
2738 /* ============ ... */
2741 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2743 /* Syntax classes */
2744 #define CWORD 0 /* character is nothing special */
2745 #define CNL 1 /* newline character */
2746 #define CBACK 2 /* a backslash character */
2747 #define CSQUOTE 3 /* single quote */
2748 #define CDQUOTE 4 /* double quote */
2749 #define CENDQUOTE 5 /* a terminating quote */
2750 #define CBQUOTE 6 /* backwards single quote */
2751 #define CVAR 7 /* a dollar sign */
2752 #define CENDVAR 8 /* a '}' character */
2753 #define CLP 9 /* a left paren in arithmetic */
2754 #define CRP 10 /* a right paren in arithmetic */
2755 #define CENDFILE 11 /* end of file */
2756 #define CCTL 12 /* like CWORD, except it must be escaped */
2757 #define CSPCL 13 /* these terminate a word */
2758 #define CIGN 14 /* character should be ignored */
2761 #if ENABLE_ASH_ALIAS
2765 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2767 #if ENABLE_SH_MATH_SUPPORT
2768 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2770 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2772 static const uint16_t S_I_T[] ALIGN2 = {
2773 #if ENABLE_ASH_ALIAS
2774 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2776 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2777 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2778 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2779 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2780 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2781 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2782 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2783 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2784 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2785 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2786 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2787 #if !USE_SIT_FUNCTION
2788 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2789 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2790 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2794 /* Constants below must match table above */
2796 #if ENABLE_ASH_ALIAS
2797 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2799 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2800 CNL_CNL_CNL_CNL , /* 2 */
2801 CWORD_CCTL_CCTL_CWORD , /* 3 */
2802 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2803 CVAR_CVAR_CWORD_CVAR , /* 5 */
2804 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2805 CSPCL_CWORD_CWORD_CLP , /* 7 */
2806 CSPCL_CWORD_CWORD_CRP , /* 8 */
2807 CBACK_CBACK_CCTL_CBACK , /* 9 */
2808 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2809 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2810 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2811 CWORD_CWORD_CWORD_CWORD , /* 13 */
2812 CCTL_CCTL_CCTL_CCTL , /* 14 */
2815 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2816 * caller must ensure proper cast on it if c is *char_ptr!
2818 /* Values for syntax param */
2819 #define BASESYNTAX 0 /* not in quotes */
2820 #define DQSYNTAX 1 /* in double quotes */
2821 #define SQSYNTAX 2 /* in single quotes */
2822 #define ARISYNTAX 3 /* in arithmetic */
2823 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2825 #if USE_SIT_FUNCTION
2828 SIT(int c, int syntax)
2830 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2831 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2833 * This causes '/' to be prepended with CTLESC in dquoted string,
2834 * making "./file"* treated incorrectly because we feed
2835 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2836 * The "homegrown" glob implementation is okay with that,
2837 * but glibc one isn't. With '/' always treated as CWORD,
2840 # if ENABLE_ASH_ALIAS
2841 static const uint8_t syntax_index_table[] ALIGN1 = {
2842 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2843 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2844 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2848 static const uint8_t syntax_index_table[] ALIGN1 = {
2849 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2850 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2851 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2860 # if ENABLE_ASH_ALIAS
2866 /* Cast is purely for paranoia here,
2867 * just in case someone passed signed char to us */
2868 if ((unsigned char)c >= CTL_FIRST
2869 && (unsigned char)c <= CTL_LAST
2873 s = strchrnul(spec_symbls, c);
2876 indx = syntax_index_table[s - spec_symbls];
2878 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2881 #else /* !USE_SIT_FUNCTION */
2883 static const uint8_t syntax_index_table[] ALIGN1 = {
2884 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2885 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2895 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2896 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2918 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2919 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2920 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2922 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2924 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2925 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2926 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2927 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2928 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2930 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2931 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2932 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2933 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2946 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2947 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2978 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2979 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2980 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2983 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3011 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3012 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3013 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3014 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3016 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3017 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3018 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3019 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3020 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3021 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3022 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3023 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3142 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3143 # if ENABLE_ASH_ALIAS
3144 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3148 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3150 #endif /* !USE_SIT_FUNCTION */
3153 /* ============ Alias handling */
3155 #if ENABLE_ASH_ALIAS
3157 #define ALIASINUSE 1
3168 static struct alias **atab; // [ATABSIZE];
3169 #define INIT_G_alias() do { \
3170 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3174 static struct alias **
3175 __lookupalias(const char *name)
3177 unsigned int hashval;
3184 ch = (unsigned char)*p;
3188 ch = (unsigned char)*++p;
3190 app = &atab[hashval % ATABSIZE];
3192 for (; *app; app = &(*app)->next) {
3193 if (strcmp(name, (*app)->name) == 0) {
3201 static struct alias *
3202 lookupalias(const char *name, int check)
3204 struct alias *ap = *__lookupalias(name);
3206 if (check && ap && (ap->flag & ALIASINUSE))
3211 static struct alias *
3212 freealias(struct alias *ap)
3216 if (ap->flag & ALIASINUSE) {
3217 ap->flag |= ALIASDEAD;
3229 setalias(const char *name, const char *val)
3231 struct alias *ap, **app;
3233 app = __lookupalias(name);
3237 if (!(ap->flag & ALIASINUSE)) {
3240 ap->val = ckstrdup(val);
3241 ap->flag &= ~ALIASDEAD;
3244 ap = ckzalloc(sizeof(struct alias));
3245 ap->name = ckstrdup(name);
3246 ap->val = ckstrdup(val);
3247 /*ap->flag = 0; - ckzalloc did it */
3248 /*ap->next = NULL;*/
3255 unalias(const char *name)
3259 app = __lookupalias(name);
3263 *app = freealias(*app);
3274 struct alias *ap, **app;
3278 for (i = 0; i < ATABSIZE; i++) {
3280 for (ap = *app; ap; ap = *app) {
3281 *app = freealias(*app);
3291 printalias(const struct alias *ap)
3293 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3297 * TODO - sort output
3299 static int FAST_FUNC
3300 aliascmd(int argc UNUSED_PARAM, char **argv)
3309 for (i = 0; i < ATABSIZE; i++) {
3310 for (ap = atab[i]; ap; ap = ap->next) {
3316 while ((n = *++argv) != NULL) {
3317 v = strchr(n+1, '=');
3318 if (v == NULL) { /* n+1: funny ksh stuff */
3319 ap = *__lookupalias(n);
3321 fprintf(stderr, "%s: %s not found\n", "alias", n);
3334 static int FAST_FUNC
3335 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3339 while ((i = nextopt("a")) != '\0') {
3345 for (i = 0; *argptr; argptr++) {
3346 if (unalias(*argptr)) {
3347 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3355 #endif /* ASH_ALIAS */
3358 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3361 #define FORK_NOJOB 2
3363 /* mode flags for showjob(s) */
3364 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3365 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3366 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3367 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3370 * A job structure contains information about a job. A job is either a
3371 * single process or a set of processes contained in a pipeline. In the
3372 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3376 pid_t ps_pid; /* process id */
3377 int ps_status; /* last process status from wait() */
3378 char *ps_cmd; /* text of command being run */
3382 struct procstat ps0; /* status of process */
3383 struct procstat *ps; /* status or processes when more than one */
3385 int stopstatus; /* status of a stopped job */
3388 nprocs: 16, /* number of processes */
3390 #define JOBRUNNING 0 /* at least one proc running */
3391 #define JOBSTOPPED 1 /* all procs are stopped */
3392 #define JOBDONE 2 /* all procs are completed */
3394 sigint: 1, /* job was killed by SIGINT */
3395 jobctl: 1, /* job running under job control */
3397 waited: 1, /* true if this entry has been waited for */
3398 used: 1, /* true if this entry is in used */
3399 changed: 1; /* true if status has changed */
3400 struct job *prev_job; /* previous job */
3403 static struct job *makejob(/*union node *,*/ int);
3404 static int forkshell(struct job *, union node *, int);
3405 static int waitforjob(struct job *);
3408 enum { doing_jobctl = 0 };
3409 #define setjobctl(on) do {} while (0)
3411 static smallint doing_jobctl; //references:8
3412 static void setjobctl(int);
3419 ignoresig(int signo)
3421 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3422 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3423 /* No, need to do it */
3424 signal(signo, SIG_IGN);
3426 sigmode[signo - 1] = S_HARD_IGN;
3430 * Only one usage site - in setsignal()
3433 signal_handler(int signo)
3435 gotsig[signo - 1] = 1;
3437 if (signo == SIGINT && !trap[SIGINT]) {
3438 if (!suppress_int) {
3440 raise_interrupt(); /* does not return */
3444 pending_sig = signo;
3449 * Set the signal handler for the specified signal. The routine figures
3450 * out what it should be set to.
3453 setsignal(int signo)
3456 char cur_act, new_act;
3457 struct sigaction act;
3461 if (t != NULL) { /* trap for this sig is set */
3463 if (t[0] == '\0') /* trap is "": ignore this sig */
3467 if (rootshell && new_act == S_DFL) {
3470 if (iflag || minusc || sflag == 0)
3479 * "In all cases, bash ignores SIGQUIT. Non-builtin
3480 * commands run by bash have signal handlers
3481 * set to the values inherited by the shell
3482 * from its parent". */
3498 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3499 //whereas we have to restore it to what shell got on entry
3500 //from the parent. See comment above
3502 t = &sigmode[signo - 1];
3505 /* current setting is not yet known */
3506 if (sigaction(signo, NULL, &act)) {
3507 /* pretend it worked; maybe we should give a warning,
3508 * but other shells don't. We don't alter sigmode,
3509 * so we retry every time.
3510 * btw, in Linux it never fails. --vda */
3513 if (act.sa_handler == SIG_IGN) {
3514 cur_act = S_HARD_IGN;
3516 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3518 cur_act = S_IGN; /* don't hard ignore these */
3522 if (cur_act == S_HARD_IGN || cur_act == new_act)
3525 act.sa_handler = SIG_DFL;
3528 act.sa_handler = signal_handler;
3531 act.sa_handler = SIG_IGN;
3535 /* flags and mask matter only if !DFL and !IGN, but we do it
3536 * for all cases for more deterministic behavior:
3539 sigfillset(&act.sa_mask);
3541 sigaction_set(signo, &act);
3546 /* mode flags for set_curjob */
3547 #define CUR_DELETE 2
3548 #define CUR_RUNNING 1
3549 #define CUR_STOPPED 0
3551 /* mode flags for dowait */
3552 #define DOWAIT_NONBLOCK WNOHANG
3553 #define DOWAIT_BLOCK 0
3556 /* pgrp of shell on invocation */
3557 static int initialpgrp; //references:2
3558 static int ttyfd = -1; //5
3561 static struct job *jobtab; //5
3563 static unsigned njobs; //4
3565 static struct job *curjob; //lots
3566 /* number of presumed living untracked jobs */
3567 static int jobless; //4
3570 set_curjob(struct job *jp, unsigned mode)
3573 struct job **jpp, **curp;
3575 /* first remove from list */
3576 jpp = curp = &curjob;
3581 jpp = &jp1->prev_job;
3583 *jpp = jp1->prev_job;
3585 /* Then re-insert in correct position */
3593 /* job being deleted */
3596 /* newly created job or backgrounded job,
3597 * put after all stopped jobs.
3602 if (!jp1 || jp1->state != JOBSTOPPED)
3605 jpp = &jp1->prev_job;
3611 /* newly stopped job - becomes curjob */
3612 jp->prev_job = *jpp;
3620 jobno(const struct job *jp)
3622 return jp - jobtab + 1;
3627 * Convert a job name to a job structure.
3630 #define getjob(name, getctl) getjob(name)
3633 getjob(const char *name, int getctl)
3637 const char *err_msg = "%s: no such job";
3641 char *(*match)(const char *, const char *);
3656 if (c == '+' || c == '%') {
3658 err_msg = "No current job";
3664 err_msg = "No previous job";
3674 if (num > 0 && num <= njobs) {
3675 jp = jobtab + num - 1;
3690 if (match(jp->ps[0].ps_cmd, p)) {
3694 err_msg = "%s: ambiguous";
3704 err_msg = "job %s not created under job control";
3705 if (getctl && jp->jobctl == 0)
3710 ash_msg_and_raise_error(err_msg, name);
3714 * Mark a job structure as unused.
3717 freejob(struct job *jp)
3719 struct procstat *ps;
3723 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3724 if (ps->ps_cmd != nullstr)
3727 if (jp->ps != &jp->ps0)
3730 set_curjob(jp, CUR_DELETE);
3736 xtcsetpgrp(int fd, pid_t pgrp)
3738 if (tcsetpgrp(fd, pgrp))
3739 ash_msg_and_raise_error("can't set tty process group (%m)");
3743 * Turn job control on and off.
3745 * Note: This code assumes that the third arg to ioctl is a character
3746 * pointer, which is true on Berkeley systems but not System V. Since
3747 * System V doesn't have job control yet, this isn't a problem now.
3749 * Called with interrupts off.
3757 if (on == doing_jobctl || rootshell == 0)
3761 ofd = fd = open(_PATH_TTY, O_RDWR);
3763 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3764 * That sometimes helps to acquire controlling tty.
3765 * Obviously, a workaround for bugs when someone
3766 * failed to provide a controlling tty to bash! :) */
3772 fd = fcntl(fd, F_DUPFD, 10);
3777 /* fd is a tty at this point */
3778 close_on_exec_on(fd);
3779 while (1) { /* while we are in the background */
3780 pgrp = tcgetpgrp(fd);
3783 ash_msg("can't access tty; job control turned off");
3787 if (pgrp == getpgrp())
3798 xtcsetpgrp(fd, pgrp);
3800 /* turning job control off */
3803 /* was xtcsetpgrp, but this can make exiting ash
3804 * loop forever if pty is already deleted */
3805 tcsetpgrp(fd, pgrp);
3819 static int FAST_FUNC
3820 killcmd(int argc, char **argv)
3822 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3825 if (argv[i][0] == '%') {
3827 * "kill %N" - job kill
3828 * Converting to pgrp / pid kill
3834 jp = getjob(argv[i], 0);
3836 * In jobs started under job control, we signal
3837 * entire process group by kill -PGRP_ID.
3838 * This happens, f.e., in interactive shell.
3840 * Otherwise, we signal each child via
3841 * kill PID1 PID2 PID3.
3843 * sh -c 'sleep 1|sleep 1 & kill %1'
3844 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3845 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3847 n = jp->nprocs; /* can't be 0 (I hope) */
3850 dst = alloca(n * sizeof(int)*4);
3852 for (j = 0; j < n; j++) {
3853 struct procstat *ps = &jp->ps[j];
3854 /* Skip non-running and not-stopped members
3855 * (i.e. dead members) of the job
3857 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3860 * kill_main has matching code to expect
3861 * leading space. Needed to not confuse
3862 * negative pids with "kill -SIGNAL_NO" syntax
3864 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3868 } while (argv[++i]);
3870 return kill_main(argc, argv);
3874 showpipe(struct job *jp /*, FILE *out*/)
3876 struct procstat *ps;
3877 struct procstat *psend;
3879 psend = jp->ps + jp->nprocs;
3880 for (ps = jp->ps + 1; ps < psend; ps++)
3881 printf(" | %s", ps->ps_cmd);
3882 newline_and_flush(stdout);
3883 flush_stdout_stderr();
3888 restartjob(struct job *jp, int mode)
3890 struct procstat *ps;
3896 if (jp->state == JOBDONE)
3898 jp->state = JOBRUNNING;
3899 pgid = jp->ps[0].ps_pid;
3900 if (mode == FORK_FG)
3901 xtcsetpgrp(ttyfd, pgid);
3902 killpg(pgid, SIGCONT);
3906 if (WIFSTOPPED(ps->ps_status)) {
3912 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3917 static int FAST_FUNC
3918 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3924 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3928 jp = getjob(*argv, 1);
3929 if (mode == FORK_BG) {
3930 set_curjob(jp, CUR_RUNNING);
3931 printf("[%d] ", jobno(jp));
3933 out1str(jp->ps[0].ps_cmd);
3934 showpipe(jp /*, stdout*/);
3935 retval = restartjob(jp, mode);
3936 } while (*argv && *++argv);
3942 sprint_status48(char *s, int status, int sigonly)
3948 if (!WIFEXITED(status)) {
3949 if (JOBS && WIFSTOPPED(status))
3950 st = WSTOPSIG(status);
3952 st = WTERMSIG(status);
3954 if (st == SIGINT || st == SIGPIPE)
3956 if (JOBS && WIFSTOPPED(status))
3960 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3961 col = fmtstr(s, 32, strsignal(st));
3962 if (WCOREDUMP(status)) {
3963 strcpy(s + col, " (core dumped)");
3964 col += sizeof(" (core dumped)")-1;
3966 } else if (!sigonly) {
3967 st = WEXITSTATUS(status);
3968 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3975 dowait(int wait_flags, struct job *job)
3980 struct job *thisjob;
3982 TRACE(("dowait(0x%x) called\n", wait_flags));
3984 /* Do a wait system call. If job control is compiled in, we accept
3985 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3986 * NB: _not_ safe_waitpid, we need to detect EINTR */
3988 wait_flags |= WUNTRACED;
3989 pid = waitpid(-1, &status, wait_flags);
3990 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3991 pid, status, errno, strerror(errno)));
3997 for (jp = curjob; jp; jp = jp->prev_job) {
3999 struct procstat *ps;
4000 struct procstat *psend;
4001 if (jp->state == JOBDONE)
4005 psend = ps + jp->nprocs;
4007 if (ps->ps_pid == pid) {
4008 TRACE(("Job %d: changing status of proc %d "
4009 "from 0x%x to 0x%x\n",
4010 jobno(jp), pid, ps->ps_status, status));
4011 ps->ps_status = status;
4014 if (ps->ps_status == -1)
4015 jobstate = JOBRUNNING;
4017 if (jobstate == JOBRUNNING)
4019 if (WIFSTOPPED(ps->ps_status)) {
4020 jp->stopstatus = ps->ps_status;
4021 jobstate = JOBSTOPPED;
4024 } while (++ps < psend);
4028 /* Found the job where one of its processes changed its state.
4029 * Is there at least one live and running process in this job? */
4030 if (jobstate != JOBRUNNING) {
4031 /* No. All live processes in the job are stopped
4032 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4034 thisjob->changed = 1;
4035 if (thisjob->state != jobstate) {
4036 TRACE(("Job %d: changing state from %d to %d\n",
4037 jobno(thisjob), thisjob->state, jobstate));
4038 thisjob->state = jobstate;
4040 if (jobstate == JOBSTOPPED)
4041 set_curjob(thisjob, CUR_STOPPED);
4047 /* The process wasn't found in job list */
4048 if (JOBS && !WIFSTOPPED(status))
4053 if (thisjob && thisjob == job) {
4057 len = sprint_status48(s, status, 1);
4068 blocking_wait_with_raise_on_sig(void)
4070 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
4071 if (pid <= 0 && pending_sig)
4072 raise_exception(EXSIG);
4078 showjob(struct job *jp, int mode)
4080 struct procstat *ps;
4081 struct procstat *psend;
4084 char s[16 + 16 + 48];
4085 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4089 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4090 /* just output process (group) id of pipeline */
4091 fprintf(out, "%d\n", ps->ps_pid);
4095 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4100 else if (curjob && jp == curjob->prev_job)
4103 if (mode & SHOW_PIDS)
4104 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4106 psend = ps + jp->nprocs;
4108 if (jp->state == JOBRUNNING) {
4109 strcpy(s + col, "Running");
4110 col += sizeof("Running") - 1;
4112 int status = psend[-1].ps_status;
4113 if (jp->state == JOBSTOPPED)
4114 status = jp->stopstatus;
4115 col += sprint_status48(s + col, status, 0);
4117 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4119 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4120 * or prints several "PID | <cmdN>" lines,
4121 * depending on SHOW_PIDS bit.
4122 * We do not print status of individual processes
4123 * between PID and <cmdN>. bash does it, but not very well:
4124 * first line shows overall job status, not process status,
4125 * making it impossible to know 1st process status.
4129 /* for each process */
4132 if (mode & SHOW_PIDS)
4133 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4135 fprintf(out, "%s%*c%s%s",
4137 33 - col >= 0 ? 33 - col : 0, ' ',
4138 ps == jp->ps ? "" : "| ",
4141 } while (++ps != psend);
4142 newline_and_flush(out);
4146 if (jp->state == JOBDONE) {
4147 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4153 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4154 * statuses have changed since the last call to showjobs.
4161 TRACE(("showjobs(0x%x) called\n", mode));
4163 /* Handle all finished jobs */
4164 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4167 for (jp = curjob; jp; jp = jp->prev_job) {
4168 if (!(mode & SHOW_CHANGED) || jp->changed) {
4174 static int FAST_FUNC
4175 jobscmd(int argc UNUSED_PARAM, char **argv)
4180 while ((m = nextopt("lp")) != '\0') {
4184 mode |= SHOW_ONLY_PGID;
4190 showjob(getjob(*argv, 0), mode);
4200 /* Called only on finished or stopped jobs (no members are running) */
4202 getstatus(struct job *job)
4206 struct procstat *ps;
4208 /* Fetch last member's status */
4209 ps = job->ps + job->nprocs - 1;
4210 status = ps->ps_status;
4212 /* "set -o pipefail" mode: use last _nonzero_ status */
4213 while (status == 0 && --ps >= job->ps)
4214 status = ps->ps_status;
4217 retval = WEXITSTATUS(status);
4218 if (!WIFEXITED(status)) {
4220 retval = WSTOPSIG(status);
4221 if (!WIFSTOPPED(status))
4224 /* XXX: limits number of signals */
4225 retval = WTERMSIG(status);
4227 if (retval == SIGINT)
4233 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4234 jobno(job), job->nprocs, status, retval));
4238 static int FAST_FUNC
4239 waitcmd(int argc UNUSED_PARAM, char **argv)
4246 raise_exception(EXSIG);
4253 /* wait for all jobs */
4257 if (!jp) /* no running procs */
4259 if (jp->state == JOBRUNNING)
4264 blocking_wait_with_raise_on_sig();
4266 * "When bash is waiting for an asynchronous command via
4267 * the wait builtin, the reception of a signal for which a trap
4268 * has been set will cause the wait builtin to return immediately
4269 * with an exit status greater than 128, immediately after which
4270 * the trap is executed."
4272 * blocking_wait_with_raise_on_sig raises signal handlers
4273 * if it gets no pid (pid < 0). However,
4274 * if child sends us a signal *and immediately exits*,
4275 * blocking_wait_with_raise_on_sig gets pid > 0
4276 * and does not handle pending_sig. Check this case: */
4278 raise_exception(EXSIG);
4284 if (**argv != '%') {
4285 pid_t pid = number(*argv);
4290 if (job->ps[job->nprocs - 1].ps_pid == pid)
4292 job = job->prev_job;
4295 job = getjob(*argv, 0);
4297 /* loop until process terminated or stopped */
4298 while (job->state == JOBRUNNING)
4299 blocking_wait_with_raise_on_sig();
4301 retval = getstatus(job);
4314 struct job *jp, *jq;
4316 len = njobs * sizeof(*jp);
4318 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4320 offset = (char *)jp - (char *)jq;
4322 /* Relocate pointers */
4325 jq = (struct job *)((char *)jq + l);
4329 #define joff(p) ((struct job *)((char *)(p) + l))
4330 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4331 if (joff(jp)->ps == &jq->ps0)
4332 jmove(joff(jp)->ps);
4333 if (joff(jp)->prev_job)
4334 jmove(joff(jp)->prev_job);
4344 jp = (struct job *)((char *)jp + len);
4348 } while (--jq >= jp);
4353 * Return a new job structure.
4354 * Called with interrupts off.
4357 makejob(/*union node *node,*/ int nprocs)
4362 for (i = njobs, jp = jobtab; ; jp++) {
4369 if (jp->state != JOBDONE || !jp->waited)
4378 memset(jp, 0, sizeof(*jp));
4380 /* jp->jobctl is a bitfield.
4381 * "jp->jobctl |= jobctl" likely to give awful code */
4385 jp->prev_job = curjob;
4390 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4392 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4399 * Return a string identifying a command (to be printed by the
4402 static char *cmdnextc;
4405 cmdputs(const char *s)
4407 static const char vstype[VSTYPE + 1][3] = {
4408 "", "}", "-", "+", "?", "=",
4409 "%", "%%", "#", "##"
4410 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4413 const char *p, *str;
4417 unsigned char subtype = 0;
4421 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4423 while ((c = *p++) != '\0') {
4431 if ((subtype & VSTYPE) == VSLENGTH)
4437 str = "\"}" + !(quoted & 1);
4444 #if ENABLE_SH_MATH_SUPPORT
4459 if ((subtype & VSTYPE) != VSNORMAL)
4461 str = vstype[subtype & VSTYPE];
4462 if (subtype & VSNUL)
4471 /* These can only happen inside quotes */
4484 while ((c = *str++) != '\0') {
4487 } /* while *p++ not NUL */
4490 USTPUTC('"', nextc);
4496 /* cmdtxt() and cmdlist() call each other */
4497 static void cmdtxt(union node *n);
4500 cmdlist(union node *np, int sep)
4502 for (; np; np = np->narg.next) {
4506 if (sep && np->narg.next)
4512 cmdtxt(union node *n)
4515 struct nodelist *lp;
4526 lp = n->npipe.cmdlist;
4544 cmdtxt(n->nbinary.ch1);
4560 cmdtxt(n->nif.test);
4562 if (n->nif.elsepart) {
4563 cmdtxt(n->nif.ifpart);
4565 n = n->nif.elsepart;
4583 cmdtxt(n->nbinary.ch1);
4593 cmdputs(n->nfor.var);
4595 cmdlist(n->nfor.args, 1);
4600 cmdputs(n->narg.text);
4604 cmdlist(n->ncmd.args, 1);
4605 cmdlist(n->ncmd.redirect, 0);
4618 cmdputs(n->ncase.expr->narg.text);
4620 for (np = n->ncase.cases; np; np = np->nclist.next) {
4621 cmdtxt(np->nclist.pattern);
4623 cmdtxt(np->nclist.body);
4637 #if ENABLE_ASH_BASH_COMPAT
4652 cmdputs(utoa(n->nfile.fd));
4654 if (n->type == NTOFD || n->type == NFROMFD) {
4655 cmdputs(utoa(n->ndup.dupfd));
4664 commandtext(union node *n)
4668 STARTSTACKSTR(cmdnextc);
4670 name = stackblock();
4671 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4672 return ckstrdup(name);
4677 * Fork off a subshell. If we are doing job control, give the subshell its
4678 * own process group. Jp is a job structure that the job is to be added to.
4679 * N is the command that will be evaluated by the child. Both jp and n may
4680 * be NULL. The mode parameter can be one of the following:
4681 * FORK_FG - Fork off a foreground process.
4682 * FORK_BG - Fork off a background process.
4683 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4684 * process group even if job control is on.
4686 * When job control is turned off, background processes have their standard
4687 * input redirected to /dev/null (except for the second and later processes
4690 * Called with interrupts off.
4693 * Clear traps on a fork.
4700 for (tp = trap; tp < &trap[NSIG]; tp++) {
4701 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4703 if (trap_ptr == trap)
4705 /* else: it "belongs" to trap_ptr vector, don't free */
4707 if ((tp - trap) != 0)
4708 setsignal(tp - trap);
4715 /* Lives far away from here, needed for forkchild */
4716 static void closescript(void);
4718 /* Called after fork(), in child */
4719 static NOINLINE void
4720 forkchild(struct job *jp, union node *n, int mode)
4724 TRACE(("Child shell %d\n", getpid()));
4728 /* man bash: "Non-builtin commands run by bash have signal handlers
4729 * set to the values inherited by the shell from its parent".
4730 * Do we do it correctly? */
4734 if (mode == FORK_NOJOB /* is it `xxx` ? */
4735 && n && n->type == NCMD /* is it single cmd? */
4736 /* && n->ncmd.args->type == NARG - always true? */
4737 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4738 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4739 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4741 TRACE(("Trap hack\n"));
4742 /* Awful hack for `trap` or $(trap).
4744 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4745 * contains an example where "trap" is executed in a subshell:
4747 * save_traps=$(trap)
4749 * eval "$save_traps"
4751 * Standard does not say that "trap" in subshell shall print
4752 * parent shell's traps. It only says that its output
4753 * must have suitable form, but then, in the above example
4754 * (which is not supposed to be normative), it implies that.
4756 * bash (and probably other shell) does implement it
4757 * (traps are reset to defaults, but "trap" still shows them),
4758 * but as a result, "trap" logic is hopelessly messed up:
4761 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4762 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4763 * # true | trap <--- trap is in subshell - no output (ditto)
4764 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4765 * trap -- 'echo Ho' SIGWINCH
4766 * # echo `(trap)` <--- in subshell in subshell - output
4767 * trap -- 'echo Ho' SIGWINCH
4768 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4769 * trap -- 'echo Ho' SIGWINCH
4771 * The rules when to forget and when to not forget traps
4772 * get really complex and nonsensical.
4774 * Our solution: ONLY bare $(trap) or `trap` is special.
4776 /* Save trap handler strings for trap builtin to print */
4777 trap_ptr = xmemdup(trap, sizeof(trap));
4778 /* Fall through into clearing traps */
4782 /* do job control only in root shell */
4784 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4787 if (jp->nprocs == 0)
4790 pgrp = jp->ps[0].ps_pid;
4791 /* this can fail because we are doing it in the parent also */
4793 if (mode == FORK_FG)
4794 xtcsetpgrp(ttyfd, pgrp);
4799 if (mode == FORK_BG) {
4800 /* man bash: "When job control is not in effect,
4801 * asynchronous commands ignore SIGINT and SIGQUIT" */
4804 if (jp->nprocs == 0) {
4806 if (open(bb_dev_null, O_RDONLY) != 0)
4807 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4811 if (iflag) { /* why if iflag only? */
4816 * "In all cases, bash ignores SIGQUIT. Non-builtin
4817 * commands run by bash have signal handlers
4818 * set to the values inherited by the shell
4820 * Take care of the second rule: */
4824 if (n && n->type == NCMD
4825 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4827 TRACE(("Job hack\n"));
4828 /* "jobs": we do not want to clear job list for it,
4829 * instead we remove only _its_ own_ job from job list.
4830 * This makes "jobs .... | cat" more useful.
4836 for (jp = curjob; jp; jp = jp->prev_job)
4841 /* Called after fork(), in parent */
4843 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4846 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4848 TRACE(("In parent shell: child = %d\n", pid));
4850 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4856 if (mode != FORK_NOJOB && jp->jobctl) {
4859 if (jp->nprocs == 0)
4862 pgrp = jp->ps[0].ps_pid;
4863 /* This can fail because we are doing it in the child also */
4867 if (mode == FORK_BG) {
4868 backgndpid = pid; /* set $! */
4869 set_curjob(jp, CUR_RUNNING);
4872 struct procstat *ps = &jp->ps[jp->nprocs++];
4875 ps->ps_cmd = nullstr;
4877 if (doing_jobctl && n)
4878 ps->ps_cmd = commandtext(n);
4884 forkshell(struct job *jp, union node *n, int mode)
4888 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4891 TRACE(("Fork failed, errno=%d", errno));
4894 ash_msg_and_raise_error("can't fork");
4897 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4898 forkchild(jp, n, mode);
4900 forkparent(jp, n, mode, pid);
4906 * Wait for job to finish.
4908 * Under job control we have the problem that while a child process
4909 * is running interrupts generated by the user are sent to the child
4910 * but not to the shell. This means that an infinite loop started by
4911 * an interactive user may be hard to kill. With job control turned off,
4912 * an interactive user may place an interactive program inside a loop.
4913 * If the interactive program catches interrupts, the user doesn't want
4914 * these interrupts to also abort the loop. The approach we take here
4915 * is to have the shell ignore interrupt signals while waiting for a
4916 * foreground process to terminate, and then send itself an interrupt
4917 * signal if the child process was terminated by an interrupt signal.
4918 * Unfortunately, some programs want to do a bit of cleanup and then
4919 * exit on interrupt; unless these processes terminate themselves by
4920 * sending a signal to themselves (instead of calling exit) they will
4921 * confuse this approach.
4923 * Called with interrupts off.
4926 waitforjob(struct job *jp)
4930 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4933 while (jp->state == JOBRUNNING) {
4934 /* In non-interactive shells, we _can_ get
4935 * a keyboard signal here and be EINTRed,
4936 * but we just loop back, waiting for command to complete.
4939 * "If bash is waiting for a command to complete and receives
4940 * a signal for which a trap has been set, the trap
4941 * will not be executed until the command completes."
4943 * Reality is that even if trap is not set, bash
4944 * will not act on the signal until command completes.
4945 * Try this. sleep5intoff.c:
4946 * #include <signal.h>
4947 * #include <unistd.h>
4950 * sigemptyset(&set);
4951 * sigaddset(&set, SIGINT);
4952 * sigaddset(&set, SIGQUIT);
4953 * sigprocmask(SIG_BLOCK, &set, NULL);
4957 * $ bash -c './sleep5intoff; echo hi'
4958 * ^C^C^C^C <--- pressing ^C once a second
4960 * $ bash -c './sleep5intoff; echo hi'
4961 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4964 dowait(DOWAIT_BLOCK, jp);
4971 xtcsetpgrp(ttyfd, rootpid);
4973 * This is truly gross.
4974 * If we're doing job control, then we did a TIOCSPGRP which
4975 * caused us (the shell) to no longer be in the controlling
4976 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4977 * intuit from the subprocess exit status whether a SIGINT
4978 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4980 if (jp->sigint) /* TODO: do the same with all signals */
4981 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4983 if (jp->state == JOBDONE)
4990 * return 1 if there are stopped jobs, otherwise 0
5002 if (jp && jp->state == JOBSTOPPED) {
5003 out2str("You have stopped jobs.\n");
5012 /* ============ redir.c
5014 * Code for dealing with input/output redirection.
5019 #define EMPTY -2 /* marks an unused slot in redirtab */
5020 #define CLOSED -3 /* marks a slot of previously-closed fd */
5023 * Open a file in noclobber mode.
5024 * The code was copied from bash.
5027 noclobberopen(const char *fname)
5030 struct stat finfo, finfo2;
5033 * If the file exists and is a regular file, return an error
5036 r = stat(fname, &finfo);
5037 if (r == 0 && S_ISREG(finfo.st_mode)) {
5043 * If the file was not present (r != 0), make sure we open it
5044 * exclusively so that if it is created before we open it, our open
5045 * will fail. Make sure that we do not truncate an existing file.
5046 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5047 * file was not a regular file, we leave O_EXCL off.
5050 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5051 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5053 /* If the open failed, return the file descriptor right away. */
5058 * OK, the open succeeded, but the file may have been changed from a
5059 * non-regular file to a regular file between the stat and the open.
5060 * We are assuming that the O_EXCL open handles the case where FILENAME
5061 * did not exist and is symlinked to an existing file between the stat
5066 * If we can open it and fstat the file descriptor, and neither check
5067 * revealed that it was a regular file, and the file has not been
5068 * replaced, return the file descriptor.
5070 if (fstat(fd, &finfo2) == 0
5071 && !S_ISREG(finfo2.st_mode)
5072 && finfo.st_dev == finfo2.st_dev
5073 && finfo.st_ino == finfo2.st_ino
5078 /* The file has been replaced. badness. */
5085 * Handle here documents. Normally we fork off a process to write the
5086 * data to a pipe. If the document is short, we can stuff the data in
5087 * the pipe without forking.
5089 /* openhere needs this forward reference */
5090 static void expandhere(union node *arg, int fd);
5092 openhere(union node *redir)
5098 ash_msg_and_raise_error("pipe call failed");
5099 if (redir->type == NHERE) {
5100 len = strlen(redir->nhere.doc->narg.text);
5101 if (len <= PIPE_BUF) {
5102 full_write(pip[1], redir->nhere.doc->narg.text, len);
5106 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5109 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5110 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5111 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5112 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5113 signal(SIGPIPE, SIG_DFL);
5114 if (redir->type == NHERE)
5115 full_write(pip[1], redir->nhere.doc->narg.text, len);
5117 expandhere(redir->nhere.doc, pip[1]);
5118 _exit(EXIT_SUCCESS);
5126 openredirect(union node *redir)
5131 switch (redir->nfile.type) {
5132 /* Can't happen, our single caller does this itself */
5138 return openhere(redir);
5141 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5142 * allocated space. Do it only when we know it is safe.
5144 fname = redir->nfile.expfname;
5146 switch (redir->nfile.type) {
5152 f = open(fname, O_RDONLY);
5157 f = open(fname, O_RDWR|O_CREAT, 0666);
5162 #if ENABLE_ASH_BASH_COMPAT
5165 /* Take care of noclobber mode. */
5167 f = noclobberopen(fname);
5174 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5179 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5187 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5189 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5193 * Copy a file descriptor to be >= to. Throws exception on error.
5195 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5196 * old code was doing close(to) prior to copyfd() to achieve the same */
5198 COPYFD_EXACT = (int)~(INT_MAX),
5199 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5202 copyfd(int from, int to)
5206 if (to & COPYFD_EXACT) {
5207 to &= ~COPYFD_EXACT;
5209 newfd = dup2(from, to);
5211 newfd = fcntl(from, F_DUPFD, to);
5214 /* Happens when source fd is not open: try "echo >&99" */
5215 ash_msg_and_raise_error("%d: %m", from);
5220 /* Struct def and variable are moved down to the first usage site */
5225 struct redirtab *next;
5228 struct two_fd_t two_fd[];
5230 #define redirlist (G_var.redirlist)
5233 need_to_remember(struct redirtab *rp, int fd)
5237 if (!rp) /* remembering was not requested */
5240 for (i = 0; i < rp->pair_count; i++) {
5241 if (rp->two_fd[i].orig == fd) {
5242 /* already remembered */
5249 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5251 is_hidden_fd(struct redirtab *rp, int fd)
5254 struct parsefile *pf;
5258 /* Check open scripts' fds */
5261 /* We skip pf_fd == 0 case because of the following case:
5262 * $ ash # running ash interactively
5264 * and in script.sh: "exec 9>&0".
5265 * Even though top-level pf_fd _is_ 0,
5266 * it's still ok to use it: "read" builtin uses it,
5267 * why should we cripple "exec" builtin?
5269 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5277 /* Check saved fds of redirects */
5278 fd |= COPYFD_RESTORE;
5279 for (i = 0; i < rp->pair_count; i++) {
5280 if (rp->two_fd[i].copy == fd) {
5288 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5289 * old file descriptors are stashed away so that the redirection can be
5290 * undone by calling popredir.
5292 /* flags passed to redirect */
5293 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5294 #define REDIR_SAVEFD2 03 /* set preverrout */
5296 redirect(union node *redir, int flags)
5298 struct redirtab *sv;
5303 int copied_fd2 = -1;
5313 if (flags & REDIR_PUSH) {
5314 union node *tmp = redir;
5317 #if ENABLE_ASH_BASH_COMPAT
5318 if (tmp->nfile.type == NTO2)
5321 tmp = tmp->nfile.next;
5323 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5324 sv->next = redirlist;
5325 sv->pair_count = sv_pos;
5327 sv->nullredirs = g_nullredirs - 1;
5329 while (sv_pos > 0) {
5331 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5337 fd = redir->nfile.fd;
5338 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5339 right_fd = redir->ndup.dupfd;
5340 //bb_error_msg("doing %d > %d", fd, right_fd);
5341 /* redirect from/to same file descriptor? */
5344 /* "echo >&10" and 10 is a fd opened to a sh script? */
5345 if (is_hidden_fd(sv, right_fd)) {
5346 errno = EBADF; /* as if it is closed */
5347 ash_msg_and_raise_error("%d: %m", right_fd);
5351 newfd = openredirect(redir); /* always >= 0 */
5353 /* Descriptor wasn't open before redirect.
5354 * Mark it for close in the future */
5355 if (need_to_remember(sv, fd)) {
5356 goto remember_to_close;
5361 #if ENABLE_ASH_BASH_COMPAT
5364 if (need_to_remember(sv, fd)) {
5365 /* Copy old descriptor */
5366 /* Careful to not accidentally "save"
5367 * to the same fd as right side fd in N>&M */
5368 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5369 i = fcntl(fd, F_DUPFD, minfd);
5370 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5371 * are closed in popredir() in the child, preventing them from leaking
5372 * into child. (popredir() also cleans up the mess in case of failures)
5377 /* Strange error (e.g. "too many files" EMFILE?) */
5381 ash_msg_and_raise_error("%d: %m", fd);
5384 /* EBADF: it is not open - good, remember to close it */
5387 } else { /* fd is open, save its copy */
5388 /* "exec fd>&-" should not close fds
5389 * which point to script file(s).
5390 * Force them to be restored afterwards */
5391 if (is_hidden_fd(sv, fd))
5392 i |= COPYFD_RESTORE;
5396 sv->two_fd[sv_pos].orig = fd;
5397 sv->two_fd[sv_pos].copy = i;
5401 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5402 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5403 /* Don't want to trigger debugging */
5407 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5409 } else if (fd != newfd) { /* move newfd to fd */
5410 copyfd(newfd, fd | COPYFD_EXACT);
5411 #if ENABLE_ASH_BASH_COMPAT
5412 if (!(redir->nfile.type == NTO2 && fd == 2))
5416 #if ENABLE_ASH_BASH_COMPAT
5417 if (redir->nfile.type == NTO2 && fd == 1) {
5418 /* We already redirected it to fd 1, now copy it to 2 */
5424 } while ((redir = redir->nfile.next) != NULL);
5427 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5428 preverrout_fd = copied_fd2;
5432 * Undo the effects of the last redirection.
5435 popredir(int drop, int restore)
5437 struct redirtab *rp;
5440 if (--g_nullredirs >= 0 || redirlist == NULL)
5444 for (i = 0; i < rp->pair_count; i++) {
5445 int fd = rp->two_fd[i].orig;
5446 int copy = rp->two_fd[i].copy;
5447 if (copy == CLOSED) {
5452 if (copy != EMPTY) {
5453 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5454 copy &= ~COPYFD_RESTORE;
5456 copyfd(copy, fd | COPYFD_EXACT);
5458 close(copy & ~COPYFD_RESTORE);
5461 redirlist = rp->next;
5462 g_nullredirs = rp->nullredirs;
5468 * Undo all redirections. Called on error or interrupt.
5472 * Discard all saved file descriptors.
5475 clearredir(int drop)
5481 popredir(drop, /*restore:*/ 0);
5486 redirectsafe(union node *redir, int flags)
5489 volatile int saveint;
5490 struct jmploc *volatile savehandler = exception_handler;
5491 struct jmploc jmploc;
5494 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5495 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5497 exception_handler = &jmploc;
5498 redirect(redir, flags);
5500 exception_handler = savehandler;
5501 if (err && exception_type != EXERROR)
5502 longjmp(exception_handler->loc, 1);
5503 RESTORE_INT(saveint);
5508 /* ============ Routines to expand arguments to commands
5510 * We have to deal with backquotes, shell variables, and file metacharacters.
5513 #if ENABLE_SH_MATH_SUPPORT
5515 ash_arith(const char *s)
5517 arith_state_t math_state;
5520 math_state.lookupvar = lookupvar;
5521 math_state.setvar = setvar0;
5522 //math_state.endofname = endofname;
5525 result = arith(&math_state, s);
5526 if (math_state.errmsg)
5527 ash_msg_and_raise_error(math_state.errmsg);
5537 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5538 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5539 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5540 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5541 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5542 * POSIX says for this case:
5543 * Pathname expansion shall not be performed on the word by a
5544 * non-interactive shell; an interactive shell may perform it, but shall
5545 * do so only when the expansion would result in one word.
5546 * Currently, our code complies to the above rule by never globbing
5547 * redirection filenames.
5548 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5549 * (this means that on a typical Linux distro, bash almost always
5550 * performs globbing, and thus diverges from what we do).
5552 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5553 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5554 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5555 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5556 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5560 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5561 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5562 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5563 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5564 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5566 /* Add CTLESC when necessary. */
5567 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5568 /* Do not skip NUL characters. */
5569 #define QUOTES_KEEPNUL EXP_TILDE
5572 * Structure specifying which parts of the string should be searched
5573 * for IFS characters.
5576 struct ifsregion *next; /* next region in list */
5577 int begoff; /* offset of start of region */
5578 int endoff; /* offset of end of region */
5579 int nulonly; /* search for nul bytes only */
5583 struct strlist *list;
5584 struct strlist **lastp;
5587 /* output of current string */
5588 static char *expdest;
5589 /* list of back quote expressions */
5590 static struct nodelist *argbackq;
5591 /* first struct in list of ifs regions */
5592 static struct ifsregion ifsfirst;
5593 /* last struct in list */
5594 static struct ifsregion *ifslastp;
5595 /* holds expanded arg list */
5596 static struct arglist exparg;
5601 #if !ENABLE_SH_MATH_SUPPORT
5602 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5603 typedef long arith_t;
5604 # define ARITH_FMT "%ld"
5611 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5612 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5613 STADJUST(len, expdest);
5618 esclen(const char *start, const char *p)
5622 while (p > start && (unsigned char)*--p == CTLESC) {
5629 * Remove any CTLESC characters from a string.
5632 rmescapes(char *str, int flag)
5634 static const char qchars[] ALIGN1 = {
5635 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5639 unsigned protect_against_glob;
5641 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5643 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5649 if (flag & RMESCAPE_ALLOC) {
5650 size_t len = p - str;
5651 size_t fulllen = len + strlen(p) + 1;
5653 if (flag & RMESCAPE_GROW) {
5654 int strloc = str - (char *)stackblock();
5655 r = makestrspace(fulllen, expdest);
5656 /* p and str may be invalidated by makestrspace */
5657 str = (char *)stackblock() + strloc;
5659 } else if (flag & RMESCAPE_HEAP) {
5660 r = ckmalloc(fulllen);
5662 r = stalloc(fulllen);
5666 q = (char *)memcpy(q, str, len) + len;
5671 globbing = flag & RMESCAPE_GLOB;
5672 protect_against_glob = globbing;
5674 if ((unsigned char)*p == CTLQUOTEMARK) {
5675 // Note: both inquotes and protect_against_glob only affect whether
5676 inquotes = ~inquotes;
5678 protect_against_glob = globbing;
5681 if ((unsigned char)*p == CTLESC) {
5685 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5687 if (protect_against_glob) {
5690 } else if (*p == '\\' && !inquotes) {
5691 /* naked back slash */
5692 protect_against_glob = 0;
5695 #if ENABLE_ASH_BASH_COMPAT
5696 else if (*p == '/' && slash) {
5697 /* stop handling globbing and mark location of slash */
5698 globbing = slash = 0;
5702 protect_against_glob = globbing;
5707 if (flag & RMESCAPE_GROW) {
5709 STADJUST(q - r + 1, expdest);
5713 #define pmatch(a, b) !fnmatch((a), (b), 0)
5716 * Prepare a pattern for a expmeta (internal glob(3)) call.
5718 * Returns an stalloced string.
5721 preglob(const char *pattern, int flag)
5723 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5727 * Put a string on the stack.
5730 memtodest(const char *p, size_t len, int syntax, int quotes)
5737 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5740 unsigned char c = *p++;
5742 int n = SIT(c, syntax);
5743 if ((quotes & QUOTES_ESC)
5745 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5751 } else if (!(quotes & QUOTES_KEEPNUL))
5760 strtodest(const char *p, int syntax, int quotes)
5762 size_t len = strlen(p);
5763 memtodest(p, len, syntax, quotes);
5768 * Record the fact that we have to scan this region of the
5769 * string for IFS characters.
5772 recordregion(int start, int end, int nulonly)
5774 struct ifsregion *ifsp;
5776 if (ifslastp == NULL) {
5780 ifsp = ckzalloc(sizeof(*ifsp));
5781 /*ifsp->next = NULL; - ckzalloc did it */
5782 ifslastp->next = ifsp;
5786 ifslastp->begoff = start;
5787 ifslastp->endoff = end;
5788 ifslastp->nulonly = nulonly;
5792 removerecordregions(int endoff)
5794 if (ifslastp == NULL)
5797 if (ifsfirst.endoff > endoff) {
5798 while (ifsfirst.next) {
5799 struct ifsregion *ifsp;
5801 ifsp = ifsfirst.next->next;
5802 free(ifsfirst.next);
5803 ifsfirst.next = ifsp;
5806 if (ifsfirst.begoff > endoff) {
5809 ifslastp = &ifsfirst;
5810 ifsfirst.endoff = endoff;
5815 ifslastp = &ifsfirst;
5816 while (ifslastp->next && ifslastp->next->begoff < endoff)
5817 ifslastp = ifslastp->next;
5818 while (ifslastp->next) {
5819 struct ifsregion *ifsp;
5821 ifsp = ifslastp->next->next;
5822 free(ifslastp->next);
5823 ifslastp->next = ifsp;
5826 if (ifslastp->endoff > endoff)
5827 ifslastp->endoff = endoff;
5831 exptilde(char *startp, char *p, int flags)
5837 int quotes = flags & QUOTES_ESC;
5841 while ((c = *++p) != '\0') {
5848 if (flags & EXP_VARTILDE)
5858 if (*name == '\0') {
5859 home = lookupvar("HOME");
5861 pw = getpwnam(name);
5866 if (!home || !*home)
5869 strtodest(home, SQSYNTAX, quotes);
5877 * Execute a command inside back quotes. If it's a builtin command, we
5878 * want to save its output in a block obtained from malloc. Otherwise
5879 * we fork off a subprocess and get the output of the command via a pipe.
5880 * Should be called with interrupts off.
5882 struct backcmd { /* result of evalbackcmd */
5883 int fd; /* file descriptor to read from */
5884 int nleft; /* number of chars in buffer */
5885 char *buf; /* buffer */
5886 struct job *jp; /* job structure for command */
5889 /* These forward decls are needed to use "eval" code for backticks handling: */
5890 #define EV_EXIT 01 /* exit after evaluating tree */
5891 static int evaltree(union node *, int);
5893 static void FAST_FUNC
5894 evalbackcmd(union node *n, struct backcmd *result)
5905 saveherefd = herefd;
5913 ash_msg_and_raise_error("pipe call failed");
5914 jp = makejob(/*n,*/ 1);
5915 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5920 copyfd(pip[1], 1 | COPYFD_EXACT);
5923 /* TODO: eflag clearing makes the following not abort:
5924 * ash -c 'set -e; z=$(false;echo foo); echo $z'
5925 * which is what bash does (unless it is in POSIX mode).
5926 * dash deleted "eflag = 0" line in the commit
5927 * Date: Mon, 28 Jun 2010 17:11:58 +1000
5928 * [EVAL] Don't clear eflag in evalbackcmd
5929 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
5932 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5936 result->fd = pip[0];
5939 herefd = saveherefd;
5941 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5942 result->fd, result->buf, result->nleft, result->jp));
5946 * Expand stuff in backwards quotes.
5949 expbackq(union node *cmd, int flag)
5957 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
5958 struct stackmark smark;
5961 startloc = expdest - (char *)stackblock();
5962 pushstackmark(&smark, startloc);
5963 evalbackcmd(cmd, &in);
5964 popstackmark(&smark);
5971 memtodest(p, i, syntax, flag & QUOTES_ESC);
5975 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
5976 TRACE(("expbackq: read returns %d\n", i));
5985 back_exitstatus = waitforjob(in.jp);
5989 /* Eat all trailing newlines */
5991 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5995 if (!(flag & EXP_QUOTED))
5996 recordregion(startloc, dest - (char *)stackblock(), 0);
5997 TRACE(("evalbackq: size:%d:'%.*s'\n",
5998 (int)((dest - (char *)stackblock()) - startloc),
5999 (int)((dest - (char *)stackblock()) - startloc),
6000 stackblock() + startloc));
6003 #if ENABLE_SH_MATH_SUPPORT
6005 * Expand arithmetic expression. Backup to start of expression,
6006 * evaluate, place result in (backed up) result, adjust string position.
6018 * This routine is slightly over-complicated for
6019 * efficiency. Next we scan backwards looking for the
6020 * start of arithmetic.
6022 start = stackblock();
6029 while ((unsigned char)*p != CTLARI) {
6033 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6038 esc = esclen(start, p);
6048 removerecordregions(begoff);
6052 if (flag & QUOTES_ESC)
6053 rmescapes(p + 1, 0);
6055 len = cvtnum(ash_arith(p + 1));
6057 if (!(flag & EXP_QUOTED))
6058 recordregion(begoff, begoff + len, 0);
6062 /* argstr needs it */
6063 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6066 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6067 * characters to allow for further processing. Otherwise treat
6068 * $@ like $* since no splitting will be performed.
6070 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6071 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6072 * for correct expansion of "B=$A" word.
6075 argstr(char *p, int flags, struct strlist *var_str_list)
6077 static const char spclchars[] ALIGN1 = {
6085 #if ENABLE_SH_MATH_SUPPORT
6090 const char *reject = spclchars;
6091 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6096 if (!(flags & EXP_VARTILDE)) {
6098 } else if (flags & EXP_VARTILDE2) {
6103 if (flags & EXP_TILDE) {
6106 flags &= ~EXP_TILDE;
6110 p = exptilde(p, q, flags);
6113 startloc = expdest - (char *)stackblock();
6117 length += strcspn(p + length, reject);
6121 IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
6123 /* c == '=' || c == ':' || c == CTLENDARI */
6129 expdest = stack_nputstr(p, length, expdest);
6130 newloc = expdest - (char *)stackblock();
6131 if (breakall && !inquotes && newloc > startloc) {
6132 recordregion(startloc, newloc, 0);
6143 if (flags & EXP_VARTILDE2) {
6147 flags |= EXP_VARTILDE2;
6152 * sort of a hack - expand tildes in variable
6153 * assignments (after the first '=' and after ':'s).
6162 case CTLENDVAR: /* ??? */
6165 inquotes ^= EXP_QUOTED;
6166 /* "$@" syntax adherence hack */
6167 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6168 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6172 if (flags & QUOTES_ESC) {
6183 * Quoted parameter expansion pattern: remove quote
6184 * unless inside inner quotes or we have a literal
6187 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6188 EXP_QPAT && *p != '\\')
6193 TRACE(("argstr: evalvar('%s')\n", p));
6194 p = evalvar(p, flags | inquotes, var_str_list);
6195 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6198 expbackq(argbackq->n, flags | inquotes);
6199 argbackq = argbackq->next;
6201 #if ENABLE_SH_MATH_SUPPORT
6204 expari(flags | inquotes);
6213 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6214 char *pattern, int quotes, int zero)
6223 const char *s = loc2;
6230 match = pmatch(pattern, s);
6235 if (quotes && (unsigned char)*loc == CTLESC)
6244 scanright(char *startp, char *rmesc, char *rmescend,
6245 char *pattern, int quotes, int match_at_start)
6247 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6248 int try2optimize = match_at_start;
6254 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6255 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6256 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6258 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6259 * and on each iteration they go back two/one char until they reach the beginning.
6260 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6262 /* TODO: document in what other circumstances we are called. */
6264 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6267 const char *s = loc2;
6268 if (match_at_start) {
6272 match = pmatch(pattern, s);
6273 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6277 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6279 /* Maybe we can optimize this:
6280 * if pattern ends with unescaped *, we can avoid checking
6281 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6282 * it wont match truncated "raw_value_of_" strings too.
6284 unsigned plen = strlen(pattern);
6285 /* Does it end with "*"? */
6286 if (plen != 0 && pattern[--plen] == '*') {
6287 /* "xxxx*" is not escaped */
6288 /* "xxx\*" is escaped */
6289 /* "xx\\*" is not escaped */
6290 /* "x\\\*" is escaped */
6292 while (plen != 0 && pattern[--plen] == '\\')
6295 break; /* ends with unescaped "*" */
6303 esc = esclen(startp, loc);
6314 static void varunset(const char *, const char *, const char *, int) NORETURN;
6316 varunset(const char *end, const char *var, const char *umsg, int varflags)
6322 msg = "parameter not set";
6324 if ((unsigned char)*end == CTLENDVAR) {
6325 if (varflags & VSNUL)
6331 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6335 subevalvar(char *p, char *varname, int strloc, int subtype,
6336 int startloc, int varflags, int flag, struct strlist *var_str_list)
6338 struct nodelist *saveargbackq = argbackq;
6339 int quotes = flag & QUOTES_ESC;
6342 char *rmesc, *rmescend;
6344 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6345 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6346 int saveherefd = herefd;
6347 int amount, resetloc;
6348 IF_ASH_BASH_COMPAT(int workloc;)
6350 char *(*scan)(char*, char*, char*, char*, int, int);
6352 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6353 // p, varname, strloc, subtype, startloc, varflags, quotes);
6356 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6357 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6359 STPUTC('\0', expdest);
6360 herefd = saveherefd;
6361 argbackq = saveargbackq;
6362 startp = (char *)stackblock() + startloc;
6366 setvar0(varname, startp);
6367 amount = startp - expdest;
6368 STADJUST(amount, expdest);
6372 varunset(p, varname, startp, varflags);
6375 #if ENABLE_ASH_BASH_COMPAT
6377 //TODO: support more general format ${v:EXPR:EXPR},
6378 // where EXPR follows $(()) rules
6379 loc = str = stackblock() + strloc;
6380 /* Read POS in ${var:POS:LEN} */
6381 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6382 len = str - startp - 1;
6384 /* *loc != '\0', guaranteed by parser */
6388 /* Adjust the length by the number of escapes */
6389 for (ptr = startp; ptr < (str - 1); ptr++) {
6390 if ((unsigned char)*ptr == CTLESC) {
6398 if (*loc++ == ':') {
6402 /* Skip POS in ${var:POS:LEN} */
6404 while (*loc && *loc != ':') {
6406 * bash complains on: var=qwe; echo ${var:1a:123}
6408 ash_msg_and_raise_error(msg_illnum, str);
6412 if (*loc++ == ':') {
6417 /* ${VAR:$((-n)):l} starts n chars from the end */
6418 pos = orig_len + pos;
6420 if ((unsigned)pos >= orig_len) {
6421 /* apart from obvious ${VAR:999999:l},
6422 * covers ${VAR:$((-9999999)):l} - result is ""
6428 if (len > (orig_len - pos))
6429 len = orig_len - pos;
6431 for (str = startp; pos; str++, pos--) {
6432 if (quotes && (unsigned char)*str == CTLESC)
6435 for (loc = startp; len; len--) {
6436 if (quotes && (unsigned char)*str == CTLESC)
6441 amount = loc - expdest;
6442 STADJUST(amount, expdest);
6447 resetloc = expdest - (char *)stackblock();
6449 /* We'll comeback here if we grow the stack while handling
6450 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6451 * stack will need rebasing, and we'll need to remove our work
6454 IF_ASH_BASH_COMPAT(restart:)
6456 amount = expdest - ((char *)stackblock() + resetloc);
6457 STADJUST(-amount, expdest);
6458 startp = (char *)stackblock() + startloc;
6461 rmescend = (char *)stackblock() + strloc;
6463 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6464 if (rmesc != startp) {
6466 startp = (char *)stackblock() + startloc;
6470 str = (char *)stackblock() + strloc;
6472 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6473 * The result is a_\_z_c (not a\_\_z_c)!
6475 * The search pattern and replace string treat backslashes differently!
6476 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6477 * and string. It's only used on the first call.
6479 preglob(str, IF_ASH_BASH_COMPAT(
6480 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6481 RMESCAPE_SLASH :) 0);
6483 #if ENABLE_ASH_BASH_COMPAT
6484 workloc = expdest - (char *)stackblock();
6485 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6489 repl = strchr(str, CTLESC);
6495 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6497 /* If there's no pattern to match, return the expansion unmolested */
6506 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6507 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6509 /* No match, advance */
6510 char *restart_detect = stackblock();
6512 STPUTC(*idx, expdest);
6513 if (quotes && (unsigned char)*idx == CTLESC) {
6516 STPUTC(*idx, expdest);
6518 if (stackblock() != restart_detect)
6523 /* continue; - prone to quadratic behavior, smarter code: */
6526 if (str[0] == '*') {
6527 /* Pattern is "*foo". If "*foo" does not match "long_string",
6528 * it would never match "ong_string" etc, no point in trying.
6535 if (subtype == VSREPLACEALL) {
6537 if (quotes && (unsigned char)*idx == CTLESC)
6546 //bb_error_msg("repl:'%s'", repl);
6547 for (loc = (char*)repl; *loc; loc++) {
6548 char *restart_detect = stackblock();
6549 if (quotes && *loc == '\\') {
6550 STPUTC(CTLESC, expdest);
6553 STPUTC(*loc, expdest);
6554 if (stackblock() != restart_detect)
6559 if (subtype == VSREPLACE) {
6560 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6562 char *restart_detect = stackblock();
6563 STPUTC(*idx, expdest);
6564 if (stackblock() != restart_detect)
6573 /* We've put the replaced text into a buffer at workloc, now
6574 * move it to the right place and adjust the stack.
6576 STPUTC('\0', expdest);
6577 startp = (char *)stackblock() + startloc;
6578 memmove(startp, (char *)stackblock() + workloc, len + 1);
6579 //bb_error_msg("startp:'%s'", startp);
6580 amount = expdest - (startp + len);
6581 STADJUST(-amount, expdest);
6584 #endif /* ENABLE_ASH_BASH_COMPAT */
6586 subtype -= VSTRIMRIGHT;
6588 if (subtype < 0 || subtype > 7)
6591 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6592 zero = subtype >> 1;
6593 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6594 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6596 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6599 memmove(startp, loc, str - loc);
6600 loc = startp + (str - loc) - 1;
6603 amount = loc - expdest;
6604 STADJUST(amount, expdest);
6610 * Add the value of a specialized variable to the stack string.
6611 * name parameter (examples):
6612 * ash -c 'echo $1' name:'1='
6613 * ash -c 'echo $qwe' name:'qwe='
6614 * ash -c 'echo $$' name:'$='
6615 * ash -c 'echo ${$}' name:'$='
6616 * ash -c 'echo ${$##q}' name:'$=q'
6617 * ash -c 'echo ${#$}' name:'$='
6618 * note: examples with bad shell syntax:
6619 * ash -c 'echo ${#$1}' name:'$=1'
6620 * ash -c 'echo ${#1#}' name:'1=#'
6622 static NOINLINE ssize_t
6623 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6630 int quoted = *quotedp;
6631 int subtype = varflags & VSTYPE;
6632 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6633 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6636 sep = (flags & EXP_FULL) << CHAR_BIT;
6637 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6647 num = shellparam.nparam;
6655 goto check_1char_name;
6657 expdest = makestrspace(NOPTS, expdest);
6658 for (i = NOPTS - 1; i >= 0; i--) {
6660 USTPUTC(optletters(i), expdest);
6666 /* handles cases similar to ${#$1} */
6667 if (name[2] != '\0')
6668 raise_error_syntax("bad substitution");
6681 sep |= ifsset() ? ifsval()[0] : ' ';
6688 while ((p = *ap++) != NULL) {
6689 len += strtodest(p, syntax, quotes);
6693 memtodest(&sepc, 1, syntax, quotes);
6708 num = atoi(name); /* number(name) fails on ${N#str} etc */
6709 if (num < 0 || num > shellparam.nparam)
6711 p = num ? shellparam.p[num - 1] : arg0;
6714 /* NB: name has form "VAR=..." */
6716 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6717 * which should be considered before we check variables. */
6719 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6723 str = var_str_list->text;
6724 eq = strchr(str, '=');
6725 if (!eq) /* stop at first non-assignment */
6728 if (name_len == (unsigned)(eq - str)
6729 && strncmp(str, name, name_len) == 0
6732 /* goto value; - WRONG! */
6733 /* think "A=1 A=2 B=$A" */
6735 var_str_list = var_str_list->next;
6736 } while (var_str_list);
6740 p = lookupvar(name);
6745 len = strtodest(p, syntax, quotes);
6746 #if ENABLE_UNICODE_SUPPORT
6747 if (subtype == VSLENGTH && len > 0) {
6748 reinit_unicode_for_ash();
6749 if (unicode_status == UNICODE_ON) {
6750 STADJUST(-len, expdest);
6752 len = unicode_strlen(p);
6760 STADJUST(-len, expdest);
6765 * Expand a variable, and return a pointer to the next character in the
6769 evalvar(char *p, int flag, struct strlist *var_str_list)
6780 varflags = (unsigned char) *p++;
6781 subtype = varflags & VSTYPE;
6782 quoted = flag & EXP_QUOTED;
6784 easy = (!quoted || (*var == '@' && shellparam.nparam));
6785 startloc = expdest - (char *)stackblock();
6786 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6789 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6790 if (varflags & VSNUL)
6793 if (subtype == VSPLUS) {
6794 varlen = -1 - varlen;
6798 if (subtype == VSMINUS) {
6803 flag | EXP_TILDE | EXP_WORD,
6811 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6815 subevalvar(p, var, 0, subtype, startloc, varflags,
6816 flag & ~QUOTES_ESC, var_str_list);
6819 * Remove any recorded regions beyond
6822 removerecordregions(startloc);
6826 if (varlen < 0 && uflag)
6827 varunset(p, var, 0, 0);
6829 if (subtype == VSLENGTH) {
6830 cvtnum(varlen > 0 ? varlen : 0);
6834 if (subtype == VSNORMAL) {
6838 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6847 case VSTRIMRIGHTMAX:
6848 #if ENABLE_ASH_BASH_COMPAT
6861 * Terminate the string and start recording the pattern
6864 STPUTC('\0', expdest);
6865 patloc = expdest - (char *)stackblock();
6866 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6867 startloc, varflags, flag, var_str_list)) {
6868 int amount = expdest - (
6869 (char *)stackblock() + patloc - 1
6871 STADJUST(-amount, expdest);
6873 /* Remove any recorded regions beyond start of variable */
6874 removerecordregions(startloc);
6879 if (subtype != VSNORMAL) { /* skip to end of alternative */
6882 unsigned char c = *p++;
6885 else if (c == CTLBACKQ) {
6887 argbackq = argbackq->next;
6888 } else if (c == CTLVAR) {
6889 if ((*p++ & VSTYPE) != VSNORMAL)
6891 } else if (c == CTLENDVAR) {
6901 * Break the argument string into pieces based upon IFS and add the
6902 * strings to the argument list. The regions of the string to be
6903 * searched for IFS characters have been stored by recordregion.
6906 ifsbreakup(char *string, struct arglist *arglist)
6908 struct ifsregion *ifsp;
6913 const char *ifs, *realifs;
6918 if (ifslastp != NULL) {
6921 realifs = ifsset() ? ifsval() : defifs;
6924 p = string + ifsp->begoff;
6925 nulonly = ifsp->nulonly;
6926 ifs = nulonly ? nullstr : realifs;
6928 while (p < string + ifsp->endoff) {
6930 if ((unsigned char)*p == CTLESC)
6932 if (!strchr(ifs, *p)) {
6937 ifsspc = (strchr(defifs, *p) != NULL);
6938 /* Ignore IFS whitespace at start */
6939 if (q == start && ifsspc) {
6945 sp = stzalloc(sizeof(*sp));
6947 *arglist->lastp = sp;
6948 arglist->lastp = &sp->next;
6952 if (p >= string + ifsp->endoff) {
6956 if ((unsigned char)*p == CTLESC)
6958 if (strchr(ifs, *p) == NULL) {
6962 if (strchr(defifs, *p) == NULL) {
6977 } while (ifsp != NULL);
6986 sp = stzalloc(sizeof(*sp));
6988 *arglist->lastp = sp;
6989 arglist->lastp = &sp->next;
6995 struct ifsregion *p;
7000 struct ifsregion *ifsp;
7006 ifsfirst.next = NULL;
7011 * Add a file name to the list.
7014 addfname(const char *name)
7018 sp = stzalloc(sizeof(*sp));
7019 sp->text = sstrdup(name);
7021 exparg.lastp = &sp->next;
7024 /* If we want to use glob() from libc... */
7025 #if !ENABLE_ASH_INTERNAL_GLOB
7027 /* Add the result of glob() to the list */
7029 addglob(const glob_t *pglob)
7031 char **p = pglob->gl_pathv;
7038 expandmeta(struct strlist *str /*, int flag*/)
7040 /* TODO - EXP_REDIR */
7050 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7051 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7052 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7054 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7055 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7056 // Which means you need to unescape the string, right? Not so fast:
7057 // if there _is_ a file named "file\?" (with backslash), it is returned
7058 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7059 // You DONT KNOW by looking at the result whether you need to unescape it.
7061 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7062 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7063 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7064 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7065 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7066 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7067 i = glob(p, 0, NULL, &pglob);
7068 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7073 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7074 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7075 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7087 *exparg.lastp = str;
7088 rmescapes(str->text, 0);
7089 exparg.lastp = &str->next;
7091 default: /* GLOB_NOSPACE */
7094 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7101 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7104 * Do metacharacter (i.e. *, ?, [...]) expansion.
7107 expmeta(char *expdir, char *enddir, char *name)
7123 for (p = name; esc = 0, *p; p += esc + 1) {
7124 if (*p == '*' || *p == '?')
7126 else if (*p == '[') {
7133 if (*q == '/' || *q == '\0')
7143 if (p[esc] == '/') {
7146 start = p + esc + 1;
7150 if (metaflag == 0) { /* we've reached the end of the file name */
7151 if (enddir != expdir)
7159 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7170 } while (p < start);
7172 if (enddir == expdir) {
7174 } else if (enddir == expdir + 1 && *expdir == '/') {
7183 if (enddir != expdir)
7185 if (*endname == 0) {
7198 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7199 if (dp->d_name[0] == '.' && !matchdot)
7201 if (pmatch(start, dp->d_name)) {
7203 strcpy(enddir, dp->d_name);
7206 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7209 expmeta(expdir, p, endname);
7215 endname[-esc - 1] = esc ? '\\' : '/';
7218 static struct strlist *
7219 msort(struct strlist *list, int len)
7221 struct strlist *p, *q = NULL;
7222 struct strlist **lpp;
7230 for (n = half; --n >= 0;) {
7234 q->next = NULL; /* terminate first half of list */
7235 q = msort(list, half); /* sort first half of list */
7236 p = msort(p, len - half); /* sort second half */
7239 #if ENABLE_LOCALE_SUPPORT
7240 if (strcoll(p->text, q->text) < 0)
7242 if (strcmp(p->text, q->text) < 0)
7266 * Sort the results of file name expansion. It calculates the number of
7267 * strings to sort and then calls msort (short for merge sort) to do the
7270 static struct strlist *
7271 expsort(struct strlist *str)
7277 for (sp = str; sp; sp = sp->next)
7279 return msort(str, len);
7283 expandmeta(struct strlist *str /*, int flag*/)
7285 static const char metachars[] ALIGN1 = {
7288 /* TODO - EXP_REDIR */
7292 struct strlist **savelastp;
7298 if (!strpbrk(str->text, metachars))
7300 savelastp = exparg.lastp;
7303 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7305 int i = strlen(str->text);
7306 //BUGGY estimation of how long expanded name can be
7307 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7309 expmeta(expdir, expdir, p);
7314 if (exparg.lastp == savelastp) {
7319 *exparg.lastp = str;
7320 rmescapes(str->text, 0);
7321 exparg.lastp = &str->next;
7323 *exparg.lastp = NULL;
7324 *savelastp = sp = expsort(*savelastp);
7325 while (sp->next != NULL)
7327 exparg.lastp = &sp->next;
7332 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7335 * Perform variable substitution and command substitution on an argument,
7336 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7337 * perform splitting and file name expansion. When arglist is NULL, perform
7338 * here document expansion.
7341 expandarg(union node *arg, struct arglist *arglist, int flag)
7346 argbackq = arg->narg.backquote;
7347 STARTSTACKSTR(expdest);
7348 ifsfirst.next = NULL;
7350 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7351 argstr(arg->narg.text, flag,
7352 /* var_str_list: */ arglist ? arglist->list : NULL);
7353 p = _STPUTC('\0', expdest);
7355 if (arglist == NULL) {
7356 return; /* here document expanded */
7358 p = grabstackstr(p);
7359 TRACE(("expandarg: p:'%s'\n", p));
7360 exparg.lastp = &exparg.list;
7364 if (flag & EXP_FULL) {
7365 ifsbreakup(p, &exparg);
7366 *exparg.lastp = NULL;
7367 exparg.lastp = &exparg.list;
7368 expandmeta(exparg.list /*, flag*/);
7370 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7372 TRACE(("expandarg: rmescapes:'%s'\n", p));
7374 sp = stzalloc(sizeof(*sp));
7377 exparg.lastp = &sp->next;
7381 *exparg.lastp = NULL;
7383 *arglist->lastp = exparg.list;
7384 arglist->lastp = exparg.lastp;
7389 * Expand shell variables and backquotes inside a here document.
7392 expandhere(union node *arg, int fd)
7395 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7396 full_write(fd, stackblock(), expdest - (char *)stackblock());
7400 * Returns true if the pattern matches the string.
7403 patmatch(char *pattern, const char *string)
7405 return pmatch(preglob(pattern, 0), string);
7409 * See if a pattern matches in a case statement.
7412 casematch(union node *pattern, char *val)
7414 struct stackmark smark;
7417 setstackmark(&smark);
7418 argbackq = pattern->narg.backquote;
7419 STARTSTACKSTR(expdest);
7421 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7422 /* var_str_list: */ NULL);
7423 STACKSTRNUL(expdest);
7424 result = patmatch(stackblock(), val);
7425 popstackmark(&smark);
7430 /* ============ find_command */
7434 int (*builtin)(int, char **) FAST_FUNC;
7435 /* unsigned flags; */
7437 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7438 /* "regular" builtins always take precedence over commands,
7439 * regardless of PATH=....%builtin... position */
7440 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7441 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7444 smallint cmdtype; /* CMDxxx */
7447 /* index >= 0 for commands without path (slashes) */
7448 /* (TODO: what exactly does the value mean? PATH position?) */
7449 /* index == -1 for commands with slashes */
7450 /* index == (-2 - applet_no) for NOFORK applets */
7451 const struct builtincmd *cmd;
7452 struct funcnode *func;
7455 /* values of cmdtype */
7456 #define CMDUNKNOWN -1 /* no entry in table for command */
7457 #define CMDNORMAL 0 /* command is an executable program */
7458 #define CMDFUNCTION 1 /* command is a shell function */
7459 #define CMDBUILTIN 2 /* command is a shell builtin */
7461 /* action to find_command() */
7462 #define DO_ERR 0x01 /* prints errors */
7463 #define DO_ABS 0x02 /* checks absolute paths */
7464 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7465 #define DO_ALTPATH 0x08 /* using alternate path */
7466 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7468 static void find_command(char *, struct cmdentry *, int, const char *);
7471 /* ============ Hashing commands */
7474 * When commands are first encountered, they are entered in a hash table.
7475 * This ensures that a full path search will not have to be done for them
7476 * on each invocation.
7478 * We should investigate converting to a linear search, even though that
7479 * would make the command name "hash" a misnomer.
7483 struct tblentry *next; /* next entry in hash chain */
7484 union param param; /* definition of builtin function */
7485 smallint cmdtype; /* CMDxxx */
7486 char rehash; /* if set, cd done since entry created */
7487 char cmdname[1]; /* name of command */
7490 static struct tblentry **cmdtable;
7491 #define INIT_G_cmdtable() do { \
7492 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7495 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7499 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7501 #if ENABLE_FEATURE_SH_STANDALONE
7502 if (applet_no >= 0) {
7503 if (APPLET_IS_NOEXEC(applet_no)) {
7507 run_applet_no_and_exit(applet_no, argv);
7509 /* re-exec ourselves with the new arguments */
7510 execve(bb_busybox_exec_path, argv, envp);
7511 /* If they called chroot or otherwise made the binary no longer
7512 * executable, fall through */
7519 execve(cmd, argv, envp);
7520 } while (errno == EINTR);
7522 execve(cmd, argv, envp);
7524 if (cmd == (char*) bb_busybox_exec_path) {
7525 /* We already visited ENOEXEC branch below, don't do it again */
7526 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7530 if (errno == ENOEXEC) {
7531 /* Run "cmd" as a shell script:
7532 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7533 * "If the execve() function fails with ENOEXEC, the shell
7534 * shall execute a command equivalent to having a shell invoked
7535 * with the command name as its first operand,
7536 * with any remaining arguments passed to the new shell"
7538 * That is, do not use $SHELL, user's shell, or /bin/sh;
7539 * just call ourselves.
7541 * Note that bash reads ~80 chars of the file, and if it sees
7542 * a zero byte before it sees newline, it doesn't try to
7543 * interpret it, but fails with "cannot execute binary file"
7544 * message and exit code 126. For one, this prevents attempts
7545 * to interpret foreign ELF binaries as shell scripts.
7550 for (ap = argv; *ap; ap++)
7552 new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
7553 new[0] = (char*) "ash";
7556 while ((*ap++ = *++argv) != NULL)
7558 cmd = (char*) bb_busybox_exec_path;
7565 * Exec a program. Never returns. If you change this routine, you may
7566 * have to change the find_command routine as well.
7568 static void shellexec(char **, const char *, int) NORETURN;
7570 shellexec(char **argv, const char *path, int idx)
7576 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7578 clearredir(/*drop:*/ 1);
7579 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7580 if (strchr(argv[0], '/') != NULL
7581 #if ENABLE_FEATURE_SH_STANDALONE
7582 || (applet_no = find_applet_by_name(argv[0])) >= 0
7585 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7586 if (applet_no >= 0) {
7587 /* We tried execing ourself, but it didn't work.
7588 * Maybe /proc/self/exe doesn't exist?
7597 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7598 if (--idx < 0 && pathopt == NULL) {
7599 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7600 if (errno != ENOENT && errno != ENOTDIR)
7607 /* Map to POSIX errors */
7619 exitstatus = exerrno;
7620 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7621 argv[0], e, suppress_int));
7622 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7627 printentry(struct tblentry *cmdp)
7633 idx = cmdp->param.index;
7636 name = path_advance(&path, cmdp->cmdname);
7638 } while (--idx >= 0);
7639 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7643 * Clear out command entries. The argument specifies the first entry in
7644 * PATH which has changed.
7647 clearcmdentry(int firstchange)
7649 struct tblentry **tblp;
7650 struct tblentry **pp;
7651 struct tblentry *cmdp;
7654 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7656 while ((cmdp = *pp) != NULL) {
7657 if ((cmdp->cmdtype == CMDNORMAL &&
7658 cmdp->param.index >= firstchange)
7659 || (cmdp->cmdtype == CMDBUILTIN &&
7660 builtinloc >= firstchange)
7673 * Locate a command in the command hash table. If "add" is nonzero,
7674 * add the command to the table if it is not already present. The
7675 * variable "lastcmdentry" is set to point to the address of the link
7676 * pointing to the entry, so that delete_cmd_entry can delete the
7679 * Interrupts must be off if called with add != 0.
7681 static struct tblentry **lastcmdentry;
7683 static struct tblentry *
7684 cmdlookup(const char *name, int add)
7686 unsigned int hashval;
7688 struct tblentry *cmdp;
7689 struct tblentry **pp;
7692 hashval = (unsigned char)*p << 4;
7694 hashval += (unsigned char)*p++;
7696 pp = &cmdtable[hashval % CMDTABLESIZE];
7697 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7698 if (strcmp(cmdp->cmdname, name) == 0)
7702 if (add && cmdp == NULL) {
7703 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7705 /* + 1 - already done because
7706 * tblentry::cmdname is char[1] */);
7707 /*cmdp->next = NULL; - ckzalloc did it */
7708 cmdp->cmdtype = CMDUNKNOWN;
7709 strcpy(cmdp->cmdname, name);
7716 * Delete the command entry returned on the last lookup.
7719 delete_cmd_entry(void)
7721 struct tblentry *cmdp;
7724 cmdp = *lastcmdentry;
7725 *lastcmdentry = cmdp->next;
7726 if (cmdp->cmdtype == CMDFUNCTION)
7727 freefunc(cmdp->param.func);
7733 * Add a new command entry, replacing any existing command entry for
7734 * the same name - except special builtins.
7737 addcmdentry(char *name, struct cmdentry *entry)
7739 struct tblentry *cmdp;
7741 cmdp = cmdlookup(name, 1);
7742 if (cmdp->cmdtype == CMDFUNCTION) {
7743 freefunc(cmdp->param.func);
7745 cmdp->cmdtype = entry->cmdtype;
7746 cmdp->param = entry->u;
7750 static int FAST_FUNC
7751 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7753 struct tblentry **pp;
7754 struct tblentry *cmdp;
7756 struct cmdentry entry;
7759 if (nextopt("r") != '\0') {
7764 if (*argptr == NULL) {
7765 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7766 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7767 if (cmdp->cmdtype == CMDNORMAL)
7775 while ((name = *argptr) != NULL) {
7776 cmdp = cmdlookup(name, 0);
7778 && (cmdp->cmdtype == CMDNORMAL
7779 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7783 find_command(name, &entry, DO_ERR, pathval());
7784 if (entry.cmdtype == CMDUNKNOWN)
7792 * Called when a cd is done. Marks all commands so the next time they
7793 * are executed they will be rehashed.
7798 struct tblentry **pp;
7799 struct tblentry *cmdp;
7801 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7802 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7803 if (cmdp->cmdtype == CMDNORMAL
7804 || (cmdp->cmdtype == CMDBUILTIN
7805 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7815 * Fix command hash table when PATH changed.
7816 * Called before PATH is changed. The argument is the new value of PATH;
7817 * pathval() still returns the old value at this point.
7818 * Called with interrupts off.
7820 static void FAST_FUNC
7821 changepath(const char *new)
7829 firstchange = 9999; /* assume no change */
7835 if ((*old == '\0' && *new == ':')
7836 || (*old == ':' && *new == '\0')
7840 old = new; /* ignore subsequent differences */
7844 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7851 if (builtinloc < 0 && idx_bltin >= 0)
7852 builtinloc = idx_bltin; /* zap builtins */
7853 if (builtinloc >= 0 && idx_bltin < 0)
7855 clearcmdentry(firstchange);
7856 builtinloc = idx_bltin;
7881 #if ENABLE_ASH_BASH_COMPAT
7892 typedef smallint token_id_t;
7894 /* Nth bit indicates if token marks the end of a list */
7897 /* 0 */ | (1u << TEOF)
7898 /* 1 */ | (0u << TNL)
7899 /* 2 */ | (0u << TREDIR)
7900 /* 3 */ | (0u << TWORD)
7901 /* 4 */ | (0u << TSEMI)
7902 /* 5 */ | (0u << TBACKGND)
7903 /* 6 */ | (0u << TAND)
7904 /* 7 */ | (0u << TOR)
7905 /* 8 */ | (0u << TPIPE)
7906 /* 9 */ | (0u << TLP)
7907 /* 10 */ | (1u << TRP)
7908 /* 11 */ | (1u << TENDCASE)
7909 /* 12 */ | (1u << TENDBQUOTE)
7910 /* 13 */ | (0u << TNOT)
7911 /* 14 */ | (0u << TCASE)
7912 /* 15 */ | (1u << TDO)
7913 /* 16 */ | (1u << TDONE)
7914 /* 17 */ | (1u << TELIF)
7915 /* 18 */ | (1u << TELSE)
7916 /* 19 */ | (1u << TESAC)
7917 /* 20 */ | (1u << TFI)
7918 /* 21 */ | (0u << TFOR)
7919 #if ENABLE_ASH_BASH_COMPAT
7920 /* 22 */ | (0u << TFUNCTION)
7922 /* 23 */ | (0u << TIF)
7923 /* 24 */ | (0u << TIN)
7924 /* 25 */ | (1u << TTHEN)
7925 /* 26 */ | (0u << TUNTIL)
7926 /* 27 */ | (0u << TWHILE)
7927 /* 28 */ | (0u << TBEGIN)
7928 /* 29 */ | (1u << TEND)
7929 , /* thus far 29 bits used */
7932 static const char *const tokname_array[] = {
7946 #define KWDOFFSET 13
7947 /* the following are keywords */
7957 #if ENABLE_ASH_BASH_COMPAT
7969 /* Wrapper around strcmp for qsort/bsearch/... */
7971 pstrcmp(const void *a, const void *b)
7973 return strcmp((char*)a, *(char**)b);
7976 static const char *const *
7977 findkwd(const char *s)
7979 return bsearch(s, tokname_array + KWDOFFSET,
7980 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7981 sizeof(tokname_array[0]), pstrcmp);
7985 * Locate and print what a word is...
7988 describe_command(char *command, const char *path, int describe_command_verbose)
7990 struct cmdentry entry;
7991 struct tblentry *cmdp;
7992 #if ENABLE_ASH_ALIAS
7993 const struct alias *ap;
7996 path = path ? path : pathval();
7998 if (describe_command_verbose) {
8002 /* First look at the keywords */
8003 if (findkwd(command)) {
8004 out1str(describe_command_verbose ? " is a shell keyword" : command);
8008 #if ENABLE_ASH_ALIAS
8009 /* Then look at the aliases */
8010 ap = lookupalias(command, 0);
8012 if (!describe_command_verbose) {
8017 out1fmt(" is an alias for %s", ap->val);
8021 /* Then check if it is a tracked alias */
8022 cmdp = cmdlookup(command, 0);
8024 entry.cmdtype = cmdp->cmdtype;
8025 entry.u = cmdp->param;
8027 /* Finally use brute force */
8028 find_command(command, &entry, DO_ABS, path);
8031 switch (entry.cmdtype) {
8033 int j = entry.u.index;
8039 p = path_advance(&path, command);
8043 if (describe_command_verbose) {
8045 (cmdp ? " a tracked alias for" : nullstr), p
8054 if (describe_command_verbose) {
8055 out1str(" is a shell function");
8062 if (describe_command_verbose) {
8063 out1fmt(" is a %sshell builtin",
8064 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8065 "special " : nullstr
8073 if (describe_command_verbose) {
8074 out1str(": not found\n");
8083 static int FAST_FUNC
8084 typecmd(int argc UNUSED_PARAM, char **argv)
8090 /* type -p ... ? (we don't bother checking for 'p') */
8091 if (argv[1] && argv[1][0] == '-') {
8096 err |= describe_command(argv[i++], NULL, verbose);
8101 #if ENABLE_ASH_CMDCMD
8102 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8104 parse_command_args(char **argv, const char **path)
8117 if (c == '-' && !*cp) {
8125 *path = bb_default_path;
8128 /* run 'typecmd' for other options */
8137 static int FAST_FUNC
8138 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8146 const char *path = NULL;
8148 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8149 * never reaches this function.
8152 while ((c = nextopt("pvV")) != '\0')
8154 verify |= VERIFY_VERBOSE;
8156 /*verify |= VERIFY_BRIEF*/;
8162 path = bb_default_path;
8164 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8166 if (/*verify && */ cmd)
8167 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8174 /*static int funcblocksize; // size of structures in function */
8175 /*static int funcstringsize; // size of strings in node */
8176 static void *funcblock; /* block to allocate function from */
8177 static char *funcstring_end; /* end of block to allocate strings from */
8179 /* flags in argument to evaltree */
8180 #define EV_EXIT 01 /* exit after evaluating tree */
8181 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8183 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8184 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8185 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8186 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8187 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8188 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8189 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8190 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8191 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8192 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8193 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8194 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8195 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8196 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8197 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8198 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8199 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8200 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8201 #if ENABLE_ASH_BASH_COMPAT
8202 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8204 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8205 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8206 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8207 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8208 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8209 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8210 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8211 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8212 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8215 static int calcsize(int funcblocksize, union node *n);
8218 sizenodelist(int funcblocksize, struct nodelist *lp)
8221 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8222 funcblocksize = calcsize(funcblocksize, lp->n);
8225 return funcblocksize;
8229 calcsize(int funcblocksize, union node *n)
8232 return funcblocksize;
8233 funcblocksize += nodesize[n->type];
8236 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8237 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8238 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8241 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8246 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8247 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8254 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8255 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8258 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8259 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8260 funcblocksize = calcsize(funcblocksize, n->nif.test);
8263 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8264 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8265 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8268 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8269 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8272 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8273 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8274 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8278 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8279 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8280 funcblocksize = calcsize(funcblocksize, n->narg.next);
8283 #if ENABLE_ASH_BASH_COMPAT
8290 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8291 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8295 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8296 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8300 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8301 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8304 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8307 return funcblocksize;
8311 nodeckstrdup(char *s)
8313 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8314 return strcpy(funcstring_end, s);
8317 static union node *copynode(union node *);
8319 static struct nodelist *
8320 copynodelist(struct nodelist *lp)
8322 struct nodelist *start;
8323 struct nodelist **lpp;
8328 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8329 (*lpp)->n = copynode(lp->n);
8331 lpp = &(*lpp)->next;
8338 copynode(union node *n)
8345 funcblock = (char *) funcblock + nodesize[n->type];
8349 new->ncmd.redirect = copynode(n->ncmd.redirect);
8350 new->ncmd.args = copynode(n->ncmd.args);
8351 new->ncmd.assign = copynode(n->ncmd.assign);
8354 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8355 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8360 new->nredir.redirect = copynode(n->nredir.redirect);
8361 new->nredir.n = copynode(n->nredir.n);
8368 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8369 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8372 new->nif.elsepart = copynode(n->nif.elsepart);
8373 new->nif.ifpart = copynode(n->nif.ifpart);
8374 new->nif.test = copynode(n->nif.test);
8377 new->nfor.var = nodeckstrdup(n->nfor.var);
8378 new->nfor.body = copynode(n->nfor.body);
8379 new->nfor.args = copynode(n->nfor.args);
8382 new->ncase.cases = copynode(n->ncase.cases);
8383 new->ncase.expr = copynode(n->ncase.expr);
8386 new->nclist.body = copynode(n->nclist.body);
8387 new->nclist.pattern = copynode(n->nclist.pattern);
8388 new->nclist.next = copynode(n->nclist.next);
8392 new->narg.backquote = copynodelist(n->narg.backquote);
8393 new->narg.text = nodeckstrdup(n->narg.text);
8394 new->narg.next = copynode(n->narg.next);
8397 #if ENABLE_ASH_BASH_COMPAT
8404 new->nfile.fname = copynode(n->nfile.fname);
8405 new->nfile.fd = n->nfile.fd;
8406 new->nfile.next = copynode(n->nfile.next);
8410 new->ndup.vname = copynode(n->ndup.vname);
8411 new->ndup.dupfd = n->ndup.dupfd;
8412 new->ndup.fd = n->ndup.fd;
8413 new->ndup.next = copynode(n->ndup.next);
8417 new->nhere.doc = copynode(n->nhere.doc);
8418 new->nhere.fd = n->nhere.fd;
8419 new->nhere.next = copynode(n->nhere.next);
8422 new->nnot.com = copynode(n->nnot.com);
8425 new->type = n->type;
8430 * Make a copy of a parse tree.
8432 static struct funcnode *
8433 copyfunc(union node *n)
8438 /*funcstringsize = 0;*/
8439 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8440 f = ckzalloc(blocksize /* + funcstringsize */);
8441 funcblock = (char *) f + offsetof(struct funcnode, n);
8442 funcstring_end = (char *) f + blocksize;
8444 /* f->count = 0; - ckzalloc did it */
8449 * Define a shell function.
8452 defun(union node *func)
8454 struct cmdentry entry;
8457 entry.cmdtype = CMDFUNCTION;
8458 entry.u.func = copyfunc(func);
8459 addcmdentry(func->narg.text, &entry);
8463 /* Reasons for skipping commands (see comment on breakcmd routine) */
8464 #define SKIPBREAK (1 << 0)
8465 #define SKIPCONT (1 << 1)
8466 #define SKIPFUNC (1 << 2)
8467 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8468 static int skipcount; /* number of levels to skip */
8469 static int funcnest; /* depth of function calls */
8470 static int loopnest; /* current loop nesting level */
8472 /* Forward decl way out to parsing code - dotrap needs it */
8473 static int evalstring(char *s, int flags);
8475 /* Called to execute a trap.
8476 * Single callsite - at the end of evaltree().
8477 * If we return non-zero, evaltree raises EXEXIT exception.
8479 * Perhaps we should avoid entering new trap handlers
8480 * while we are executing a trap handler. [is it a TODO?]
8487 uint8_t last_status;
8492 last_status = exitstatus;
8496 TRACE(("dotrap entered\n"));
8497 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8509 /* non-trapped SIGINT is handled separately by raise_interrupt,
8510 * don't upset it by resetting gotsig[SIGINT-1] */
8511 if (sig == SIGINT && !p)
8514 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8520 exitstatus = last_status;
8521 TRACE(("dotrap returns\n"));
8524 /* forward declarations - evaluation is fairly recursive business... */
8525 static int evalloop(union node *, int);
8526 static int evalfor(union node *, int);
8527 static int evalcase(union node *, int);
8528 static int evalsubshell(union node *, int);
8529 static void expredir(union node *);
8530 static int evalpipe(union node *, int);
8531 static int evalcommand(union node *, int);
8532 static int evalbltin(const struct builtincmd *, int, char **, int);
8533 static void prehash(union node *);
8536 * Evaluate a parse tree. The value is left in the global variable
8540 evaltree(union node *n, int flags)
8542 struct jmploc *volatile savehandler = exception_handler;
8543 struct jmploc jmploc;
8545 int (*evalfn)(union node *, int);
8549 SAVE_INT(int_level);
8552 TRACE(("evaltree(NULL) called\n"));
8555 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8559 exception_handler = &jmploc;
8561 int err = setjmp(jmploc.loc);
8563 /* if it was a signal, check for trap handlers */
8564 if (exception_type == EXSIG) {
8565 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8566 exception_type, err));
8569 /* continue on the way out */
8570 TRACE(("exception %d in evaltree, propagating err=%d\n",
8571 exception_type, err));
8572 exception_handler = savehandler;
8573 longjmp(exception_handler->loc, err);
8580 out1fmt("Node type = %d\n", n->type);
8585 status = !evaltree(n->nnot.com, EV_TESTED);
8588 expredir(n->nredir.redirect);
8589 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8591 status = evaltree(n->nredir.n, flags & EV_TESTED);
8593 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8596 evalfn = evalcommand;
8598 if (eflag && !(flags & EV_TESTED))
8610 evalfn = evalsubshell;
8623 #error NAND + 1 != NOR
8625 #if NOR + 1 != NSEMI
8626 #error NOR + 1 != NSEMI
8628 unsigned is_or = n->type - NAND;
8631 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8633 if ((!status) == is_or || evalskip)
8639 status = evalfn(n, flags);
8643 status = evaltree(n->nif.test, EV_TESTED);
8650 if (n->nif.elsepart) {
8651 n = n->nif.elsepart;
8658 /* Not necessary. To test it:
8659 * "false; f() { qwerty; }; echo $?" should print 0.
8663 exitstatus = status;
8668 exception_handler = savehandler;
8671 /* Order of checks below is important:
8672 * signal handlers trigger before exit caused by "set -e".
8676 if (checkexit & status)
8677 raise_exception(EXEXIT);
8678 if (flags & EV_EXIT)
8679 raise_exception(EXEXIT);
8681 RESTORE_INT(int_level);
8682 TRACE(("leaving evaltree (no interrupts)\n"));
8687 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8690 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8695 int skip = evalskip;
8702 if (--skipcount <= 0) {
8713 evalloop(union node *n, int flags)
8724 i = evaltree(n->nbinary.ch1, EV_TESTED);
8726 if (skip == SKIPFUNC)
8730 if (n->type != NWHILE)
8734 status = evaltree(n->nbinary.ch2, flags);
8736 } while (!(skip & ~SKIPCONT));
8743 evalfor(union node *n, int flags)
8745 struct arglist arglist;
8748 struct stackmark smark;
8751 setstackmark(&smark);
8752 arglist.list = NULL;
8753 arglist.lastp = &arglist.list;
8754 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8755 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8757 *arglist.lastp = NULL;
8761 for (sp = arglist.list; sp; sp = sp->next) {
8762 setvar0(n->nfor.var, sp->text);
8763 status = evaltree(n->nfor.body, flags);
8764 if (skiploop() & ~SKIPCONT)
8768 popstackmark(&smark);
8774 evalcase(union node *n, int flags)
8778 struct arglist arglist;
8779 struct stackmark smark;
8782 setstackmark(&smark);
8783 arglist.list = NULL;
8784 arglist.lastp = &arglist.list;
8785 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8786 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8787 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8788 if (casematch(patp, arglist.list->text)) {
8789 /* Ensure body is non-empty as otherwise
8790 * EV_EXIT may prevent us from setting the
8793 if (evalskip == 0 && cp->nclist.body) {
8794 status = evaltree(cp->nclist.body, flags);
8801 popstackmark(&smark);
8807 * Kick off a subshell to evaluate a tree.
8810 evalsubshell(union node *n, int flags)
8813 int backgnd = (n->type == NBACKGND);
8816 expredir(n->nredir.redirect);
8817 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8820 jp = makejob(/*n,*/ 1);
8821 if (forkshell(jp, n, backgnd) == 0) {
8826 flags &= ~EV_TESTED;
8828 redirect(n->nredir.redirect, 0);
8829 evaltreenr(n->nredir.n, flags);
8834 status = waitforjob(jp);
8840 * Compute the names of the files in a redirection list.
8842 static void fixredir(union node *, const char *, int);
8844 expredir(union node *n)
8848 for (redir = n; redir; redir = redir->nfile.next) {
8852 fn.lastp = &fn.list;
8853 switch (redir->type) {
8857 #if ENABLE_ASH_BASH_COMPAT
8862 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8863 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8864 #if ENABLE_ASH_BASH_COMPAT
8868 // By the design of stack allocator, the loop of this kind:
8869 // while true; do while true; do break; done </dev/null; done
8870 // will look like a memory leak: ash plans to free expfname's
8871 // of "/dev/null" as soon as it finishes running the loop
8872 // (in this case, never).
8873 // This "fix" is wrong:
8874 if (redir->nfile.expfname)
8875 stunalloc(redir->nfile.expfname);
8876 // It results in corrupted state of stacked allocations.
8878 redir->nfile.expfname = fn.list->text;
8881 case NTOFD: /* >& */
8882 if (redir->ndup.vname) {
8883 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8884 if (fn.list == NULL)
8885 ash_msg_and_raise_error("redir error");
8886 #if ENABLE_ASH_BASH_COMPAT
8887 //FIXME: we used expandarg with different args!
8888 if (!isdigit_str9(fn.list->text)) {
8889 /* >&file, not >&fd */
8890 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8891 ash_msg_and_raise_error("redir error");
8893 goto store_expfname;
8896 fixredir(redir, fn.list->text, 1);
8904 * Evaluate a pipeline. All the processes in the pipeline are children
8905 * of the process creating the pipeline. (This differs from some versions
8906 * of the shell, which make the last process in a pipeline the parent
8910 evalpipe(union node *n, int flags)
8913 struct nodelist *lp;
8919 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8921 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8925 jp = makejob(/*n,*/ pipelen);
8927 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8931 if (pipe(pip) < 0) {
8933 ash_msg_and_raise_error("pipe call failed");
8936 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8949 evaltreenr(lp->n, flags);
8955 /* Don't want to trigger debugging */
8959 if (n->npipe.pipe_backgnd == 0) {
8960 status = waitforjob(jp);
8961 TRACE(("evalpipe: job done exit status %d\n", status));
8969 * Controls whether the shell is interactive or not.
8972 setinteractive(int on)
8974 static smallint is_interactive;
8976 if (++on == is_interactive)
8978 is_interactive = on;
8982 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8983 if (is_interactive > 1) {
8984 /* Looks like they want an interactive shell */
8985 static smallint did_banner;
8988 /* note: ash and hush share this string */
8989 out1fmt("\n\n%s %s\n"
8990 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
8993 "built-in shell (ash)"
9007 setinteractive(iflag);
9009 #if ENABLE_FEATURE_EDITING_VI
9011 line_input_state->flags |= VI_MODE;
9013 line_input_state->flags &= ~VI_MODE;
9015 viflag = 0; /* forcibly keep the option off */
9019 static struct localvar *localvars;
9022 * Called after a function returns.
9023 * Interrupts must be off.
9028 struct localvar *lvp;
9031 while ((lvp = localvars) != NULL) {
9032 localvars = lvp->next;
9034 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9035 if (vp == NULL) { /* $- saved */
9036 memcpy(optlist, lvp->text, sizeof(optlist));
9037 free((char*)lvp->text);
9039 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9040 unsetvar(vp->var_text);
9043 vp->var_func(var_end(lvp->text));
9044 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9045 free((char*)vp->var_text);
9046 vp->flags = lvp->flags;
9047 vp->var_text = lvp->text;
9054 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9056 volatile struct shparam saveparam;
9057 struct localvar *volatile savelocalvars;
9058 struct jmploc *volatile savehandler;
9059 struct jmploc jmploc;
9062 saveparam = shellparam;
9063 savelocalvars = localvars;
9064 savehandler = exception_handler;
9065 e = setjmp(jmploc.loc);
9070 exception_handler = &jmploc;
9072 shellparam.malloced = 0;
9076 shellparam.nparam = argc - 1;
9077 shellparam.p = argv + 1;
9078 #if ENABLE_ASH_GETOPTS
9079 shellparam.optind = 1;
9080 shellparam.optoff = -1;
9082 evaltree(func->n.narg.next, flags & EV_TESTED);
9088 localvars = savelocalvars;
9089 freeparam(&shellparam);
9090 shellparam = saveparam;
9091 exception_handler = savehandler;
9093 evalskip &= ~SKIPFUNC;
9098 * Make a variable a local variable. When a variable is made local, it's
9099 * value and flags are saved in a localvar structure. The saved values
9100 * will be restored when the shell function returns. We handle the name
9101 * "-" as a special case: it makes changes to "set +-options" local
9102 * (options will be restored on return from the function).
9107 struct localvar *lvp;
9110 char *eq = strchr(name, '=');
9113 /* Cater for duplicate "local". Examples:
9114 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9115 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9119 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9123 * it's a duplicate "local VAR" declaration, do nothing
9130 lvp = ckzalloc(sizeof(*lvp));
9131 if (LONE_DASH(name)) {
9133 p = ckmalloc(sizeof(optlist));
9134 lvp->text = memcpy(p, optlist, sizeof(optlist));
9137 vpp = hashvar(name);
9138 vp = *findvar(vpp, name);
9140 /* variable did not exist yet */
9142 setvareq(name, VSTRFIXED);
9144 setvar(name, NULL, VSTRFIXED);
9145 vp = *vpp; /* the new variable */
9146 lvp->flags = VUNSET;
9148 lvp->text = vp->var_text;
9149 lvp->flags = vp->flags;
9150 /* make sure neither "struct var" nor string gets freed
9151 * during (un)setting:
9153 vp->flags |= VSTRFIXED|VTEXTFIXED;
9157 /* "local VAR" unsets VAR: */
9158 setvar0(name, NULL);
9162 lvp->next = localvars;
9168 * The "local" command.
9170 static int FAST_FUNC
9171 localcmd(int argc UNUSED_PARAM, char **argv)
9176 ash_msg_and_raise_error("not in a function");
9179 while ((name = *argv++) != NULL) {
9185 static int FAST_FUNC
9186 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9191 static int FAST_FUNC
9192 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9197 static int FAST_FUNC
9198 execcmd(int argc UNUSED_PARAM, char **argv)
9201 iflag = 0; /* exit on error */
9204 /* We should set up signals for "exec CMD"
9205 * the same way as for "CMD" without "exec".
9206 * But optschanged->setinteractive->setsignal
9207 * still thought we are a root shell. Therefore, for example,
9208 * SIGQUIT is still set to IGN. Fix it:
9212 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9213 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9214 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9216 shellexec(argv + 1, pathval(), 0);
9223 * The return command.
9225 static int FAST_FUNC
9226 returncmd(int argc UNUSED_PARAM, char **argv)
9229 * If called outside a function, do what ksh does;
9230 * skip the rest of the file.
9232 evalskip = SKIPFUNC;
9233 return argv[1] ? number(argv[1]) : exitstatus;
9236 /* Forward declarations for builtintab[] */
9237 static int breakcmd(int, char **) FAST_FUNC;
9238 static int dotcmd(int, char **) FAST_FUNC;
9239 static int evalcmd(int, char **, int) FAST_FUNC;
9240 static int exitcmd(int, char **) FAST_FUNC;
9241 static int exportcmd(int, char **) FAST_FUNC;
9242 #if ENABLE_ASH_GETOPTS
9243 static int getoptscmd(int, char **) FAST_FUNC;
9246 static int helpcmd(int, char **) FAST_FUNC;
9249 static int historycmd(int, char **) FAST_FUNC;
9251 #if ENABLE_SH_MATH_SUPPORT
9252 static int letcmd(int, char **) FAST_FUNC;
9254 static int readcmd(int, char **) FAST_FUNC;
9255 static int setcmd(int, char **) FAST_FUNC;
9256 static int shiftcmd(int, char **) FAST_FUNC;
9257 static int timescmd(int, char **) FAST_FUNC;
9258 static int trapcmd(int, char **) FAST_FUNC;
9259 static int umaskcmd(int, char **) FAST_FUNC;
9260 static int unsetcmd(int, char **) FAST_FUNC;
9261 static int ulimitcmd(int, char **) FAST_FUNC;
9263 #define BUILTIN_NOSPEC "0"
9264 #define BUILTIN_SPECIAL "1"
9265 #define BUILTIN_REGULAR "2"
9266 #define BUILTIN_SPEC_REG "3"
9267 #define BUILTIN_ASSIGN "4"
9268 #define BUILTIN_SPEC_ASSG "5"
9269 #define BUILTIN_REG_ASSG "6"
9270 #define BUILTIN_SPEC_REG_ASSG "7"
9272 /* Stubs for calling non-FAST_FUNC's */
9273 #if ENABLE_ASH_BUILTIN_ECHO
9274 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9276 #if ENABLE_ASH_BUILTIN_PRINTF
9277 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9279 #if ENABLE_ASH_BUILTIN_TEST
9280 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9283 /* Keep these in proper order since it is searched via bsearch() */
9284 static const struct builtincmd builtintab[] = {
9285 { BUILTIN_SPEC_REG "." , dotcmd },
9286 { BUILTIN_SPEC_REG ":" , truecmd },
9287 #if ENABLE_ASH_BUILTIN_TEST
9288 { BUILTIN_REGULAR "[" , testcmd },
9289 #if ENABLE_ASH_BASH_COMPAT
9290 { BUILTIN_REGULAR "[[" , testcmd },
9293 #if ENABLE_ASH_ALIAS
9294 { BUILTIN_REG_ASSG "alias" , aliascmd },
9297 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9299 { BUILTIN_SPEC_REG "break" , breakcmd },
9300 { BUILTIN_REGULAR "cd" , cdcmd },
9301 { BUILTIN_NOSPEC "chdir" , cdcmd },
9302 #if ENABLE_ASH_CMDCMD
9303 { BUILTIN_REGULAR "command" , commandcmd },
9305 { BUILTIN_SPEC_REG "continue", breakcmd },
9306 #if ENABLE_ASH_BUILTIN_ECHO
9307 { BUILTIN_REGULAR "echo" , echocmd },
9309 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9310 { BUILTIN_SPEC_REG "exec" , execcmd },
9311 { BUILTIN_SPEC_REG "exit" , exitcmd },
9312 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9313 { BUILTIN_REGULAR "false" , falsecmd },
9315 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9317 #if ENABLE_ASH_GETOPTS
9318 { BUILTIN_REGULAR "getopts" , getoptscmd },
9320 { BUILTIN_NOSPEC "hash" , hashcmd },
9322 { BUILTIN_NOSPEC "help" , helpcmd },
9325 { BUILTIN_NOSPEC "history" , historycmd },
9328 { BUILTIN_REGULAR "jobs" , jobscmd },
9329 { BUILTIN_REGULAR "kill" , killcmd },
9331 #if ENABLE_SH_MATH_SUPPORT
9332 { BUILTIN_NOSPEC "let" , letcmd },
9334 { BUILTIN_ASSIGN "local" , localcmd },
9335 #if ENABLE_ASH_BUILTIN_PRINTF
9336 { BUILTIN_REGULAR "printf" , printfcmd },
9338 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9339 { BUILTIN_REGULAR "read" , readcmd },
9340 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9341 { BUILTIN_SPEC_REG "return" , returncmd },
9342 { BUILTIN_SPEC_REG "set" , setcmd },
9343 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9344 #if ENABLE_ASH_BASH_COMPAT
9345 { BUILTIN_SPEC_REG "source" , dotcmd },
9347 #if ENABLE_ASH_BUILTIN_TEST
9348 { BUILTIN_REGULAR "test" , testcmd },
9350 { BUILTIN_SPEC_REG "times" , timescmd },
9351 { BUILTIN_SPEC_REG "trap" , trapcmd },
9352 { BUILTIN_REGULAR "true" , truecmd },
9353 { BUILTIN_NOSPEC "type" , typecmd },
9354 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9355 { BUILTIN_REGULAR "umask" , umaskcmd },
9356 #if ENABLE_ASH_ALIAS
9357 { BUILTIN_REGULAR "unalias" , unaliascmd },
9359 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9360 { BUILTIN_REGULAR "wait" , waitcmd },
9363 /* Should match the above table! */
9364 #define COMMANDCMD (builtintab + \
9366 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9367 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9368 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9369 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9370 /* break cd cddir */ 3)
9371 #define EVALCMD (COMMANDCMD + \
9372 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9373 /* continue */ 1 + \
9374 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9376 #define EXECCMD (EVALCMD + \
9380 * Search the table of builtin commands.
9383 pstrcmp1(const void *a, const void *b)
9385 return strcmp((char*)a, *(char**)b + 1);
9387 static struct builtincmd *
9388 find_builtin(const char *name)
9390 struct builtincmd *bp;
9393 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9400 * Execute a simple command.
9403 isassignment(const char *p)
9405 const char *q = endofname(p);
9410 static int FAST_FUNC
9411 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9413 /* Preserve exitstatus of a previous possible redirection
9414 * as POSIX mandates */
9415 return back_exitstatus;
9418 evalcommand(union node *cmd, int flags)
9420 static const struct builtincmd null_bltin = {
9421 "\0\0", bltincmd /* why three NULs? */
9423 struct stackmark smark;
9425 struct arglist arglist;
9426 struct arglist varlist;
9429 const struct strlist *sp;
9430 struct cmdentry cmdentry;
9437 struct builtincmd *bcmd;
9438 smallint cmd_is_exec;
9439 smallint pseudovarflag = 0;
9441 /* First expand the arguments. */
9442 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9443 setstackmark(&smark);
9444 back_exitstatus = 0;
9446 cmdentry.cmdtype = CMDBUILTIN;
9447 cmdentry.u.cmd = &null_bltin;
9448 varlist.lastp = &varlist.list;
9449 *varlist.lastp = NULL;
9450 arglist.lastp = &arglist.list;
9451 *arglist.lastp = NULL;
9454 if (cmd->ncmd.args) {
9455 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9456 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9459 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9460 struct strlist **spp;
9462 spp = arglist.lastp;
9463 if (pseudovarflag && isassignment(argp->narg.text))
9464 expandarg(argp, &arglist, EXP_VARTILDE);
9466 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9468 for (sp = *spp; sp; sp = sp->next)
9472 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9473 for (sp = arglist.list; sp; sp = sp->next) {
9474 TRACE(("evalcommand arg: %s\n", sp->text));
9475 *nargv++ = sp->text;
9480 if (iflag && funcnest == 0 && argc > 0)
9481 lastarg = nargv[-1];
9484 expredir(cmd->ncmd.redirect);
9485 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9487 path = vpath.var_text;
9488 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9489 struct strlist **spp;
9492 spp = varlist.lastp;
9493 expandarg(argp, &varlist, EXP_VARTILDE);
9496 * Modify the command lookup path, if a PATH= assignment
9500 if (varcmp(p, path) == 0)
9504 /* Print the command if xflag is set. */
9507 const char *p = " %s" + 1;
9509 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9511 for (n = 0; n < 2; n++) {
9513 fdprintf(preverrout_fd, p, sp->text);
9519 safe_write(preverrout_fd, "\n", 1);
9525 /* Now locate the command. */
9527 int cmd_flag = DO_ERR;
9528 #if ENABLE_ASH_CMDCMD
9529 const char *oldpath = path + 5;
9533 find_command(argv[0], &cmdentry, cmd_flag, path);
9534 if (cmdentry.cmdtype == CMDUNKNOWN) {
9535 flush_stdout_stderr();
9540 /* implement bltin and command here */
9541 if (cmdentry.cmdtype != CMDBUILTIN)
9544 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9545 if (cmdentry.u.cmd == EXECCMD)
9547 #if ENABLE_ASH_CMDCMD
9548 if (cmdentry.u.cmd == COMMANDCMD) {
9550 nargv = parse_command_args(argv, &path);
9553 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9554 * nargv => "PROG". path is updated if -p.
9556 argc -= nargv - argv;
9558 cmd_flag |= DO_NOFUNC;
9566 /* We have a redirection error. */
9568 raise_exception(EXERROR);
9570 exitstatus = status;
9574 /* Execute the command. */
9575 switch (cmdentry.cmdtype) {
9578 #if ENABLE_FEATURE_SH_NOFORK
9579 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9580 * around run_nofork_applet() call.
9581 * (2) Should this check also be done in forkshell()?
9582 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9584 /* find_command() encodes applet_no as (-2 - applet_no) */
9585 int applet_no = (- cmdentry.u.index - 2);
9586 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9587 listsetvar(varlist.list, VEXPORT|VSTACK);
9588 /* run <applet>_main() */
9589 status = run_nofork_applet(applet_no, argv);
9593 /* Can we avoid forking off? For example, very last command
9594 * in a script or a subshell does not need forking,
9595 * we can just exec it.
9597 if (!(flags & EV_EXIT) || may_have_traps) {
9598 /* No, forking off a child is necessary */
9600 jp = makejob(/*cmd,*/ 1);
9601 if (forkshell(jp, cmd, FORK_FG) != 0) {
9603 status = waitforjob(jp);
9605 TRACE(("forked child exited with %d\n", status));
9610 /* fall through to exec'ing external program */
9612 listsetvar(varlist.list, VEXPORT|VSTACK);
9613 shellexec(argv, path, cmdentry.u.index);
9617 cmdenviron = varlist.list;
9619 struct strlist *list = cmdenviron;
9621 if (spclbltin > 0 || argc == 0) {
9623 if (cmd_is_exec && argc > 1)
9626 listsetvar(list, i);
9628 /* Tight loop with builtins only:
9629 * "while kill -0 $child; do true; done"
9630 * will never exit even if $child died, unless we do this
9631 * to reap the zombie and make kill detect that it's gone: */
9632 dowait(DOWAIT_NONBLOCK, NULL);
9634 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9636 int i = exception_type;
9641 exit_status = 128 + SIGINT;
9643 exit_status = 128 + pending_sig;
9644 exitstatus = exit_status;
9645 if (i == EXINT || spclbltin > 0) {
9647 longjmp(exception_handler->loc, 1);
9654 listsetvar(varlist.list, 0);
9655 /* See above for the rationale */
9656 dowait(DOWAIT_NONBLOCK, NULL);
9657 if (evalfun(cmdentry.u.func, argc, argv, flags))
9660 status = exitstatus;
9665 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9667 /* dsl: I think this is intended to be used to support
9668 * '_' in 'vi' command mode during line editing...
9669 * However I implemented that within libedit itself.
9671 setvar0("_", lastarg);
9673 popstackmark(&smark);
9679 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9681 char *volatile savecmdname;
9682 struct jmploc *volatile savehandler;
9683 struct jmploc jmploc;
9687 savecmdname = commandname;
9688 savehandler = exception_handler;
9689 i = setjmp(jmploc.loc);
9692 exception_handler = &jmploc;
9693 commandname = argv[0];
9695 optptr = NULL; /* initialize nextopt */
9697 status = evalcmd(argc, argv, flags);
9699 status = (*cmd->builtin)(argc, argv);
9700 flush_stdout_stderr();
9701 status |= ferror(stdout);
9702 exitstatus = status;
9705 commandname = savecmdname;
9706 exception_handler = savehandler;
9712 goodname(const char *p)
9714 return endofname(p)[0] == '\0';
9719 * Search for a command. This is called before we fork so that the
9720 * location of the command will be available in the parent as well as
9721 * the child. The check for "goodname" is an overly conservative
9722 * check that the name will not be subject to expansion.
9725 prehash(union node *n)
9727 struct cmdentry entry;
9729 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9730 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9734 /* ============ Builtin commands
9736 * Builtin commands whose functions are closely tied to evaluation
9737 * are implemented here.
9741 * Handle break and continue commands. Break, continue, and return are
9742 * all handled by setting the evalskip flag. The evaluation routines
9743 * above all check this flag, and if it is set they start skipping
9744 * commands rather than executing them. The variable skipcount is
9745 * the number of loops to break/continue, or the number of function
9746 * levels to return. (The latter is always 1.) It should probably
9747 * be an error to break out of more loops than exist, but it isn't
9748 * in the standard shell so we don't make it one here.
9750 static int FAST_FUNC
9751 breakcmd(int argc UNUSED_PARAM, char **argv)
9753 int n = argv[1] ? number(argv[1]) : 1;
9756 ash_msg_and_raise_error(msg_illnum, argv[1]);
9760 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9767 /* ============ input.c
9769 * This implements the input routines used by the parser.
9773 INPUT_PUSH_FILE = 1,
9774 INPUT_NOFILE_OK = 2,
9777 static smallint checkkwd;
9778 /* values of checkkwd variable */
9779 #define CHKALIAS 0x1
9784 * Push a string back onto the input at this current parsefile level.
9785 * We handle aliases this way.
9787 #if !ENABLE_ASH_ALIAS
9788 #define pushstring(s, ap) pushstring(s)
9791 pushstring(char *s, struct alias *ap)
9798 if (g_parsefile->strpush) {
9799 sp = ckzalloc(sizeof(*sp));
9800 sp->prev = g_parsefile->strpush;
9802 sp = &(g_parsefile->basestrpush);
9804 g_parsefile->strpush = sp;
9805 sp->prev_string = g_parsefile->next_to_pgetc;
9806 sp->prev_left_in_line = g_parsefile->left_in_line;
9807 sp->unget = g_parsefile->unget;
9808 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9809 #if ENABLE_ASH_ALIAS
9812 ap->flag |= ALIASINUSE;
9816 g_parsefile->next_to_pgetc = s;
9817 g_parsefile->left_in_line = len;
9818 g_parsefile->unget = 0;
9825 struct strpush *sp = g_parsefile->strpush;
9828 #if ENABLE_ASH_ALIAS
9830 if (g_parsefile->next_to_pgetc[-1] == ' '
9831 || g_parsefile->next_to_pgetc[-1] == '\t'
9833 checkkwd |= CHKALIAS;
9835 if (sp->string != sp->ap->val) {
9838 sp->ap->flag &= ~ALIASINUSE;
9839 if (sp->ap->flag & ALIASDEAD) {
9840 unalias(sp->ap->name);
9844 g_parsefile->next_to_pgetc = sp->prev_string;
9845 g_parsefile->left_in_line = sp->prev_left_in_line;
9846 g_parsefile->unget = sp->unget;
9847 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9848 g_parsefile->strpush = sp->prev;
9849 if (sp != &(g_parsefile->basestrpush))
9858 char *buf = g_parsefile->buf;
9860 g_parsefile->next_to_pgetc = buf;
9861 #if ENABLE_FEATURE_EDITING
9863 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9864 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9867 # if ENABLE_ASH_IDLE_TIMEOUT
9869 const char *tmout_var = lookupvar("TMOUT");
9871 timeout = atoi(tmout_var) * 1000;
9877 # if ENABLE_FEATURE_TAB_COMPLETION
9878 line_input_state->path_lookup = pathval();
9880 reinit_unicode_for_ash();
9881 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9883 /* Ctrl+C pressed */
9894 /* Ctrl+D pressed */
9897 # if ENABLE_ASH_IDLE_TIMEOUT
9898 else if (errno == EAGAIN && timeout > 0) {
9899 puts("\007timed out waiting for input: auto-logout");
9906 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9909 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9911 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9912 int flags = fcntl(0, F_GETFL);
9913 if (flags >= 0 && (flags & O_NONBLOCK)) {
9914 flags &= ~O_NONBLOCK;
9915 if (fcntl(0, F_SETFL, flags) >= 0) {
9916 out2str("sh: turning off NDELAY mode\n");
9927 * Refill the input buffer and return the next input character:
9929 * 1) If a string was pushed back on the input, pop it;
9930 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9931 * or we are reading from a string so we can't refill the buffer,
9933 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9934 * 4) Process input up to the next newline, deleting nul characters.
9936 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9937 #define pgetc_debug(...) ((void)0)
9938 static int pgetc(void);
9945 if (g_parsefile->strpush) {
9946 #if ENABLE_ASH_ALIAS
9947 if (g_parsefile->left_in_line == -1
9948 && g_parsefile->strpush->ap
9949 && g_parsefile->next_to_pgetc[-1] != ' '
9950 && g_parsefile->next_to_pgetc[-1] != '\t'
9952 pgetc_debug("preadbuffer PEOA");
9959 /* on both branches above g_parsefile->left_in_line < 0.
9960 * "pgetc" needs refilling.
9963 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9964 * pungetc() may increment it a few times.
9965 * Assuming it won't increment it to less than -90.
9967 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9968 pgetc_debug("preadbuffer PEOF1");
9969 /* even in failure keep left_in_line and next_to_pgetc
9970 * in lock step, for correct multi-layer pungetc.
9971 * left_in_line was decremented before preadbuffer(),
9972 * must inc next_to_pgetc: */
9973 g_parsefile->next_to_pgetc++;
9977 more = g_parsefile->left_in_buffer;
9979 flush_stdout_stderr();
9983 /* don't try reading again */
9984 g_parsefile->left_in_line = -99;
9985 pgetc_debug("preadbuffer PEOF2");
9986 g_parsefile->next_to_pgetc++;
9991 /* Find out where's the end of line.
9992 * Set g_parsefile->left_in_line
9993 * and g_parsefile->left_in_buffer acordingly.
9994 * NUL chars are deleted.
9996 q = g_parsefile->next_to_pgetc;
10004 memmove(q, q + 1, more);
10008 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10014 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10015 if (g_parsefile->left_in_line < 0)
10020 g_parsefile->left_in_buffer = more;
10025 out2str(g_parsefile->next_to_pgetc);
10029 pgetc_debug("preadbuffer at %d:%p'%s'",
10030 g_parsefile->left_in_line,
10031 g_parsefile->next_to_pgetc,
10032 g_parsefile->next_to_pgetc);
10033 return (unsigned char)*g_parsefile->next_to_pgetc++;
10039 g_parsefile->linno++;
10040 setprompt_if(doprompt, 2);
10045 g_parsefile->linno++;
10046 needprompt = doprompt;
10054 pgetc_debug("pgetc at %d:%p'%s'",
10055 g_parsefile->left_in_line,
10056 g_parsefile->next_to_pgetc,
10057 g_parsefile->next_to_pgetc);
10058 if (g_parsefile->unget)
10059 return g_parsefile->lastc[--g_parsefile->unget];
10061 if (--g_parsefile->left_in_line >= 0)
10062 c = (signed char)*g_parsefile->next_to_pgetc++;
10066 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10067 g_parsefile->lastc[0] = c;
10072 #if ENABLE_ASH_ALIAS
10074 pgetc_without_PEOA(void)
10078 pgetc_debug("pgetc at %d:%p'%s'",
10079 g_parsefile->left_in_line,
10080 g_parsefile->next_to_pgetc,
10081 g_parsefile->next_to_pgetc);
10083 } while (c == PEOA);
10087 # define pgetc_without_PEOA() pgetc()
10091 * Read a line from the script.
10094 pfgets(char *line, int len)
10100 while (--nleft > 0) {
10101 c = pgetc_without_PEOA();
10116 * Undo a call to pgetc. Only two characters may be pushed back.
10117 * PEOF may be pushed back.
10122 g_parsefile->unget++;
10125 /* This one eats backslash+newline */
10131 while ((c = pgetc()) == '\\') {
10132 if (pgetc() != '\n') {
10144 * To handle the "." command, a stack of input files is used. Pushfile
10145 * adds a new entry to the stack and popfile restores the previous level.
10150 struct parsefile *pf;
10152 pf = ckzalloc(sizeof(*pf));
10153 pf->prev = g_parsefile;
10155 /*pf->strpush = NULL; - ckzalloc did it */
10156 /*pf->basestrpush.prev = NULL;*/
10164 struct parsefile *pf = g_parsefile;
10167 if (pf->pf_fd >= 0)
10170 while (pf->strpush)
10172 g_parsefile = pf->prev;
10178 * Return to top level.
10183 while (g_parsefile != &basepf)
10188 * Close the file(s) that the shell is reading commands from. Called
10189 * after a fork is done.
10195 if (g_parsefile->pf_fd > 0) {
10196 close(g_parsefile->pf_fd);
10197 g_parsefile->pf_fd = 0;
10202 * Like setinputfile, but takes an open file descriptor. Call this with
10206 setinputfd(int fd, int push)
10208 close_on_exec_on(fd);
10211 g_parsefile->buf = NULL;
10213 g_parsefile->pf_fd = fd;
10214 if (g_parsefile->buf == NULL)
10215 g_parsefile->buf = ckmalloc(IBUFSIZ);
10216 g_parsefile->left_in_buffer = 0;
10217 g_parsefile->left_in_line = 0;
10218 g_parsefile->linno = 1;
10222 * Set the input to take input from a file. If push is set, push the
10223 * old input onto the stack first.
10226 setinputfile(const char *fname, int flags)
10232 fd = open(fname, O_RDONLY);
10234 if (flags & INPUT_NOFILE_OK)
10237 ash_msg_and_raise_error("can't open '%s'", fname);
10240 fd2 = copyfd(fd, 10);
10244 setinputfd(fd, flags & INPUT_PUSH_FILE);
10251 * Like setinputfile, but takes input from a string.
10254 setinputstring(char *string)
10258 g_parsefile->next_to_pgetc = string;
10259 g_parsefile->left_in_line = strlen(string);
10260 g_parsefile->buf = NULL;
10261 g_parsefile->linno = 1;
10266 /* ============ mail.c
10268 * Routines to check for mail.
10271 #if ENABLE_ASH_MAIL
10273 /* Hash of mtimes of mailboxes */
10274 static unsigned mailtime_hash;
10275 /* Set if MAIL or MAILPATH is changed. */
10276 static smallint mail_var_path_changed;
10279 * Print appropriate message(s) if mail has arrived.
10280 * If mail_var_path_changed is set,
10281 * then the value of MAIL has mail_var_path_changed,
10282 * so we just update the values.
10291 struct stackmark smark;
10294 setstackmark(&smark);
10295 mpath = mpathset() ? mpathval() : mailval();
10298 p = path_advance(&mpath, nullstr);
10303 for (q = p; *q; q++)
10309 q[-1] = '\0'; /* delete trailing '/' */
10310 if (stat(p, &statb) < 0) {
10313 /* Very simplistic "hash": just a sum of all mtimes */
10314 new_hash += (unsigned)statb.st_mtime;
10316 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10317 if (mailtime_hash != 0)
10318 out2str("you have mail\n");
10319 mailtime_hash = new_hash;
10321 mail_var_path_changed = 0;
10322 popstackmark(&smark);
10325 static void FAST_FUNC
10326 changemail(const char *val UNUSED_PARAM)
10328 mail_var_path_changed = 1;
10331 #endif /* ASH_MAIL */
10334 /* ============ ??? */
10337 * Set the shell parameters.
10340 setparam(char **argv)
10346 for (nparam = 0; argv[nparam]; nparam++)
10348 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10350 *ap++ = ckstrdup(*argv++);
10353 freeparam(&shellparam);
10354 shellparam.malloced = 1;
10355 shellparam.nparam = nparam;
10356 shellparam.p = newparam;
10357 #if ENABLE_ASH_GETOPTS
10358 shellparam.optind = 1;
10359 shellparam.optoff = -1;
10364 * Process shell options. The global variable argptr contains a pointer
10365 * to the argument list; we advance it past the options.
10367 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10368 * For a non-interactive shell, an error condition encountered
10369 * by a special built-in ... shall cause the shell to write a diagnostic message
10370 * to standard error and exit as shown in the following table:
10371 * Error Special Built-In
10373 * Utility syntax error (option or operand error) Shall exit
10375 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10376 * we see that bash does not do that (set "finishes" with error code 1 instead,
10377 * and shell continues), and people rely on this behavior!
10379 * set -o barfoo 2>/dev/null
10382 * Oh well. Let's mimic that.
10385 plus_minus_o(char *name, int val)
10390 for (i = 0; i < NOPTS; i++) {
10391 if (strcmp(name, optnames(i)) == 0) {
10396 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10399 for (i = 0; i < NOPTS; i++) {
10401 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10403 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10409 setoption(int flag, int val)
10413 for (i = 0; i < NOPTS; i++) {
10414 if (optletters(i) == flag) {
10419 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10423 options(int cmdline)
10431 while ((p = *argptr) != NULL) {
10433 if (c != '-' && c != '+')
10436 val = 0; /* val = 0 if c == '+' */
10439 if (p[0] == '\0' || LONE_DASH(p)) {
10441 /* "-" means turn off -x and -v */
10444 /* "--" means reset params */
10445 else if (*argptr == NULL)
10448 break; /* "-" or "--" terminates options */
10451 /* first char was + or - */
10452 while ((c = *p++) != '\0') {
10453 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10454 if (c == 'c' && cmdline) {
10455 minusc = p; /* command is after shell args */
10456 } else if (c == 'o') {
10457 if (plus_minus_o(*argptr, val)) {
10458 /* it already printed err message */
10459 return 1; /* error */
10463 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10465 /* bash does not accept +-login, we also won't */
10466 } else if (cmdline && val && (c == '-')) { /* long options */
10467 if (strcmp(p, "login") == 0)
10479 * The shift builtin command.
10481 static int FAST_FUNC
10482 shiftcmd(int argc UNUSED_PARAM, char **argv)
10489 n = number(argv[1]);
10490 if (n > shellparam.nparam)
10491 n = 0; /* bash compat, was = shellparam.nparam; */
10493 shellparam.nparam -= n;
10494 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10495 if (shellparam.malloced)
10498 ap2 = shellparam.p;
10499 while ((*ap2++ = *ap1++) != NULL)
10501 #if ENABLE_ASH_GETOPTS
10502 shellparam.optind = 1;
10503 shellparam.optoff = -1;
10510 * POSIX requires that 'set' (but not export or readonly) output the
10511 * variables in lexicographic order - by the locale's collating order (sigh).
10512 * Maybe we could keep them in an ordered balanced binary tree
10513 * instead of hashed lists.
10514 * For now just roll 'em through qsort for printing...
10517 showvars(const char *sep_prefix, int on, int off)
10520 char **ep, **epend;
10522 ep = listvars(on, off, &epend);
10523 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10525 sep = *sep_prefix ? " " : sep_prefix;
10527 for (; ep < epend; ep++) {
10531 p = strchrnul(*ep, '=');
10534 q = single_quote(++p);
10535 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10541 * The set command builtin.
10543 static int FAST_FUNC
10544 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10549 return showvars(nullstr, 0, VUNSET);
10552 retval = options(/*cmdline:*/ 0);
10553 if (retval == 0) { /* if no parse error... */
10555 if (*argptr != NULL) {
10563 #if ENABLE_ASH_RANDOM_SUPPORT
10564 static void FAST_FUNC
10565 change_random(const char *value)
10569 if (value == NULL) {
10570 /* "get", generate */
10571 t = next_random(&random_gen);
10572 /* set without recursion */
10573 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10574 vrandom.flags &= ~VNOFUNC;
10577 t = strtoul(value, NULL, 10);
10578 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10583 #if ENABLE_ASH_GETOPTS
10585 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10596 if (*param_optind < 1)
10598 optnext = optfirst + *param_optind - 1;
10600 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10603 p = optnext[-1] + *optoff;
10604 if (p == NULL || *p == '\0') {
10605 /* Current word is done, advance */
10607 if (p == NULL || *p != '-' || *++p == '\0') {
10614 if (LONE_DASH(p)) /* check for "--" */
10619 for (q = optstr; *q != c;) {
10621 if (optstr[0] == ':') {
10623 /*sbuf[1] = '\0'; - already is */
10624 err |= setvarsafe("OPTARG", sbuf, 0);
10626 fprintf(stderr, "Illegal option -%c\n", c);
10627 unsetvar("OPTARG");
10637 if (*p == '\0' && (p = *optnext) == NULL) {
10638 if (optstr[0] == ':') {
10640 /*sbuf[1] = '\0'; - already is */
10641 err |= setvarsafe("OPTARG", sbuf, 0);
10644 fprintf(stderr, "No arg for -%c option\n", c);
10645 unsetvar("OPTARG");
10653 err |= setvarsafe("OPTARG", p, 0);
10656 err |= setvarsafe("OPTARG", nullstr, 0);
10658 *optoff = p ? p - *(optnext - 1) : -1;
10659 *param_optind = optnext - optfirst + 1;
10660 err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
10662 /*sbuf[1] = '\0'; - already is */
10663 err |= setvarsafe(optvar, sbuf, 0);
10667 flush_stdout_stderr();
10668 raise_exception(EXERROR);
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 (shellparam.optind > shellparam.nparam + 1) {
10689 shellparam.optind = 1;
10690 shellparam.optoff = -1;
10693 optbase = &argv[3];
10694 if (shellparam.optind > argc - 2) {
10695 shellparam.optind = 1;
10696 shellparam.optoff = -1;
10700 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10701 &shellparam.optoff);
10703 #endif /* ASH_GETOPTS */
10706 /* ============ Shell parser */
10709 struct heredoc *next; /* next here document in list */
10710 union node *here; /* redirection node */
10711 char *eofmark; /* string indicating end of input */
10712 smallint striptabs; /* if set, strip leading tabs */
10715 static smallint tokpushback; /* last token pushed back */
10716 static smallint quoteflag; /* set if (part of) last token was quoted */
10717 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10718 static struct heredoc *heredoclist; /* list of here documents to read */
10719 static char *wordtext; /* text of last word returned by readtoken */
10720 static struct nodelist *backquotelist;
10721 static union node *redirnode;
10722 static struct heredoc *heredoc;
10724 static const char *
10725 tokname(char *buf, int tok)
10728 return tokname_array[tok];
10729 sprintf(buf, "\"%s\"", tokname_array[tok]);
10733 /* raise_error_unexpected_syntax:
10734 * Called when an unexpected token is read during the parse. The argument
10735 * is the token that is expected, or -1 if more than one type of token can
10736 * occur at this point.
10738 static void raise_error_unexpected_syntax(int) NORETURN;
10740 raise_error_unexpected_syntax(int token)
10746 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10748 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10749 raise_error_syntax(msg);
10753 #define EOFMARKLEN 79
10755 /* parsing is heavily cross-recursive, need these forward decls */
10756 static union node *andor(void);
10757 static union node *pipeline(void);
10758 static union node *parse_command(void);
10759 static void parseheredoc(void);
10760 static int peektoken(void);
10761 static int readtoken(void);
10763 static union node *
10766 union node *n1, *n2, *n3;
10771 switch (peektoken()) {
10779 if (!n1 && (nlflag & 1))
10785 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10786 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10792 if (tok == TBACKGND) {
10793 if (n2->type == NPIPE) {
10794 n2->npipe.pipe_backgnd = 1;
10796 if (n2->type != NREDIR) {
10797 n3 = stzalloc(sizeof(struct nredir));
10799 /*n3->nredir.redirect = NULL; - stzalloc did it */
10802 n2->type = NBACKGND;
10808 n3 = stzalloc(sizeof(struct nbinary));
10810 n3->nbinary.ch1 = n1;
10811 n3->nbinary.ch2 = n2;
10824 raise_error_unexpected_syntax(-1);
10831 static union node *
10834 union node *n1, *n2, *n3;
10842 } else if (t == TOR) {
10848 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10850 n3 = stzalloc(sizeof(struct nbinary));
10852 n3->nbinary.ch1 = n1;
10853 n3->nbinary.ch2 = n2;
10858 static union node *
10861 union node *n1, *n2, *pipenode;
10862 struct nodelist *lp, *prev;
10866 TRACE(("pipeline: entered\n"));
10867 if (readtoken() == TNOT) {
10869 checkkwd = CHKKWD | CHKALIAS;
10872 n1 = parse_command();
10873 if (readtoken() == TPIPE) {
10874 pipenode = stzalloc(sizeof(struct npipe));
10875 pipenode->type = NPIPE;
10876 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10877 lp = stzalloc(sizeof(struct nodelist));
10878 pipenode->npipe.cmdlist = lp;
10882 lp = stzalloc(sizeof(struct nodelist));
10883 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10884 lp->n = parse_command();
10886 } while (readtoken() == TPIPE);
10892 n2 = stzalloc(sizeof(struct nnot));
10900 static union node *
10905 n = stzalloc(sizeof(struct narg));
10907 /*n->narg.next = NULL; - stzalloc did it */
10908 n->narg.text = wordtext;
10909 n->narg.backquote = backquotelist;
10914 fixredir(union node *n, const char *text, int err)
10918 TRACE(("Fix redir %s %d\n", text, err));
10920 n->ndup.vname = NULL;
10922 fd = bb_strtou(text, NULL, 10);
10923 if (!errno && fd >= 0)
10924 n->ndup.dupfd = fd;
10925 else if (LONE_DASH(text))
10926 n->ndup.dupfd = -1;
10929 raise_error_syntax("bad fd number");
10930 n->ndup.vname = makename();
10935 * Returns true if the text contains nothing to expand (no dollar signs
10939 noexpand(const char *text)
10943 while ((c = *text++) != '\0') {
10944 if (c == CTLQUOTEMARK)
10948 else if (SIT(c, BASESYNTAX) == CCTL)
10957 union node *n = redirnode;
10959 if (readtoken() != TWORD)
10960 raise_error_unexpected_syntax(-1);
10961 if (n->type == NHERE) {
10962 struct heredoc *here = heredoc;
10966 if (quoteflag == 0)
10968 TRACE(("Here document %d\n", n->type));
10969 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10970 raise_error_syntax("illegal eof marker for << redirection");
10971 rmescapes(wordtext, 0);
10972 here->eofmark = wordtext;
10974 if (heredoclist == NULL)
10975 heredoclist = here;
10977 for (p = heredoclist; p->next; p = p->next)
10981 } else if (n->type == NTOFD || n->type == NFROMFD) {
10982 fixredir(n, wordtext, 0);
10984 n->nfile.fname = makename();
10988 static union node *
10991 union node *args, **app;
10992 union node *n = NULL;
10993 union node *vars, **vpp;
10994 union node **rpp, *redir;
10996 #if ENABLE_ASH_BASH_COMPAT
10997 smallint double_brackets_flag = 0;
10998 smallint function_flag = 0;
11008 savecheckkwd = CHKALIAS;
11011 checkkwd = savecheckkwd;
11014 #if ENABLE_ASH_BASH_COMPAT
11016 if (peektoken() != TWORD)
11017 raise_error_unexpected_syntax(TWORD);
11020 case TAND: /* "&&" */
11021 case TOR: /* "||" */
11022 if (!double_brackets_flag) {
11026 wordtext = (char *) (t == TAND ? "-a" : "-o");
11029 n = stzalloc(sizeof(struct narg));
11031 /*n->narg.next = NULL; - stzalloc did it */
11032 n->narg.text = wordtext;
11033 #if ENABLE_ASH_BASH_COMPAT
11034 if (strcmp("[[", wordtext) == 0)
11035 double_brackets_flag = 1;
11036 else if (strcmp("]]", wordtext) == 0)
11037 double_brackets_flag = 0;
11039 n->narg.backquote = backquotelist;
11040 if (savecheckkwd && isassignment(wordtext)) {
11042 vpp = &n->narg.next;
11045 app = &n->narg.next;
11048 #if ENABLE_ASH_BASH_COMPAT
11049 if (function_flag) {
11050 checkkwd = CHKNL | CHKKWD;
11051 switch (peektoken()) {
11063 if (strcmp("[[", wordtext) == 0)
11067 raise_error_unexpected_syntax(-1);
11073 *rpp = n = redirnode;
11074 rpp = &n->nfile.next;
11075 parsefname(); /* read name of redirection file */
11078 IF_ASH_BASH_COMPAT(do_func:)
11079 if (args && app == &args->narg.next
11082 struct builtincmd *bcmd;
11085 /* We have a function */
11086 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11087 raise_error_unexpected_syntax(TRP);
11088 name = n->narg.text;
11089 if (!goodname(name)
11090 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11092 raise_error_syntax("bad function name");
11095 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11096 n->narg.next = parse_command();
11099 IF_ASH_BASH_COMPAT(function_flag = 0;)
11110 n = stzalloc(sizeof(struct ncmd));
11112 n->ncmd.args = args;
11113 n->ncmd.assign = vars;
11114 n->ncmd.redirect = redir;
11118 static union node *
11119 parse_command(void)
11121 union node *n1, *n2;
11122 union node *ap, **app;
11123 union node *cp, **cpp;
11124 union node *redir, **rpp;
11131 switch (readtoken()) {
11133 raise_error_unexpected_syntax(-1);
11136 n1 = stzalloc(sizeof(struct nif));
11138 n1->nif.test = list(0);
11139 if (readtoken() != TTHEN)
11140 raise_error_unexpected_syntax(TTHEN);
11141 n1->nif.ifpart = list(0);
11143 while (readtoken() == TELIF) {
11144 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11145 n2 = n2->nif.elsepart;
11147 n2->nif.test = list(0);
11148 if (readtoken() != TTHEN)
11149 raise_error_unexpected_syntax(TTHEN);
11150 n2->nif.ifpart = list(0);
11152 if (lasttoken == TELSE)
11153 n2->nif.elsepart = list(0);
11155 n2->nif.elsepart = NULL;
11163 n1 = stzalloc(sizeof(struct nbinary));
11164 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11165 n1->nbinary.ch1 = list(0);
11168 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11169 got == TWORD ? wordtext : ""));
11170 raise_error_unexpected_syntax(TDO);
11172 n1->nbinary.ch2 = list(0);
11177 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11178 raise_error_syntax("bad for loop variable");
11179 n1 = stzalloc(sizeof(struct nfor));
11181 n1->nfor.var = wordtext;
11182 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11183 if (readtoken() == TIN) {
11185 while (readtoken() == TWORD) {
11186 n2 = stzalloc(sizeof(struct narg));
11188 /*n2->narg.next = NULL; - stzalloc did it */
11189 n2->narg.text = wordtext;
11190 n2->narg.backquote = backquotelist;
11192 app = &n2->narg.next;
11195 n1->nfor.args = ap;
11196 if (lasttoken != TNL && lasttoken != TSEMI)
11197 raise_error_unexpected_syntax(-1);
11199 n2 = stzalloc(sizeof(struct narg));
11201 /*n2->narg.next = NULL; - stzalloc did it */
11202 n2->narg.text = (char *)dolatstr;
11203 /*n2->narg.backquote = NULL;*/
11204 n1->nfor.args = n2;
11206 * Newline or semicolon here is optional (but note
11207 * that the original Bourne shell only allowed NL).
11209 if (lasttoken != TSEMI)
11212 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11213 if (readtoken() != TDO)
11214 raise_error_unexpected_syntax(TDO);
11215 n1->nfor.body = list(0);
11219 n1 = stzalloc(sizeof(struct ncase));
11221 if (readtoken() != TWORD)
11222 raise_error_unexpected_syntax(TWORD);
11223 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11225 /*n2->narg.next = NULL; - stzalloc did it */
11226 n2->narg.text = wordtext;
11227 n2->narg.backquote = backquotelist;
11228 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11229 if (readtoken() != TIN)
11230 raise_error_unexpected_syntax(TIN);
11231 cpp = &n1->ncase.cases;
11233 checkkwd = CHKNL | CHKKWD;
11235 while (t != TESAC) {
11236 if (lasttoken == TLP)
11238 *cpp = cp = stzalloc(sizeof(struct nclist));
11240 app = &cp->nclist.pattern;
11242 *app = ap = stzalloc(sizeof(struct narg));
11244 /*ap->narg.next = NULL; - stzalloc did it */
11245 ap->narg.text = wordtext;
11246 ap->narg.backquote = backquotelist;
11247 if (readtoken() != TPIPE)
11249 app = &ap->narg.next;
11252 //ap->narg.next = NULL;
11253 if (lasttoken != TRP)
11254 raise_error_unexpected_syntax(TRP);
11255 cp->nclist.body = list(2);
11257 cpp = &cp->nclist.next;
11259 checkkwd = CHKNL | CHKKWD;
11263 raise_error_unexpected_syntax(TENDCASE);
11270 n1 = stzalloc(sizeof(struct nredir));
11271 n1->type = NSUBSHELL;
11272 n1->nredir.n = list(0);
11273 /*n1->nredir.redirect = NULL; - stzalloc did it */
11280 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11284 return simplecmd();
11287 if (readtoken() != t)
11288 raise_error_unexpected_syntax(t);
11291 /* Now check for redirection which may follow command */
11292 checkkwd = CHKKWD | CHKALIAS;
11294 while (readtoken() == TREDIR) {
11295 *rpp = n2 = redirnode;
11296 rpp = &n2->nfile.next;
11302 if (n1->type != NSUBSHELL) {
11303 n2 = stzalloc(sizeof(struct nredir));
11308 n1->nredir.redirect = redir;
11313 #if ENABLE_ASH_BASH_COMPAT
11315 decode_dollar_squote(void)
11317 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11323 p = strchr(C_escapes, c);
11328 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11332 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11334 } else if (c == 'x') { /* \xHH */
11338 } while (isxdigit(c) && --cnt);
11340 if (cnt == 3) { /* \x but next char is "bad" */
11344 } else { /* simple seq like \\ or \t */
11349 c = bb_process_escape_sequence((void*)&p);
11350 } else { /* unrecognized "\z": print both chars unless ' or " */
11351 if (c != '\'' && c != '"') {
11353 c |= 0x100; /* "please encode \, then me" */
11361 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11362 * is not NULL, read a here document. In the latter case, eofmark is the
11363 * word which marks the end of the document and striptabs is true if
11364 * leading tabs should be stripped from the document. The argument c
11365 * is the first character of the input token or document.
11367 * Because C does not have internal subroutines, I have simulated them
11368 * using goto's to implement the subroutine linkage. The following macros
11369 * will run code that appears at the end of readtoken1.
11371 #define CHECKEND() {goto checkend; checkend_return:;}
11372 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11373 #define PARSESUB() {goto parsesub; parsesub_return:;}
11374 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11375 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11376 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11378 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11380 /* NB: syntax parameter fits into smallint */
11381 /* c parameter is an unsigned char or PEOF or PEOA */
11384 char line[EOFMARKLEN + 1];
11385 struct nodelist *bqlist;
11389 smallint prevsyntax; /* syntax before arithmetic */
11390 #if ENABLE_ASH_EXPAND_PRMT
11391 smallint pssyntax; /* we are expanding a prompt string */
11393 int varnest; /* levels of variables expansion */
11394 int arinest; /* levels of arithmetic expansion */
11395 int parenlevel; /* levels of parens in arithmetic */
11396 int dqvarnest; /* levels of variables expansion within double quotes */
11398 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11400 startlinno = g_parsefile->linno;
11404 #if ENABLE_ASH_EXPAND_PRMT
11405 pssyntax = (syntax == PSSYNTAX);
11409 dblquote = (syntax == DQSYNTAX);
11415 STARTSTACKSTR(out);
11417 /* For each line, until end of word */
11418 CHECKEND(); /* set c to PEOF if at end of here document */
11419 for (;;) { /* until end of line or end of word */
11420 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11421 switch (SIT(c, syntax)) {
11422 case CNL: /* '\n' */
11423 if (syntax == BASESYNTAX)
11424 goto endword; /* exit outer loop */
11428 goto loop; /* continue outer loop */
11433 #if ENABLE_ASH_BASH_COMPAT
11434 if (c == '\\' && bash_dollar_squote) {
11435 c = decode_dollar_squote();
11437 /* skip $'\000', $'\x00' (like bash) */
11441 /* Unknown escape. Encode as '\z' */
11442 c = (unsigned char)c;
11443 if (eofmark == NULL || dblquote)
11444 USTPUTC(CTLESC, out);
11445 USTPUTC('\\', out);
11449 if (eofmark == NULL || dblquote)
11450 USTPUTC(CTLESC, out);
11453 case CBACK: /* backslash */
11454 c = pgetc_without_PEOA();
11456 USTPUTC(CTLESC, out);
11457 USTPUTC('\\', out);
11459 } else if (c == '\n') {
11462 #if ENABLE_ASH_EXPAND_PRMT
11463 if (c == '$' && pssyntax) {
11464 USTPUTC(CTLESC, out);
11465 USTPUTC('\\', out);
11468 /* Backslash is retained if we are in "str" and next char isn't special */
11473 && (c != '"' || eofmark != NULL)
11475 USTPUTC('\\', out);
11477 USTPUTC(CTLESC, out);
11485 if (eofmark == NULL) {
11486 USTPUTC(CTLQUOTEMARK, out);
11494 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11495 if (eofmark != NULL && varnest == 0) {
11498 if (dqvarnest == 0) {
11499 syntax = BASESYNTAX;
11506 case CVAR: /* '$' */
11507 PARSESUB(); /* parse substitution */
11509 case CENDVAR: /* '}' */
11512 if (dqvarnest > 0) {
11519 #if ENABLE_SH_MATH_SUPPORT
11520 case CLP: /* '(' in arithmetic */
11524 case CRP: /* ')' in arithmetic */
11525 if (parenlevel > 0) {
11528 if (pgetc_eatbnl() == ')') {
11530 if (--arinest == 0) {
11531 syntax = prevsyntax;
11535 * unbalanced parens
11536 * (don't 2nd guess - no error)
11544 case CBQUOTE: /* '`' */
11548 goto endword; /* exit outer loop */
11552 if (varnest == 0) {
11553 #if ENABLE_ASH_BASH_COMPAT
11555 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11556 if (pgetc() == '>')
11557 c = 0x100 + '>'; /* flag &> */
11561 goto endword; /* exit outer loop */
11563 IF_ASH_ALIAS(if (c != PEOA))
11570 #if ENABLE_SH_MATH_SUPPORT
11571 if (syntax == ARISYNTAX)
11572 raise_error_syntax("missing '))'");
11574 if (syntax != BASESYNTAX && eofmark == NULL)
11575 raise_error_syntax("unterminated quoted string");
11576 if (varnest != 0) {
11577 startlinno = g_parsefile->linno;
11579 raise_error_syntax("missing '}'");
11581 USTPUTC('\0', out);
11582 len = out - (char *)stackblock();
11583 out = stackblock();
11584 if (eofmark == NULL) {
11585 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11588 if (isdigit_str9(out)) {
11589 PARSEREDIR(); /* passed as params: out, c */
11590 lasttoken = TREDIR;
11593 /* else: non-number X seen, interpret it
11594 * as "NNNX>file" = "NNNX >file" */
11598 quoteflag = quotef;
11599 backquotelist = bqlist;
11600 grabstackblock(len);
11604 /* end of readtoken routine */
11607 * Check to see whether we are at the end of the here document. When this
11608 * is called, c is set to the first character of the next input line. If
11609 * we are at the end of the here document, this routine sets the c to PEOF.
11613 #if ENABLE_ASH_ALIAS
11615 c = pgetc_without_PEOA();
11618 while (c == '\t') {
11619 c = pgetc_without_PEOA();
11622 if (c == *eofmark) {
11623 if (pfgets(line, sizeof(line)) != NULL) {
11627 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11629 if (*p == '\n' && *q == '\0') {
11633 pushstring(line, NULL);
11638 goto checkend_return;
11642 * Parse a redirection operator. The variable "out" points to a string
11643 * specifying the fd to be redirected. The variable "c" contains the
11644 * first character of the redirection operator.
11647 /* out is already checked to be a valid number or "" */
11648 int fd = (*out == '\0' ? -1 : atoi(out));
11651 np = stzalloc(sizeof(struct nfile));
11656 np->type = NAPPEND;
11658 np->type = NCLOBBER;
11661 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11667 #if ENABLE_ASH_BASH_COMPAT
11668 else if (c == 0x100 + '>') { /* this flags &> redirection */
11670 pgetc(); /* this is '>', no need to check */
11674 else { /* c == '<' */
11675 /*np->nfile.fd = 0; - stzalloc did it */
11679 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11680 np = stzalloc(sizeof(struct nhere));
11681 /*np->nfile.fd = 0; - stzalloc did it */
11684 heredoc = stzalloc(sizeof(struct heredoc));
11685 heredoc->here = np;
11688 heredoc->striptabs = 1;
11690 /*heredoc->striptabs = 0; - stzalloc did it */
11696 np->type = NFROMFD;
11700 np->type = NFROMTO;
11712 goto parseredir_return;
11716 * Parse a substitution. At this point, we have read the dollar sign
11717 * and nothing else.
11720 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11721 * (assuming ascii char codes, as the original implementation did) */
11722 #define is_special(c) \
11723 (((unsigned)(c) - 33 < 32) \
11724 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11726 unsigned char subtype;
11730 c = pgetc_eatbnl();
11731 if (c > 255 /* PEOA or PEOF */
11732 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11734 #if ENABLE_ASH_BASH_COMPAT
11735 if (syntax != DQSYNTAX && c == '\'')
11736 bash_dollar_squote = 1;
11741 } else if (c == '(') {
11742 /* $(command) or $((arith)) */
11743 if (pgetc_eatbnl() == '(') {
11744 #if ENABLE_SH_MATH_SUPPORT
11747 raise_error_syntax("you disabled math support for $((arith)) syntax");
11754 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11755 USTPUTC(CTLVAR, out);
11756 typeloc = out - (char *)stackblock();
11757 USTPUTC(VSNORMAL, out);
11758 subtype = VSNORMAL;
11760 c = pgetc_eatbnl();
11762 c = pgetc_eatbnl();
11764 c = '#'; /* ${#} - same as $# */
11766 subtype = VSLENGTH; /* ${#VAR} */
11771 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11772 /* $[{[#]]NAME[}] */
11775 c = pgetc_eatbnl();
11776 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11777 } else if (isdigit(c)) {
11778 /* $[{[#]]NUM[}] */
11781 c = pgetc_eatbnl();
11782 } while (isdigit(c));
11783 } else if (is_special(c)) {
11784 /* $[{[#]]<specialchar>[}] */
11786 c = pgetc_eatbnl();
11789 raise_error_syntax("bad substitution");
11791 if (c != '}' && subtype == VSLENGTH) {
11792 /* ${#VAR didn't end with } */
11798 if (subtype == 0) {
11799 static const char types[] ALIGN1 = "}-+?=";
11800 /* ${VAR...} but not $VAR or ${#VAR} */
11801 /* c == first char after VAR */
11804 c = pgetc_eatbnl();
11805 #if ENABLE_ASH_BASH_COMPAT
11806 /* This check is only needed to not misinterpret
11807 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11810 if (!strchr(types, c)) {
11811 subtype = VSSUBSTR;
11813 break; /* "goto do_pungetc" is bigger (!) */
11819 const char *p = strchr(types, c);
11822 subtype = p - types + VSNORMAL;
11828 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11829 c = pgetc_eatbnl();
11835 #if ENABLE_ASH_BASH_COMPAT
11837 /* ${v/[/]pattern/repl} */
11838 //TODO: encode pattern and repl separately.
11839 // Currently ${v/$var_with_slash/repl} is horribly broken
11840 subtype = VSREPLACE;
11841 c = pgetc_eatbnl();
11844 subtype++; /* VSREPLACEALL */
11852 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11853 if (subtype != VSNORMAL) {
11860 goto parsesub_return;
11864 * Called to parse command substitutions. Newstyle is set if the command
11865 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11866 * list of commands (passed by reference), and savelen is the number of
11867 * characters on the top of the stack which must be preserved.
11870 struct nodelist **nlpp;
11874 smallint saveprompt = 0;
11877 savelen = out - (char *)stackblock();
11880 * FIXME: this can allocate very large block on stack and SEGV.
11882 * echo "..<100kbytes>..`true` $(true) `true` ..."
11883 * allocates 100kb for every command subst. With about
11884 * a hundred command substitutions stack overflows.
11885 * With larger prepended string, SEGV happens sooner.
11887 str = alloca(savelen);
11888 memcpy(str, stackblock(), savelen);
11892 /* We must read until the closing backquote, giving special
11893 * treatment to some slashes, and then push the string and
11894 * reread it as input, interpreting it normally.
11900 STARTSTACKSTR(pout);
11904 setprompt_if(needprompt, 2);
11915 * If eating a newline, avoid putting
11916 * the newline into the new character
11917 * stream (via the STPUTC after the
11922 if (pc != '\\' && pc != '`' && pc != '$'
11923 && (!dblquote || pc != '"')
11925 STPUTC('\\', pout);
11927 if (pc <= 255 /* not PEOA or PEOF */) {
11933 IF_ASH_ALIAS(case PEOA:)
11934 startlinno = g_parsefile->linno;
11935 raise_error_syntax("EOF in backquote substitution");
11947 STPUTC('\0', pout);
11948 psavelen = pout - (char *)stackblock();
11949 if (psavelen > 0) {
11950 pstr = grabstackstr(pout);
11951 setinputstring(pstr);
11956 nlpp = &(*nlpp)->next;
11957 *nlpp = stzalloc(sizeof(**nlpp));
11958 /* (*nlpp)->next = NULL; - stzalloc did it */
11961 saveprompt = doprompt;
11968 doprompt = saveprompt;
11969 else if (readtoken() != TRP)
11970 raise_error_unexpected_syntax(TRP);
11975 * Start reading from old file again, ignoring any pushed back
11976 * tokens left from the backquote parsing
11981 while (stackblocksize() <= savelen)
11983 STARTSTACKSTR(out);
11985 memcpy(out, str, savelen);
11986 STADJUST(savelen, out);
11988 USTPUTC(CTLBACKQ, out);
11990 goto parsebackq_oldreturn;
11991 goto parsebackq_newreturn;
11994 #if ENABLE_SH_MATH_SUPPORT
11996 * Parse an arithmetic expansion (indicate start of one and set state)
11999 if (++arinest == 1) {
12000 prevsyntax = syntax;
12001 syntax = ARISYNTAX;
12003 USTPUTC(CTLARI, out);
12004 goto parsearith_return;
12007 } /* end of readtoken */
12010 * Read the next input token.
12011 * If the token is a word, we set backquotelist to the list of cmds in
12012 * backquotes. We set quoteflag to true if any part of the word was
12014 * If the token is TREDIR, then we set redirnode to a structure containing
12016 * In all cases, the variable startlinno is set to the number of the line
12017 * on which the token starts.
12019 * [Change comment: here documents and internal procedures]
12020 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12021 * word parsing code into a separate routine. In this case, readtoken
12022 * doesn't need to have any internal procedures, but parseword does.
12023 * We could also make parseoperator in essence the main routine, and
12024 * have parseword (readtoken1?) handle both words and redirection.]
12026 #define NEW_xxreadtoken
12027 #ifdef NEW_xxreadtoken
12028 /* singles must be first! */
12029 static const char xxreadtoken_chars[7] ALIGN1 = {
12030 '\n', '(', ')', /* singles */
12031 '&', '|', ';', /* doubles */
12035 #define xxreadtoken_singles 3
12036 #define xxreadtoken_doubles 3
12038 static const char xxreadtoken_tokens[] ALIGN1 = {
12039 TNL, TLP, TRP, /* only single occurrence allowed */
12040 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12041 TEOF, /* corresponds to trailing nul */
12042 TAND, TOR, TENDCASE /* if double occurrence */
12054 setprompt_if(needprompt, 2);
12055 startlinno = g_parsefile->linno;
12056 for (;;) { /* until token or start of word found */
12058 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12062 while ((c = pgetc()) != '\n' && c != PEOF)
12065 } else if (c == '\\') {
12066 if (pgetc() != '\n') {
12068 break; /* return readtoken1(...) */
12074 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12080 p = strchr(xxreadtoken_chars, c);
12082 break; /* return readtoken1(...) */
12084 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12086 if (cc == c) { /* double occurrence? */
12087 p += xxreadtoken_doubles + 1;
12090 #if ENABLE_ASH_BASH_COMPAT
12091 if (c == '&' && cc == '>') /* &> */
12092 break; /* return readtoken1(...) */
12097 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12102 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12104 #else /* old xxreadtoken */
12105 #define RETURN(token) return lasttoken = token
12115 setprompt_if(needprompt, 2);
12116 startlinno = g_parsefile->linno;
12117 for (;;) { /* until token or start of word found */
12120 case ' ': case '\t':
12121 IF_ASH_ALIAS(case PEOA:)
12124 while ((c = pgetc()) != '\n' && c != PEOF)
12129 if (pgetc() == '\n') {
12141 if (pgetc() == '&')
12146 if (pgetc() == '|')
12151 if (pgetc() == ';')
12164 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12167 #endif /* old xxreadtoken */
12173 int kwd = checkkwd;
12175 smallint alreadyseen = tokpushback;
12178 #if ENABLE_ASH_ALIAS
12194 if (t != TWORD || quoteflag) {
12199 * check for keywords
12201 if (kwd & CHKKWD) {
12202 const char *const *pp;
12204 pp = findkwd(wordtext);
12206 lasttoken = t = pp - tokname_array;
12207 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12212 if (checkkwd & CHKALIAS) {
12213 #if ENABLE_ASH_ALIAS
12215 ap = lookupalias(wordtext, 1);
12218 pushstring(ap->val, ap);
12228 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12230 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12246 * Read and parse a command. Returns NODE_EOF on end of file.
12247 * (NULL is a valid parse tree indicating a blank line.)
12249 static union node *
12250 parsecmd(int interact)
12255 doprompt = interact;
12256 setprompt_if(doprompt, doprompt);
12262 * Input any here documents.
12267 struct heredoc *here;
12270 here = heredoclist;
12271 heredoclist = NULL;
12274 setprompt_if(needprompt, 2);
12275 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12276 here->eofmark, here->striptabs);
12277 n = stzalloc(sizeof(struct narg));
12278 n->narg.type = NARG;
12279 /*n->narg.next = NULL; - stzalloc did it */
12280 n->narg.text = wordtext;
12281 n->narg.backquote = backquotelist;
12282 here->here->nhere.doc = n;
12289 * called by editline -- any expansions to the prompt should be added here.
12291 #if ENABLE_ASH_EXPAND_PRMT
12292 static const char *
12293 expandstr(const char *ps)
12297 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12298 * and token processing _can_ alter it (delete NULs etc). */
12299 setinputstring((char *)ps);
12300 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12303 n.narg.type = NARG;
12304 n.narg.next = NULL;
12305 n.narg.text = wordtext;
12306 n.narg.backquote = backquotelist;
12308 expandarg(&n, NULL, EXP_QUOTED);
12309 return stackblock();
12314 * Execute a command or commands contained in a string.
12317 evalstring(char *s, int flags)
12320 struct stackmark smark;
12325 setstackmark(&smark);
12328 while ((n = parsecmd(0)) != NODE_EOF) {
12331 i = evaltree(n, flags);
12334 popstackmark(&smark);
12338 popstackmark(&smark);
12346 * The eval command.
12348 static int FAST_FUNC
12349 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12358 STARTSTACKSTR(concat);
12360 concat = stack_putstr(p, concat);
12364 STPUTC(' ', concat);
12366 STPUTC('\0', concat);
12367 p = grabstackstr(concat);
12369 return evalstring(p, flags & EV_TESTED);
12375 * Read and execute commands.
12376 * "Top" is nonzero for the top level command loop;
12377 * it turns on prompting if the shell is interactive.
12383 struct stackmark smark;
12388 TRACE(("cmdloop(%d) called\n", top));
12392 setstackmark(&smark);
12395 showjobs(SHOW_CHANGED|SHOW_STDERR);
12398 if (iflag && top) {
12402 n = parsecmd(inter);
12404 if (DEBUG > 2 && debug && (n != NODE_EOF))
12407 if (n == NODE_EOF) {
12408 if (!top || numeof >= 50)
12410 if (!stoppedjobs()) {
12413 out2str("\nUse \"exit\" to leave shell.\n");
12416 } else if (nflag == 0) {
12419 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12422 i = evaltree(n, 0);
12426 popstackmark(&smark);
12430 evalskip &= ~SKIPFUNC;
12438 * Take commands from a file. To be compatible we should do a path
12439 * search for the file, which is necessary to find sub-commands.
12442 find_dot_file(char *name)
12445 const char *path = pathval();
12448 /* don't try this for absolute or relative paths */
12449 if (strchr(name, '/'))
12452 /* IIRC standards do not say whether . is to be searched.
12453 * And it is even smaller this way, making it unconditional for now:
12455 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12460 while ((fullname = path_advance(&path, name)) != NULL) {
12462 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12464 * Don't bother freeing here, since it will
12465 * be freed by the caller.
12469 if (fullname != name)
12470 stunalloc(fullname);
12473 /* not found in the PATH */
12474 ash_msg_and_raise_error("%s: not found", name);
12478 static int FAST_FUNC
12479 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12481 /* "false; . empty_file; echo $?" should print 0, not 1: */
12485 struct strlist *sp;
12486 volatile struct shparam saveparam;
12488 for (sp = cmdenviron; sp; sp = sp->next)
12489 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12491 nextopt(nullstr); /* handle possible "--" */
12495 /* bash says: "bash: .: filename argument required" */
12496 return 2; /* bash compat */
12499 /* This aborts if file isn't found, which is POSIXly correct.
12500 * bash returns exitcode 1 instead.
12502 fullname = find_dot_file(argv[0]);
12504 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12506 saveparam = shellparam;
12507 shellparam.malloced = 0;
12511 shellparam.nparam = argc;
12512 shellparam.p = argv;
12515 /* This aborts if file can't be opened, which is POSIXly correct.
12516 * bash returns exitcode 1 instead.
12518 setinputfile(fullname, INPUT_PUSH_FILE);
12519 commandname = fullname;
12520 status = cmdloop(0);
12524 freeparam(&shellparam);
12525 shellparam = saveparam;
12531 static int FAST_FUNC
12532 exitcmd(int argc UNUSED_PARAM, char **argv)
12537 exitstatus = number(argv[1]);
12538 raise_exception(EXEXIT);
12543 * Read a file containing shell functions.
12546 readcmdfile(char *name)
12548 setinputfile(name, INPUT_PUSH_FILE);
12554 /* ============ find_command inplementation */
12557 * Resolve a command name. If you change this routine, you may have to
12558 * change the shellexec routine as well.
12561 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12563 struct tblentry *cmdp;
12570 struct builtincmd *bcmd;
12572 /* If name contains a slash, don't use PATH or hash table */
12573 if (strchr(name, '/') != NULL) {
12574 entry->u.index = -1;
12575 if (act & DO_ABS) {
12576 while (stat(name, &statb) < 0) {
12578 if (errno == EINTR)
12581 entry->cmdtype = CMDUNKNOWN;
12585 entry->cmdtype = CMDNORMAL;
12589 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12591 updatetbl = (path == pathval());
12594 if (strstr(path, "%builtin") != NULL)
12595 act |= DO_ALTBLTIN;
12598 /* If name is in the table, check answer will be ok */
12599 cmdp = cmdlookup(name, 0);
12600 if (cmdp != NULL) {
12603 switch (cmdp->cmdtype) {
12621 } else if (cmdp->rehash == 0)
12622 /* if not invalidated by cd, we're done */
12626 /* If %builtin not in path, check for builtin next */
12627 bcmd = find_builtin(name);
12629 if (IS_BUILTIN_REGULAR(bcmd))
12630 goto builtin_success;
12631 if (act & DO_ALTPATH) {
12632 if (!(act & DO_ALTBLTIN))
12633 goto builtin_success;
12634 } else if (builtinloc <= 0) {
12635 goto builtin_success;
12639 #if ENABLE_FEATURE_SH_STANDALONE
12641 int applet_no = find_applet_by_name(name);
12642 if (applet_no >= 0) {
12643 entry->cmdtype = CMDNORMAL;
12644 entry->u.index = -2 - applet_no;
12650 /* We have to search path. */
12651 prev = -1; /* where to start */
12652 if (cmdp && cmdp->rehash) { /* doing a rehash */
12653 if (cmdp->cmdtype == CMDBUILTIN)
12656 prev = cmdp->param.index;
12662 while ((fullname = path_advance(&path, name)) != NULL) {
12663 stunalloc(fullname);
12664 /* NB: code below will still use fullname
12665 * despite it being "unallocated" */
12668 if (prefix(pathopt, "builtin")) {
12670 goto builtin_success;
12673 if ((act & DO_NOFUNC)
12674 || !prefix(pathopt, "func")
12675 ) { /* ignore unimplemented options */
12679 /* if rehash, don't redo absolute path names */
12680 if (fullname[0] == '/' && idx <= prev) {
12683 TRACE(("searchexec \"%s\": no change\n", name));
12686 while (stat(fullname, &statb) < 0) {
12688 if (errno == EINTR)
12691 if (errno != ENOENT && errno != ENOTDIR)
12695 e = EACCES; /* if we fail, this will be the error */
12696 if (!S_ISREG(statb.st_mode))
12698 if (pathopt) { /* this is a %func directory */
12699 stalloc(strlen(fullname) + 1);
12700 /* NB: stalloc will return space pointed by fullname
12701 * (because we don't have any intervening allocations
12702 * between stunalloc above and this stalloc) */
12703 readcmdfile(fullname);
12704 cmdp = cmdlookup(name, 0);
12705 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12706 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12707 stunalloc(fullname);
12710 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12712 entry->cmdtype = CMDNORMAL;
12713 entry->u.index = idx;
12717 cmdp = cmdlookup(name, 1);
12718 cmdp->cmdtype = CMDNORMAL;
12719 cmdp->param.index = idx;
12724 /* We failed. If there was an entry for this command, delete it */
12725 if (cmdp && updatetbl)
12726 delete_cmd_entry();
12728 ash_msg("%s: %s", name, errmsg(e, "not found"));
12729 entry->cmdtype = CMDUNKNOWN;
12734 entry->cmdtype = CMDBUILTIN;
12735 entry->u.cmd = bcmd;
12739 cmdp = cmdlookup(name, 1);
12740 cmdp->cmdtype = CMDBUILTIN;
12741 cmdp->param.cmd = bcmd;
12745 entry->cmdtype = cmdp->cmdtype;
12746 entry->u = cmdp->param;
12751 * The trap builtin.
12753 static int FAST_FUNC
12754 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12758 int signo, exitcode;
12763 for (signo = 0; signo < NSIG; signo++) {
12764 char *tr = trap_ptr[signo];
12766 /* note: bash adds "SIG", but only if invoked
12767 * as "bash". If called as "sh", or if set -o posix,
12768 * then it prints short signal names.
12769 * We are printing short names: */
12770 out1fmt("trap -- %s %s\n",
12772 get_signame(signo));
12773 /* trap_ptr != trap only if we are in special-cased `trap` code.
12774 * In this case, we will exit very soon, no need to free(). */
12775 /* if (trap_ptr != trap && tp[0]) */
12780 if (trap_ptr != trap) {
12793 signo = get_signum(*ap);
12795 /* Mimic bash message exactly */
12796 ash_msg("%s: invalid signal specification", *ap);
12802 if (LONE_DASH(action))
12805 action = ckstrdup(action);
12809 may_have_traps = 1;
12810 trap[signo] = action;
12821 /* ============ Builtins */
12823 #if ENABLE_ASH_HELP
12824 static int FAST_FUNC
12825 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12831 "Built-in commands:\n"
12832 "------------------\n");
12833 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12834 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12835 builtintab[i].name + 1);
12841 # if ENABLE_FEATURE_SH_STANDALONE
12843 const char *a = applet_names;
12845 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12850 while (*a++ != '\0')
12855 newline_and_flush(stdout);
12856 return EXIT_SUCCESS;
12861 static int FAST_FUNC
12862 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12864 show_history(line_input_state);
12865 return EXIT_SUCCESS;
12870 * The export and readonly commands.
12872 static int FAST_FUNC
12873 exportcmd(int argc UNUSED_PARAM, char **argv)
12883 /* "readonly" in bash accepts, but ignores -n.
12884 * We do the same: it saves a conditional in nextopt's param.
12887 while ((opt = nextopt("np")) != '\0') {
12889 flag_off = VEXPORT;
12892 if (argv[0][0] == 'r') {
12894 flag_off = 0; /* readonly ignores -n */
12896 flag_off = ~flag_off;
12898 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12904 p = strchr(name, '=');
12908 vp = *findvar(hashvar(name), name);
12910 vp->flags = ((vp->flags | flag) & flag_off);
12914 setvar(name, p, (flag & flag_off));
12915 } while ((name = *++aptr) != NULL);
12920 /* No arguments. Show the list of exported or readonly vars.
12923 showvars(argv[0], flag, 0);
12928 * Delete a function if it exists.
12931 unsetfunc(const char *name)
12933 struct tblentry *cmdp;
12935 cmdp = cmdlookup(name, 0);
12936 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12937 delete_cmd_entry();
12941 * The unset builtin command. We unset the function before we unset the
12942 * variable to allow a function to be unset when there is a readonly variable
12943 * with the same name.
12945 static int FAST_FUNC
12946 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12953 while ((i = nextopt("vf")) != 0) {
12957 for (ap = argptr; *ap; ap++) {
12970 static const unsigned char timescmd_str[] ALIGN1 = {
12971 ' ', offsetof(struct tms, tms_utime),
12972 '\n', offsetof(struct tms, tms_stime),
12973 ' ', offsetof(struct tms, tms_cutime),
12974 '\n', offsetof(struct tms, tms_cstime),
12977 static int FAST_FUNC
12978 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12980 unsigned long clk_tck, s, t;
12981 const unsigned char *p;
12984 clk_tck = bb_clk_tck();
12989 t = *(clock_t *)(((char *) &buf) + p[1]);
12992 out1fmt("%lum%lu.%03lus%c",
12994 (t * 1000) / clk_tck,
13002 #if ENABLE_SH_MATH_SUPPORT
13004 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13005 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13007 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13009 static int FAST_FUNC
13010 letcmd(int argc UNUSED_PARAM, char **argv)
13016 ash_msg_and_raise_error("expression expected");
13018 i = ash_arith(*argv);
13026 * The read builtin. Options:
13027 * -r Do not interpret '\' specially
13028 * -s Turn off echo (tty only)
13029 * -n NCHARS Read NCHARS max
13030 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13031 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13032 * -u FD Read from given FD instead of fd 0
13033 * This uses unbuffered input, which may be avoidable in some cases.
13034 * TODO: bash also has:
13035 * -a ARRAY Read into array[0],[1],etc
13036 * -d DELIM End on DELIM char, not newline
13037 * -e Use line editing (tty only)
13039 static int FAST_FUNC
13040 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13042 char *opt_n = NULL;
13043 char *opt_p = NULL;
13044 char *opt_t = NULL;
13045 char *opt_u = NULL;
13046 int read_flags = 0;
13050 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13059 read_flags |= BUILTIN_READ_SILENT;
13065 read_flags |= BUILTIN_READ_RAW;
13075 /* "read -s" needs to save/restore termios, can't allow ^C
13076 * to jump out of it.
13079 r = shell_builtin_read(setvar0,
13081 bltinlookup("IFS"), /* can be NULL */
13090 if ((uintptr_t)r > 1)
13091 ash_msg_and_raise_error(r);
13093 return (uintptr_t)r;
13096 static int FAST_FUNC
13097 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13099 static const char permuser[3] ALIGN1 = "ogu";
13102 int symbolic_mode = 0;
13104 while (nextopt("S") != '\0') {
13113 if (*argptr == NULL) {
13114 if (symbolic_mode) {
13115 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13122 *p++ = permuser[i];
13124 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13125 if (!(mask & 0400)) *p++ = 'r';
13126 if (!(mask & 0200)) *p++ = 'w';
13127 if (!(mask & 0100)) *p++ = 'x';
13135 out1fmt("%04o\n", mask);
13138 char *modestr = *argptr;
13139 /* numeric umasks are taken as-is */
13140 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13141 if (!isdigit(modestr[0]))
13143 mask = bb_parse_mode(modestr, mask);
13144 if ((unsigned)mask > 0777) {
13145 ash_msg_and_raise_error("illegal mode: %s", modestr);
13147 if (!isdigit(modestr[0]))
13154 static int FAST_FUNC
13155 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13157 return shell_builtin_ulimit(argv);
13160 /* ============ main() and helpers */
13163 * Called to exit the shell.
13172 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13173 save_history(line_input_state);
13175 status = exitstatus;
13176 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13177 if (setjmp(loc.loc)) {
13178 if (exception_type == EXEXIT)
13179 status = exitstatus;
13182 exception_handler = &loc;
13188 /*free(p); - we'll exit soon */
13191 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13192 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13195 flush_stdout_stderr();
13203 /* we will never free this */
13204 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13206 signal(SIGCHLD, SIG_DFL);
13207 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13208 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13210 signal(SIGHUP, SIG_DFL);
13215 struct stat st1, st2;
13218 for (envp = environ; envp && *envp; envp++) {
13219 p = endofname(*envp);
13220 if (p != *envp && *p == '=') {
13221 setvareq(*envp, VEXPORT|VTEXTFIXED);
13225 setvareq((char*)defoptindvar, VTEXTFIXED);
13227 setvar0("PPID", utoa(getppid()));
13228 #if ENABLE_ASH_BASH_COMPAT
13229 p = lookupvar("SHLVL");
13230 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13231 if (!lookupvar("HOSTNAME")) {
13232 struct utsname uts;
13234 setvar0("HOSTNAME", uts.nodename);
13237 p = lookupvar("PWD");
13239 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13240 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13250 //usage:#define ash_trivial_usage
13251 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13252 //usage:#define ash_full_usage "\n\n"
13253 //usage: "Unix shell interpreter"
13255 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13256 //usage:# define sh_trivial_usage ash_trivial_usage
13257 //usage:# define sh_full_usage ash_full_usage
13259 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13260 //usage:# define bash_trivial_usage ash_trivial_usage
13261 //usage:# define bash_full_usage ash_full_usage
13265 * Process the shell command line arguments.
13268 procargs(char **argv)
13271 const char *xminusc;
13276 /* if (xargv[0]) - mmm, this is always true! */
13278 for (i = 0; i < NOPTS; i++)
13281 if (options(/*cmdline:*/ 1)) {
13282 /* it already printed err message */
13283 raise_exception(EXERROR);
13287 if (*xargv == NULL) {
13289 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13292 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13296 for (i = 0; i < NOPTS; i++)
13297 if (optlist[i] == 2)
13302 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13307 } else if (!sflag) {
13308 setinputfile(*xargv, 0);
13311 commandname = arg0;
13314 shellparam.p = xargv;
13315 #if ENABLE_ASH_GETOPTS
13316 shellparam.optind = 1;
13317 shellparam.optoff = -1;
13319 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13321 shellparam.nparam++;
13328 * Read /etc/profile or .profile.
13331 read_profile(const char *name)
13333 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13340 * This routine is called when an error or an interrupt occurs in an
13341 * interactive shell and control is returned to the main command loop.
13349 /* from input.c: */
13350 g_parsefile->left_in_buffer = 0;
13351 g_parsefile->left_in_line = 0; /* clear input buffer */
13353 /* from parser.c: */
13356 /* from redir.c: */
13357 clearredir(/*drop:*/ 0);
13361 static short profile_buf[16384];
13362 extern int etext();
13366 * Main routine. We initialize things, parse the arguments, execute
13367 * profiles if we're a login shell, and then call cmdloop to execute
13368 * commands. The setjmp call sets up the location to jump to when an
13369 * exception occurs. When an exception occurs the variable "state"
13370 * is used to figure out how far we had gotten.
13372 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13373 int ash_main(int argc UNUSED_PARAM, char **argv)
13375 const char *shinit;
13376 volatile smallint state;
13377 struct jmploc jmploc;
13378 struct stackmark smark;
13380 /* Initialize global data */
13384 #if ENABLE_ASH_ALIAS
13390 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13393 #if ENABLE_FEATURE_EDITING
13394 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13397 if (setjmp(jmploc.loc)) {
13403 e = exception_type;
13405 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13409 newline_and_flush(stderr);
13412 popstackmark(&smark);
13413 FORCE_INT_ON; /* enable interrupts */
13422 exception_handler = &jmploc;
13425 TRACE(("Shell args: "));
13426 trace_puts_args(argv);
13428 rootpid = getpid();
13431 setstackmark(&smark);
13434 if (argv[0] && argv[0][0] == '-')
13440 read_profile("/etc/profile");
13443 hp = lookupvar("HOME");
13445 hp = concat_path_file(hp, ".profile");
13454 getuid() == geteuid() && getgid() == getegid() &&
13458 shinit = lookupvar("ENV");
13459 if (shinit != NULL && *shinit != '\0') {
13460 read_profile(shinit);
13466 /* evalstring pushes parsefile stack.
13467 * Ensure we don't falsely claim that 0 (stdin)
13468 * is one of stacked source fds.
13469 * Testcase: ash -c 'exec 1>&0' must not complain. */
13470 // if (!sflag) g_parsefile->pf_fd = -1;
13471 // ^^ not necessary since now we special-case fd 0
13472 // in is_hidden_fd() to not be considered "hidden fd"
13473 evalstring(minusc, 0);
13476 if (sflag || minusc == NULL) {
13477 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13479 const char *hp = lookupvar("HISTFILE");
13481 hp = lookupvar("HOME");
13483 hp = concat_path_file(hp, ".ash_history");
13484 setvar0("HISTFILE", hp);
13486 hp = lookupvar("HISTFILE");
13490 line_input_state->hist_file = hp;
13491 # if ENABLE_FEATURE_SH_HISTFILESIZE
13492 hp = lookupvar("HISTFILESIZE");
13493 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13497 state4: /* XXX ??? - why isn't this before the "if" statement */
13505 extern void _mcleanup(void);
13509 TRACE(("End of main reached\n"));
13516 * Copyright (c) 1989, 1991, 1993, 1994
13517 * The Regents of the University of California. All rights reserved.
13519 * This code is derived from software contributed to Berkeley by
13520 * Kenneth Almquist.
13522 * Redistribution and use in source and binary forms, with or without
13523 * modification, are permitted provided that the following conditions
13525 * 1. Redistributions of source code must retain the above copyright
13526 * notice, this list of conditions and the following disclaimer.
13527 * 2. Redistributions in binary form must reproduce the above copyright
13528 * notice, this list of conditions and the following disclaimer in the
13529 * documentation and/or other materials provided with the distribution.
13530 * 3. Neither the name of the University nor the names of its contributors
13531 * may be used to endorse or promote products derived from this software
13532 * without specific prior written permission.
13534 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13535 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13536 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13537 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13538 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13539 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13540 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13541 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13542 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13543 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF