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.
21 //config: depends on !NOMMU
23 //config: Tha 'ash' shell adds about 60k in the default configuration and is
24 //config: the most complete and most pedantically correct shell included with
25 //config: busybox. This shell is actually a derivative of the Debian 'dash'
26 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
27 //config: (written by Kenneth Almquist) from NetBSD.
29 //config:# ash options
30 //config:# note: Don't remove !NOMMU part in the next line; it would break
31 //config:# menuconfig's indenting.
32 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
34 //config:config ASH_OPTIMIZE_FOR_SIZE
35 //config: bool "Optimize for size instead of speed"
37 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
39 //config:config ASH_INTERNAL_GLOB
40 //config: bool "Use internal glob() implementation"
41 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
42 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
44 //config: Do not use glob() function from libc, use internal implementation.
45 //config: Use this if you are getting "glob.h: No such file or directory"
46 //config: or similar build errors.
47 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
48 //config: which would break ash if you select N here.
50 //config:config ASH_BASH_COMPAT
51 //config: bool "bash-compatible extensions"
53 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
55 //config:config ASH_JOB_CONTROL
56 //config: bool "Job control"
58 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
60 //config:config ASH_ALIAS
61 //config: bool "Alias support"
63 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
65 //config:config ASH_RANDOM_SUPPORT
66 //config: bool "Pseudorandom generator and $RANDOM variable"
68 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
70 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
71 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
72 //config: You can reset the generator by using a specified start value.
73 //config: After "unset RANDOM" the generator will switch off and this
74 //config: variable will no longer have special treatment.
76 //config:config ASH_EXPAND_PRMT
77 //config: bool "Expand prompt string"
79 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
81 //config: $PS# may contain volatile content, such as backquote commands.
82 //config: This option recreates the prompt string from the environment
83 //config: variable each time it is displayed.
85 //config:config ASH_IDLE_TIMEOUT
86 //config: bool "Idle timeout variable $TMOUT"
88 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
90 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
92 //config:config ASH_MAIL
93 //config: bool "Check for new mail in interactive shell"
95 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
97 //config: Enable "check for new mail" function:
98 //config: if set, $MAIL file and $MAILPATH list of files
99 //config: are checked for mtime changes, and "you have mail"
100 //config: message is printed if change is detected.
102 //config:config ASH_ECHO
103 //config: bool "echo builtin"
105 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
107 //config:config ASH_PRINTF
108 //config: bool "printf builtin"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config:config ASH_TEST
113 //config: bool "test builtin"
115 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
117 //config:config ASH_HELP
118 //config: bool "help builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_GETOPTS
123 //config: bool "getopts builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_CMDCMD
128 //config: bool "command builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config: Enable support for the 'command' builtin, which allows
133 //config: you to run the specified command or builtin,
134 //config: even when there is a function with the same name.
136 //config:endif # ash options
138 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
139 //applet:IF_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * The following should be set to reflect the type of system you have:
149 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
150 * define SYSV if you are running under System V.
151 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
152 * define DEBUG=2 to compile in and turn on debugging.
154 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
155 * debugging info will be written to ./trace and a quit signal
156 * will generate a core dump.
159 /* Tweak debug output verbosity here */
163 #define DEBUG_INTONOFF 0
167 #define JOBS ENABLE_ASH_JOB_CONTROL
171 #include <sys/times.h>
172 #include <sys/utsname.h> /* for setting $HOSTNAME */
174 #include "busybox.h" /* for applet_names */
176 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
177 /* Bionic at least up to version 24 has no glob() */
178 # undef ENABLE_ASH_INTERNAL_GLOB
179 # define ENABLE_ASH_INTERNAL_GLOB 1
182 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
183 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
184 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
185 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
186 # error glob() should unbackslash them and match. uClibc does not unbackslash,
187 # error fails to match dirname, subsequently not expanding <pattern> in it.
189 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
190 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
193 #if !ENABLE_ASH_INTERNAL_GLOB
198 #include "shell_common.h"
199 #if ENABLE_FEATURE_SH_MATH
202 #if ENABLE_ASH_RANDOM_SUPPORT
205 # define CLEAR_RANDOM_T(rnd) ((void)0)
208 #include "NUM_APPLETS.h"
210 /* STANDALONE does not make sense, and won't compile */
211 # undef CONFIG_FEATURE_SH_STANDALONE
212 # undef ENABLE_FEATURE_SH_STANDALONE
213 # undef IF_FEATURE_SH_STANDALONE
214 # undef IF_NOT_FEATURE_SH_STANDALONE
215 # define ENABLE_FEATURE_SH_STANDALONE 0
216 # define IF_FEATURE_SH_STANDALONE(...)
217 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
221 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
225 # error "Do not even bother, ash will not run on NOMMU machine"
229 /* ============ Hash table sizes. Configurable. */
233 #define CMDTABLESIZE 31 /* should be prime */
236 /* ============ Shell options */
238 static const char *const optletters_optnames[] = {
253 #if ENABLE_ASH_BASH_COMPAT
262 #define optletters(n) optletters_optnames[n][0]
263 #define optnames(n) (optletters_optnames[n] + 1)
265 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
268 /* ============ Misc data */
270 #define msg_illnum "Illegal number: %s"
273 * We enclose jmp_buf in a structure so that we can declare pointers to
274 * jump locations. The global variable handler contains the location to
275 * jump to when an exception occurs, and the global variable exception_type
276 * contains a code identifying the exception. To implement nested
277 * exception handlers, the user should save the value of handler on entry
278 * to an inner scope, set handler to point to a jmploc structure for the
279 * inner scope, and restore handler on exit from the scope.
285 struct globals_misc {
286 uint8_t exitstatus; /* exit status of last command */
287 uint8_t back_exitstatus;/* exit status of backquoted command */
288 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
289 int rootpid; /* pid of main shell */
290 /* shell level: 0 for the main shell, 1 for its children, and so on */
292 #define rootshell (!shlvl)
293 char *minusc; /* argument to -c option */
295 char *curdir; // = nullstr; /* current working directory */
296 char *physdir; // = nullstr; /* physical working directory */
298 char *arg0; /* value of $0 */
300 struct jmploc *exception_handler;
302 volatile int suppress_int; /* counter */
303 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
304 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
305 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
306 smallint exception_type; /* kind of exception (0..5) */
308 #define EXINT 0 /* SIGINT received */
309 #define EXERROR 1 /* a generic error */
310 #define EXEXIT 4 /* exit the shell */
313 char nullstr[1]; /* zero length string */
316 #define eflag optlist[0]
317 #define fflag optlist[1]
318 #define Iflag optlist[2]
319 #define iflag optlist[3]
320 #define mflag optlist[4]
321 #define nflag optlist[5]
322 #define sflag optlist[6]
323 #define xflag optlist[7]
324 #define vflag optlist[8]
325 #define Cflag optlist[9]
326 #define aflag optlist[10]
327 #define bflag optlist[11]
328 #define uflag optlist[12]
329 #define viflag optlist[13]
330 #if ENABLE_ASH_BASH_COMPAT
331 # define pipefail optlist[14]
336 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
337 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
340 /* trap handler commands */
342 * Sigmode records the current value of the signal handlers for the various
343 * modes. A value of zero means that the current handler is not known.
344 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
346 char sigmode[NSIG - 1];
347 #define S_DFL 1 /* default signal handling (SIG_DFL) */
348 #define S_CATCH 2 /* signal is caught */
349 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
350 #define S_HARD_IGN 4 /* signal is ignored permanently */
352 /* indicates specified signal received */
353 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
354 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
356 char **trap_ptr; /* used only by "trap hack" */
358 /* Rarely referenced stuff */
359 #if ENABLE_ASH_RANDOM_SUPPORT
362 pid_t backgndpid; /* pid of last background process */
364 extern struct globals_misc *const ash_ptr_to_globals_misc;
365 #define G_misc (*ash_ptr_to_globals_misc)
366 #define exitstatus (G_misc.exitstatus )
367 #define back_exitstatus (G_misc.back_exitstatus )
368 #define job_warning (G_misc.job_warning)
369 #define rootpid (G_misc.rootpid )
370 #define shlvl (G_misc.shlvl )
371 #define minusc (G_misc.minusc )
372 #define curdir (G_misc.curdir )
373 #define physdir (G_misc.physdir )
374 #define arg0 (G_misc.arg0 )
375 #define exception_handler (G_misc.exception_handler)
376 #define exception_type (G_misc.exception_type )
377 #define suppress_int (G_misc.suppress_int )
378 #define pending_int (G_misc.pending_int )
379 #define got_sigchld (G_misc.got_sigchld )
380 #define pending_sig (G_misc.pending_sig )
381 #define isloginsh (G_misc.isloginsh )
382 #define nullstr (G_misc.nullstr )
383 #define optlist (G_misc.optlist )
384 #define sigmode (G_misc.sigmode )
385 #define gotsig (G_misc.gotsig )
386 #define may_have_traps (G_misc.may_have_traps )
387 #define trap (G_misc.trap )
388 #define trap_ptr (G_misc.trap_ptr )
389 #define random_gen (G_misc.random_gen )
390 #define backgndpid (G_misc.backgndpid )
391 #define INIT_G_misc() do { \
392 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
400 /* ============ DEBUG */
402 static void trace_printf(const char *fmt, ...);
403 static void trace_vprintf(const char *fmt, va_list va);
404 # define TRACE(param) trace_printf param
405 # define TRACEV(param) trace_vprintf param
406 # define close(fd) do { \
408 if (close(dfd) < 0) \
409 bb_error_msg("bug on %d: closing %d(0x%x)", \
410 __LINE__, dfd, dfd); \
413 # define TRACE(param)
414 # define TRACEV(param)
418 /* ============ Utility functions */
419 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
420 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
423 isdigit_str9(const char *str)
425 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
426 while (--maxlen && isdigit(*str))
428 return (*str == '\0');
432 var_end(const char *var)
441 /* ============ Interrupts / exceptions */
443 static void exitshell(void) NORETURN;
446 * These macros allow the user to suspend the handling of interrupt signals
447 * over a period of time. This is similar to SIGHOLD or to sigblock, but
448 * much more efficient and portable. (But hacking the kernel is so much
449 * more fun than worrying about efficiency and portability. :-))
452 # define INT_OFF do { \
453 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
458 # define INT_OFF do { \
465 * Called to raise an exception. Since C doesn't include exceptions, we
466 * just do a longjmp to the exception handler. The type of exception is
467 * stored in the global variable "exception_type".
469 static void raise_exception(int) NORETURN;
471 raise_exception(int e)
474 if (exception_handler == NULL)
479 longjmp(exception_handler->loc, 1);
482 #define raise_exception(e) do { \
483 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
484 raise_exception(e); \
489 * Called when a SIGINT is received. (If the user specifies
490 * that SIGINT is to be trapped or ignored using the trap builtin, then
491 * this routine is not called.) Suppressint is nonzero when interrupts
492 * are held using the INT_OFF macro. (The test for iflag is just
493 * defensive programming.)
495 static void raise_interrupt(void) NORETURN;
497 raise_interrupt(void)
500 /* Signal is not automatically unmasked after it is raised,
501 * do it ourself - unmask all signals */
502 sigprocmask_allsigs(SIG_UNBLOCK);
503 /* pending_sig = 0; - now done in signal_handler() */
505 if (!(rootshell && iflag)) {
506 /* Kill ourself with SIGINT */
507 signal(SIGINT, SIG_DFL);
510 /* bash: ^C even on empty command line sets $? */
511 exitstatus = SIGINT + 128;
512 raise_exception(EXINT);
516 #define raise_interrupt() do { \
517 TRACE(("raising interrupt on line %d\n", __LINE__)); \
522 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
526 if (--suppress_int == 0 && pending_int) {
531 # define INT_ON do { \
532 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
536 # define INT_ON int_on()
538 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
546 #define FORCE_INT_ON force_int_on()
548 #define SAVE_INT(v) ((v) = suppress_int)
550 #define RESTORE_INT(v) do { \
552 suppress_int = (v); \
553 if (suppress_int == 0 && pending_int) \
558 /* ============ Stdout/stderr output */
561 outstr(const char *p, FILE *file)
569 flush_stdout_stderr(void)
576 /* Was called outcslow(c,FILE*), but c was always '\n' */
578 newline_and_flush(FILE *dest)
586 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
588 out1fmt(const char *fmt, ...)
595 r = vprintf(fmt, ap);
601 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
603 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
610 ret = vsnprintf(outbuf, length, fmt, ap);
617 out1str(const char *p)
623 out2str(const char *p)
626 flush_stdout_stderr();
630 /* ============ Parser structures */
632 /* control characters in argument strings */
633 #define CTL_FIRST CTLESC
634 #define CTLESC ((unsigned char)'\201') /* escape next character */
635 #define CTLVAR ((unsigned char)'\202') /* variable defn */
636 #define CTLENDVAR ((unsigned char)'\203')
637 #define CTLBACKQ ((unsigned char)'\204')
638 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
639 #define CTLENDARI ((unsigned char)'\207')
640 #define CTLQUOTEMARK ((unsigned char)'\210')
641 #define CTL_LAST CTLQUOTEMARK
643 /* variable substitution byte (follows CTLVAR) */
644 #define VSTYPE 0x0f /* type of variable substitution */
645 #define VSNUL 0x10 /* colon--treat the empty string as unset */
647 /* values of VSTYPE field */
648 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
649 #define VSMINUS 0x2 /* ${var-text} */
650 #define VSPLUS 0x3 /* ${var+text} */
651 #define VSQUESTION 0x4 /* ${var?message} */
652 #define VSASSIGN 0x5 /* ${var=text} */
653 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
654 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
655 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
656 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
657 #define VSLENGTH 0xa /* ${#var} */
658 #if ENABLE_ASH_BASH_COMPAT
659 #define VSSUBSTR 0xc /* ${var:position:length} */
660 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
661 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
664 static const char dolatstr[] ALIGN1 = {
665 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
667 #define DOLATSTRLEN 6
686 #if ENABLE_ASH_BASH_COMPAT
703 smallint type; /* Nxxxx */
706 union node *redirect;
711 smallint pipe_backgnd;
712 struct nodelist *cmdlist;
718 union node *redirect;
731 union node *elsepart;
758 struct nodelist *backquote;
761 /* nfile and ndup layout must match!
762 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
763 * that it is actually NTO2 (>&file), and change its type.
780 char *_unused_expfname;
799 struct nredir nredir;
800 struct nbinary nbinary;
804 struct nclist nclist;
813 * NODE_EOF is returned by parsecmd when it encounters an end of file.
814 * It must be distinct from NULL.
816 #define NODE_EOF ((union node *) -1L)
819 struct nodelist *next;
832 freefunc(struct funcnode *f)
834 if (f && --f->count < 0)
839 /* ============ Debugging output */
843 static FILE *tracefile;
846 trace_printf(const char *fmt, ...)
853 fprintf(tracefile, "%u ", (int) time(NULL));
855 fprintf(tracefile, "[%u] ", (int) getpid());
857 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
859 vfprintf(tracefile, fmt, va);
864 trace_vprintf(const char *fmt, va_list va)
868 vfprintf(tracefile, fmt, va);
869 fprintf(tracefile, "\n");
873 trace_puts(const char *s)
881 trace_puts_quoted(char *s)
888 putc('"', tracefile);
889 for (p = s; *p; p++) {
890 switch ((unsigned char)*p) {
891 case '\n': c = 'n'; goto backslash;
892 case '\t': c = 't'; goto backslash;
893 case '\r': c = 'r'; goto backslash;
894 case '\"': c = '\"'; goto backslash;
895 case '\\': c = '\\'; goto backslash;
896 case CTLESC: c = 'e'; goto backslash;
897 case CTLVAR: c = 'v'; goto backslash;
898 case CTLBACKQ: c = 'q'; goto backslash;
900 putc('\\', tracefile);
904 if (*p >= ' ' && *p <= '~')
907 putc('\\', tracefile);
908 putc((*p >> 6) & 03, tracefile);
909 putc((*p >> 3) & 07, tracefile);
910 putc(*p & 07, tracefile);
915 putc('"', tracefile);
919 trace_puts_args(char **ap)
926 trace_puts_quoted(*ap);
928 putc('\n', tracefile);
931 putc(' ', tracefile);
946 /* leave open because libedit might be using it */
949 strcpy(s, "./trace");
951 if (!freopen(s, "a", tracefile)) {
952 fprintf(stderr, "Can't re-open %s\n", s);
957 tracefile = fopen(s, "a");
958 if (tracefile == NULL) {
959 fprintf(stderr, "Can't open %s\n", s);
965 flags = fcntl(fileno(tracefile), F_GETFL);
967 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
969 setlinebuf(tracefile);
970 fputs("\nTracing started.\n", tracefile);
974 indent(int amount, char *pfx, FILE *fp)
978 for (i = 0; i < amount; i++) {
979 if (pfx && i == amount - 1)
985 /* little circular references here... */
986 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
989 sharg(union node *arg, FILE *fp)
992 struct nodelist *bqlist;
993 unsigned char subtype;
995 if (arg->type != NARG) {
996 out1fmt("<node type %d>\n", arg->type);
999 bqlist = arg->narg.backquote;
1000 for (p = arg->narg.text; *p; p++) {
1001 switch ((unsigned char)*p) {
1010 if (subtype == VSLENGTH)
1018 if (subtype & VSNUL)
1021 switch (subtype & VSTYPE) {
1047 case VSTRIMRIGHTMAX:
1054 out1fmt("<subtype %d>", subtype);
1063 shtree(bqlist->n, -1, NULL, fp);
1074 shcmd(union node *cmd, FILE *fp)
1082 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1088 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1092 switch (np->nfile.type) {
1093 case NTO: s = ">>"+1; dftfd = 1; break;
1094 case NCLOBBER: s = ">|"; dftfd = 1; break;
1095 case NAPPEND: s = ">>"; dftfd = 1; break;
1096 #if ENABLE_ASH_BASH_COMPAT
1099 case NTOFD: s = ">&"; dftfd = 1; break;
1100 case NFROM: s = "<"; break;
1101 case NFROMFD: s = "<&"; break;
1102 case NFROMTO: s = "<>"; break;
1103 default: s = "*error*"; break;
1105 if (np->nfile.fd != dftfd)
1106 fprintf(fp, "%d", np->nfile.fd);
1108 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1109 fprintf(fp, "%d", np->ndup.dupfd);
1111 sharg(np->nfile.fname, fp);
1118 shtree(union node *n, int ind, char *pfx, FILE *fp)
1120 struct nodelist *lp;
1126 indent(ind, pfx, fp);
1128 if (n == NODE_EOF) {
1143 shtree(n->nbinary.ch1, ind, NULL, fp);
1146 shtree(n->nbinary.ch2, ind, NULL, fp);
1154 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1155 shtree(lp->n, 0, NULL, fp);
1159 if (n->npipe.pipe_backgnd)
1165 fprintf(fp, "<node type %d>", n->type);
1173 showtree(union node *n)
1175 trace_puts("showtree called\n");
1176 shtree(n, 1, NULL, stderr);
1182 /* ============ Parser data */
1185 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1188 struct strlist *next;
1195 struct strpush *prev; /* preceding string on stack */
1197 int prev_left_in_line;
1198 #if ENABLE_ASH_ALIAS
1199 struct alias *ap; /* if push was associated with an alias */
1201 char *string; /* remember the string since it may change */
1203 /* Remember last two characters for pungetc. */
1206 /* Number of outstanding calls to pungetc. */
1211 struct parsefile *prev; /* preceding file on stack */
1212 int linno; /* current line */
1213 int pf_fd; /* file descriptor (or -1 if string) */
1214 int left_in_line; /* number of chars left in this line */
1215 int left_in_buffer; /* number of chars left in this buffer past the line */
1216 char *next_to_pgetc; /* next char in buffer */
1217 char *buf; /* input buffer */
1218 struct strpush *strpush; /* for pushing strings at this level */
1219 struct strpush basestrpush; /* so pushing one is fast */
1221 /* Remember last two characters for pungetc. */
1224 /* Number of outstanding calls to pungetc. */
1228 static struct parsefile basepf; /* top level input file */
1229 static struct parsefile *g_parsefile = &basepf; /* current input file */
1230 static int startlinno; /* line # where last token started */
1231 static char *commandname; /* currently executing command */
1232 static struct strlist *cmdenviron; /* environment for builtin command */
1235 /* ============ Message printing */
1238 ash_vmsg(const char *msg, va_list ap)
1240 fprintf(stderr, "%s: ", arg0);
1242 if (strcmp(arg0, commandname))
1243 fprintf(stderr, "%s: ", commandname);
1244 if (!iflag || g_parsefile->pf_fd > 0)
1245 fprintf(stderr, "line %d: ", startlinno);
1247 vfprintf(stderr, msg, ap);
1248 newline_and_flush(stderr);
1252 * Exverror is called to raise the error exception. If the second argument
1253 * is not NULL then error prints an error message using printf style
1254 * formatting. It then raises the error exception.
1256 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1258 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1262 TRACE(("ash_vmsg_and_raise(%d):", cond));
1265 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1270 flush_stdout_stderr();
1271 raise_exception(cond);
1275 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1277 ash_msg_and_raise_error(const char *msg, ...)
1284 ash_vmsg_and_raise(EXERROR, msg, ap);
1289 static void raise_error_syntax(const char *) NORETURN;
1291 raise_error_syntax(const char *msg)
1293 ash_msg_and_raise_error("syntax error: %s", msg);
1297 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1299 ash_msg_and_raise(int cond, const char *msg, ...)
1304 ash_vmsg_and_raise(cond, msg, ap);
1310 * error/warning routines for external builtins
1313 ash_msg(const char *fmt, ...)
1323 * Return a string describing an error. The returned string may be a
1324 * pointer to a static buffer that will be overwritten on the next call.
1325 * Action describes the operation that got the error.
1328 errmsg(int e, const char *em)
1330 if (e == ENOENT || e == ENOTDIR) {
1337 /* ============ Memory allocation */
1340 /* I consider these wrappers nearly useless:
1341 * ok, they return you to nearest exception handler, but
1342 * how much memory do you leak in the process, making
1343 * memory starvation worse?
1346 ckrealloc(void * p, size_t nbytes)
1348 p = realloc(p, nbytes);
1350 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1355 ckmalloc(size_t nbytes)
1357 return ckrealloc(NULL, nbytes);
1361 ckzalloc(size_t nbytes)
1363 return memset(ckmalloc(nbytes), 0, nbytes);
1367 ckstrdup(const char *s)
1369 char *p = strdup(s);
1371 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1375 /* Using bbox equivalents. They exit if out of memory */
1376 # define ckrealloc xrealloc
1377 # define ckmalloc xmalloc
1378 # define ckzalloc xzalloc
1379 # define ckstrdup xstrdup
1383 * It appears that grabstackstr() will barf with such alignments
1384 * because stalloc() will return a string allocated in a new stackblock.
1386 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1388 /* Most machines require the value returned from malloc to be aligned
1389 * in some way. The following macro will get this right
1390 * on many machines. */
1391 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1392 /* Minimum size of a block */
1393 MINSIZE = SHELL_ALIGN(504),
1396 struct stack_block {
1397 struct stack_block *prev;
1398 char space[MINSIZE];
1402 struct stack_block *stackp;
1408 struct globals_memstack {
1409 struct stack_block *g_stackp; // = &stackbase;
1410 char *g_stacknxt; // = stackbase.space;
1411 char *sstrend; // = stackbase.space + MINSIZE;
1412 size_t g_stacknleft; // = MINSIZE;
1413 struct stack_block stackbase;
1415 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1416 #define G_memstack (*ash_ptr_to_globals_memstack)
1417 #define g_stackp (G_memstack.g_stackp )
1418 #define g_stacknxt (G_memstack.g_stacknxt )
1419 #define sstrend (G_memstack.sstrend )
1420 #define g_stacknleft (G_memstack.g_stacknleft)
1421 #define stackbase (G_memstack.stackbase )
1422 #define INIT_G_memstack() do { \
1423 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1425 g_stackp = &stackbase; \
1426 g_stacknxt = stackbase.space; \
1427 g_stacknleft = MINSIZE; \
1428 sstrend = stackbase.space + MINSIZE; \
1432 #define stackblock() ((void *)g_stacknxt)
1433 #define stackblocksize() g_stacknleft
1436 * Parse trees for commands are allocated in lifo order, so we use a stack
1437 * to make this more efficient, and also to avoid all sorts of exception
1438 * handling code to handle interrupts in the middle of a parse.
1440 * The size 504 was chosen because the Ultrix malloc handles that size
1444 stalloc(size_t nbytes)
1449 aligned = SHELL_ALIGN(nbytes);
1450 if (aligned > g_stacknleft) {
1453 struct stack_block *sp;
1455 blocksize = aligned;
1456 if (blocksize < MINSIZE)
1457 blocksize = MINSIZE;
1458 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1459 if (len < blocksize)
1460 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1463 sp->prev = g_stackp;
1464 g_stacknxt = sp->space;
1465 g_stacknleft = blocksize;
1466 sstrend = g_stacknxt + blocksize;
1471 g_stacknxt += aligned;
1472 g_stacknleft -= aligned;
1477 stzalloc(size_t nbytes)
1479 return memset(stalloc(nbytes), 0, nbytes);
1486 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1487 write(STDERR_FILENO, "stunalloc\n", 10);
1491 g_stacknleft += g_stacknxt - (char *)p;
1496 * Like strdup but works with the ash stack.
1499 sstrdup(const char *p)
1501 size_t len = strlen(p) + 1;
1502 return memcpy(stalloc(len), p, len);
1506 grabstackblock(size_t len)
1512 pushstackmark(struct stackmark *mark, size_t len)
1514 mark->stackp = g_stackp;
1515 mark->stacknxt = g_stacknxt;
1516 mark->stacknleft = g_stacknleft;
1517 grabstackblock(len);
1521 setstackmark(struct stackmark *mark)
1523 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1527 popstackmark(struct stackmark *mark)
1529 struct stack_block *sp;
1535 while (g_stackp != mark->stackp) {
1537 g_stackp = sp->prev;
1540 g_stacknxt = mark->stacknxt;
1541 g_stacknleft = mark->stacknleft;
1542 sstrend = mark->stacknxt + mark->stacknleft;
1547 * When the parser reads in a string, it wants to stick the string on the
1548 * stack and only adjust the stack pointer when it knows how big the
1549 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1550 * of space on top of the stack and stackblocklen returns the length of
1551 * this block. Growstackblock will grow this space by at least one byte,
1552 * possibly moving it (like realloc). Grabstackblock actually allocates the
1553 * part of the block that has been used.
1556 growstackblock(void)
1560 newlen = g_stacknleft * 2;
1561 if (newlen < g_stacknleft)
1562 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1566 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1567 struct stack_block *sp;
1568 struct stack_block *prevstackp;
1573 prevstackp = sp->prev;
1574 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1575 sp = ckrealloc(sp, grosslen);
1576 sp->prev = prevstackp;
1578 g_stacknxt = sp->space;
1579 g_stacknleft = newlen;
1580 sstrend = sp->space + newlen;
1583 char *oldspace = g_stacknxt;
1584 size_t oldlen = g_stacknleft;
1585 char *p = stalloc(newlen);
1587 /* free the space we just allocated */
1588 g_stacknxt = memcpy(p, oldspace, oldlen);
1589 g_stacknleft += newlen;
1594 * The following routines are somewhat easier to use than the above.
1595 * The user declares a variable of type STACKSTR, which may be declared
1596 * to be a register. The macro STARTSTACKSTR initializes things. Then
1597 * the user uses the macro STPUTC to add characters to the string. In
1598 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1599 * grown as necessary. When the user is done, she can just leave the
1600 * string there and refer to it using stackblock(). Or she can allocate
1601 * the space for it using grabstackstr(). If it is necessary to allow
1602 * someone else to use the stack temporarily and then continue to grow
1603 * the string, the user should use grabstack to allocate the space, and
1604 * then call ungrabstr(p) to return to the previous mode of operation.
1606 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1607 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1608 * is space for at least one character.
1613 size_t len = stackblocksize();
1615 return (char *)stackblock() + len;
1619 * Called from CHECKSTRSPACE.
1622 makestrspace(size_t newlen, char *p)
1624 size_t len = p - g_stacknxt;
1630 size = stackblocksize();
1632 if (nleft >= newlen)
1636 return (char *)stackblock() + len;
1640 stack_nputstr(const char *s, size_t n, char *p)
1642 p = makestrspace(n, p);
1643 p = (char *)memcpy(p, s, n) + n;
1648 stack_putstr(const char *s, char *p)
1650 return stack_nputstr(s, strlen(s), p);
1654 _STPUTC(int c, char *p)
1662 #define STARTSTACKSTR(p) ((p) = stackblock())
1663 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1664 #define CHECKSTRSPACE(n, p) do { \
1667 size_t m = sstrend - q; \
1669 (p) = makestrspace(l, q); \
1671 #define USTPUTC(c, p) (*(p)++ = (c))
1672 #define STACKSTRNUL(p) do { \
1673 if ((p) == sstrend) \
1674 (p) = growstackstr(); \
1677 #define STUNPUTC(p) (--(p))
1678 #define STTOPC(p) ((p)[-1])
1679 #define STADJUST(amount, p) ((p) += (amount))
1681 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1682 #define ungrabstackstr(s, p) stunalloc(s)
1683 #define stackstrend() ((void *)sstrend)
1686 /* ============ String helpers */
1689 * prefix -- see if pfx is a prefix of string.
1692 prefix(const char *string, const char *pfx)
1695 if (*pfx++ != *string++)
1698 return (char *) string;
1702 * Check for a valid number. This should be elsewhere.
1705 is_number(const char *p)
1710 } while (*++p != '\0');
1715 * Convert a string of digits to an integer, printing an error message on
1719 number(const char *s)
1722 ash_msg_and_raise_error(msg_illnum, s);
1727 * Produce a possibly single quoted string suitable as input to the shell.
1728 * The return string is allocated on the stack.
1731 single_quote(const char *s)
1741 len = strchrnul(s, '\'') - s;
1743 q = p = makestrspace(len + 3, p);
1746 q = (char *)memcpy(q, s, len) + len;
1755 do len++; while (*++s == '\'');
1757 q = p = makestrspace(len + 3, p);
1760 q = (char *)memcpy(q, s - len, len) + len;
1768 return stackblock();
1772 /* ============ nextopt */
1774 static char **argptr; /* argument list for builtin commands */
1775 static char *optionarg; /* set by nextopt (like getopt) */
1776 static char *optptr; /* used by nextopt */
1779 * XXX - should get rid of. Have all builtins use getopt(3).
1780 * The library getopt must have the BSD extension static variable
1781 * "optreset", otherwise it can't be used within the shell safely.
1783 * Standard option processing (a la getopt) for builtin routines.
1784 * The only argument that is passed to nextopt is the option string;
1785 * the other arguments are unnecessary. It returns the character,
1786 * or '\0' on end of input.
1789 nextopt(const char *optstring)
1796 if (p == NULL || *p == '\0') {
1797 /* We ate entire "-param", take next one */
1803 if (*++p == '\0') /* just "-" ? */
1806 if (LONE_DASH(p)) /* "--" ? */
1808 /* p => next "-param" */
1810 /* p => some option char in the middle of a "-param" */
1812 for (q = optstring; *q != c;) {
1814 ash_msg_and_raise_error("illegal option -%c", c);
1822 ash_msg_and_raise_error("no arg for -%c option", c);
1832 /* ============ Shell variables */
1835 * The parsefile structure pointed to by the global variable parsefile
1836 * contains information about the current file being read.
1839 int nparam; /* # of positional parameters (without $0) */
1840 #if ENABLE_ASH_GETOPTS
1841 int optind; /* next parameter to be processed by getopts */
1842 int optoff; /* used by getopts */
1844 unsigned char malloced; /* if parameter list dynamically allocated */
1845 char **p; /* parameter list */
1849 * Free the list of positional parameters.
1852 freeparam(volatile struct shparam *param)
1854 if (param->malloced) {
1856 ap = ap1 = param->p;
1863 #if ENABLE_ASH_GETOPTS
1864 static void FAST_FUNC getoptsreset(const char *value);
1868 struct var *next; /* next entry in hash list */
1869 int flags; /* flags are defined above */
1870 const char *var_text; /* name=value */
1871 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1872 /* the variable gets set/unset */
1876 struct localvar *next; /* next local variable in list */
1877 struct var *vp; /* the variable that was made local */
1878 int flags; /* saved flags */
1879 const char *text; /* saved text */
1883 #define VEXPORT 0x01 /* variable is exported */
1884 #define VREADONLY 0x02 /* variable cannot be modified */
1885 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1886 #define VTEXTFIXED 0x08 /* text is statically allocated */
1887 #define VSTACK 0x10 /* text is allocated on the stack */
1888 #define VUNSET 0x20 /* the variable is not set */
1889 #define VNOFUNC 0x40 /* don't call the callback function */
1890 #define VNOSET 0x80 /* do not set variable - just readonly test */
1891 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1892 #if ENABLE_ASH_RANDOM_SUPPORT
1893 # define VDYNAMIC 0x200 /* dynamic variable */
1899 /* Need to be before varinit_data[] */
1900 #if ENABLE_LOCALE_SUPPORT
1901 static void FAST_FUNC
1902 change_lc_all(const char *value)
1904 if (value && *value != '\0')
1905 setlocale(LC_ALL, value);
1907 static void FAST_FUNC
1908 change_lc_ctype(const char *value)
1910 if (value && *value != '\0')
1911 setlocale(LC_CTYPE, value);
1915 static void chkmail(void);
1916 static void changemail(const char *var_value) FAST_FUNC;
1918 # define chkmail() ((void)0)
1920 static void changepath(const char *) FAST_FUNC;
1921 #if ENABLE_ASH_RANDOM_SUPPORT
1922 static void change_random(const char *) FAST_FUNC;
1925 static const struct {
1927 const char *var_text;
1928 void (*var_func)(const char *) FAST_FUNC;
1929 } varinit_data[] = {
1931 * Note: VEXPORT would not work correctly here for NOFORK applets:
1932 * some environment strings may be constant.
1934 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1936 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1937 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1939 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1940 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1941 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1942 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1943 #if ENABLE_ASH_GETOPTS
1944 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1946 #if ENABLE_ASH_RANDOM_SUPPORT
1947 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1949 #if ENABLE_LOCALE_SUPPORT
1950 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1951 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1953 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1960 struct globals_var {
1961 struct shparam shellparam; /* $@ current positional parameters */
1962 struct redirtab *redirlist;
1963 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1964 struct var *vartab[VTABSIZE];
1965 struct var varinit[ARRAY_SIZE(varinit_data)];
1967 extern struct globals_var *const ash_ptr_to_globals_var;
1968 #define G_var (*ash_ptr_to_globals_var)
1969 #define shellparam (G_var.shellparam )
1970 //#define redirlist (G_var.redirlist )
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) ?: 1;
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);
2145 #if ENABLE_UNICODE_SUPPORT
2147 reinit_unicode_for_ash(void)
2149 /* Unicode support should be activated even if LANG is set
2150 * _during_ shell execution, not only if it was set when
2151 * shell was started. Therefore, re-check LANG every time:
2153 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2154 || ENABLE_UNICODE_USING_LOCALE
2156 const char *s = lookupvar("LC_ALL");
2157 if (!s) s = lookupvar("LC_CTYPE");
2158 if (!s) s = lookupvar("LANG");
2163 # define reinit_unicode_for_ash() ((void)0)
2167 * Search the environment of a builtin command.
2170 bltinlookup(const char *name)
2174 for (sp = cmdenviron; sp; sp = sp->next) {
2175 if (varcmp(sp->text, name) == 0)
2176 return var_end(sp->text);
2178 return lookupvar(name);
2182 * Same as setvar except that the variable and value are passed in
2183 * the first argument as name=value. Since the first argument will
2184 * be actually stored in the table, it should not be a string that
2186 * Called with interrupts off.
2189 setvareq(char *s, int flags)
2191 struct var *vp, **vpp;
2194 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2195 vp = *findvar(vpp, s);
2197 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2200 if (flags & VNOSAVE)
2204 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2210 if (vp->var_func && !(flags & VNOFUNC))
2211 vp->var_func(var_end(s));
2213 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2214 free((char*)vp->var_text);
2216 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2218 /* variable s is not found */
2221 vp = ckzalloc(sizeof(*vp));
2223 /*vp->func = NULL; - ckzalloc did it */
2226 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2233 * Set the value of a variable. The flags argument is ored with the
2234 * flags of the variable. If val is NULL, the variable is unset.
2237 setvar(const char *name, const char *val, int flags)
2245 q = endofname(name);
2246 p = strchrnul(q, '=');
2248 if (!namelen || p != q)
2249 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2254 vallen = strlen(val);
2258 nameeq = ckmalloc(namelen + vallen + 2);
2259 p = memcpy(nameeq, name, namelen) + namelen;
2262 p = memcpy(p, val, vallen) + vallen;
2265 setvareq(nameeq, flags | VNOSAVE);
2269 static void FAST_FUNC
2270 setvar0(const char *name, const char *val)
2272 setvar(name, val, 0);
2276 * Unset the specified variable.
2279 unsetvar(const char *s)
2285 vpp = findvar(hashvar(s), s);
2289 int flags = vp->flags;
2292 if (flags & VREADONLY)
2294 #if ENABLE_ASH_RANDOM_SUPPORT
2295 vp->flags &= ~VDYNAMIC;
2299 if ((flags & VSTRFIXED) == 0) {
2301 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2302 free((char*)vp->var_text);
2308 vp->flags &= ~VEXPORT;
2318 * Process a linked list of variable assignments.
2321 listsetvar(struct strlist *list_set_var, int flags)
2323 struct strlist *lp = list_set_var;
2329 setvareq(lp->text, flags);
2336 * Generate a list of variables satisfying the given conditions.
2339 listvars(int on, int off, char ***end)
2350 for (vp = *vpp; vp; vp = vp->next) {
2351 if ((vp->flags & mask) == on) {
2352 if (ep == stackstrend())
2353 ep = growstackstr();
2354 *ep++ = (char*)vp->var_text;
2357 } while (++vpp < vartab + VTABSIZE);
2358 if (ep == stackstrend())
2359 ep = growstackstr();
2363 return grabstackstr(ep);
2367 /* ============ Path search helper
2369 * The variable path (passed by reference) should be set to the start
2370 * of the path before the first call; path_advance will update
2371 * this value as it proceeds. Successive calls to path_advance will return
2372 * the possible path expansions in sequence. If an option (indicated by
2373 * a percent sign) appears in the path entry then the global variable
2374 * pathopt will be set to point to it; otherwise pathopt will be set to
2377 static const char *pathopt; /* set by path_advance */
2380 path_advance(const char **path, const char *name)
2390 for (p = start; *p && *p != ':' && *p != '%'; p++)
2392 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2393 while (stackblocksize() < len)
2397 memcpy(q, start, p - start);
2405 while (*p && *p != ':')
2412 return stalloc(len);
2416 /* ============ Prompt */
2418 static smallint doprompt; /* if set, prompt the user */
2419 static smallint needprompt; /* true if interactive and at start of line */
2421 #if ENABLE_FEATURE_EDITING
2422 static line_input_t *line_input_state;
2423 static const char *cmdedit_prompt;
2425 putprompt(const char *s)
2427 if (ENABLE_ASH_EXPAND_PRMT) {
2428 free((char*)cmdedit_prompt);
2429 cmdedit_prompt = ckstrdup(s);
2436 putprompt(const char *s)
2442 #if ENABLE_ASH_EXPAND_PRMT
2443 /* expandstr() needs parsing machinery, so it is far away ahead... */
2444 static const char *expandstr(const char *ps);
2446 #define expandstr(s) s
2450 setprompt_if(smallint do_set, int whichprompt)
2453 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2460 switch (whichprompt) {
2470 #if ENABLE_ASH_EXPAND_PRMT
2471 pushstackmark(&smark, stackblocksize());
2473 putprompt(expandstr(prompt));
2474 #if ENABLE_ASH_EXPAND_PRMT
2475 popstackmark(&smark);
2480 /* ============ The cd and pwd commands */
2482 #define CD_PHYSICAL 1
2492 while ((i = nextopt("LP")) != '\0') {
2494 flags ^= CD_PHYSICAL;
2503 * Update curdir (the name of the current directory) in response to a
2507 updatepwd(const char *dir)
2514 cdcomppath = sstrdup(dir);
2517 if (curdir == nullstr)
2519 new = stack_putstr(curdir, new);
2521 new = makestrspace(strlen(dir) + 2, new);
2522 lim = (char *)stackblock() + 1;
2526 if (new > lim && *lim == '/')
2531 if (dir[1] == '/' && dir[2] != '/') {
2537 p = strtok(cdcomppath, "/");
2541 if (p[1] == '.' && p[2] == '\0') {
2553 new = stack_putstr(p, new);
2556 p = strtok(NULL, "/");
2561 return stackblock();
2565 * Find out what the current directory is. If we already know the current
2566 * directory, this routine returns immediately.
2571 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2572 return dir ? dir : nullstr;
2576 setpwd(const char *val, int setold)
2580 oldcur = dir = curdir;
2583 setvar("OLDPWD", oldcur, VEXPORT);
2586 if (physdir != nullstr) {
2587 if (physdir != oldcur)
2591 if (oldcur == val || !val) {
2597 dir = ckstrdup(val);
2598 if (oldcur != dir && oldcur != nullstr) {
2603 setvar("PWD", dir, VEXPORT);
2606 static void hashcd(void);
2609 * Actually do the chdir. We also call hashcd to let other routines
2610 * know that the current directory has changed.
2613 docd(const char *dest, int flags)
2615 const char *dir = NULL;
2618 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2621 if (!(flags & CD_PHYSICAL)) {
2622 dir = updatepwd(dest);
2636 static int FAST_FUNC
2637 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2649 dest = bltinlookup("HOME");
2650 else if (LONE_DASH(dest)) {
2651 dest = bltinlookup("OLDPWD");
2673 path = bltinlookup("CDPATH");
2676 p = path_advance(&path, dest);
2677 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2681 if (!docd(p, flags))
2692 ash_msg_and_raise_error("can't cd to %s", dest);
2695 if (flags & CD_PRINT)
2696 out1fmt("%s\n", curdir);
2700 static int FAST_FUNC
2701 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2704 const char *dir = curdir;
2708 if (physdir == nullstr)
2712 out1fmt("%s\n", dir);
2717 /* ============ ... */
2720 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2722 /* Syntax classes */
2723 #define CWORD 0 /* character is nothing special */
2724 #define CNL 1 /* newline character */
2725 #define CBACK 2 /* a backslash character */
2726 #define CSQUOTE 3 /* single quote */
2727 #define CDQUOTE 4 /* double quote */
2728 #define CENDQUOTE 5 /* a terminating quote */
2729 #define CBQUOTE 6 /* backwards single quote */
2730 #define CVAR 7 /* a dollar sign */
2731 #define CENDVAR 8 /* a '}' character */
2732 #define CLP 9 /* a left paren in arithmetic */
2733 #define CRP 10 /* a right paren in arithmetic */
2734 #define CENDFILE 11 /* end of file */
2735 #define CCTL 12 /* like CWORD, except it must be escaped */
2736 #define CSPCL 13 /* these terminate a word */
2737 #define CIGN 14 /* character should be ignored */
2740 #if ENABLE_ASH_ALIAS
2744 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2746 #if ENABLE_FEATURE_SH_MATH
2747 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2749 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2751 static const uint16_t S_I_T[] ALIGN2 = {
2752 #if ENABLE_ASH_ALIAS
2753 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2755 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2756 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2757 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2758 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2759 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2760 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2761 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2762 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2763 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2764 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2765 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2766 #if !USE_SIT_FUNCTION
2767 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2768 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2769 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2773 /* Constants below must match table above */
2775 #if ENABLE_ASH_ALIAS
2776 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2778 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2779 CNL_CNL_CNL_CNL , /* 2 */
2780 CWORD_CCTL_CCTL_CWORD , /* 3 */
2781 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2782 CVAR_CVAR_CWORD_CVAR , /* 5 */
2783 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2784 CSPCL_CWORD_CWORD_CLP , /* 7 */
2785 CSPCL_CWORD_CWORD_CRP , /* 8 */
2786 CBACK_CBACK_CCTL_CBACK , /* 9 */
2787 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2788 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2789 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2790 CWORD_CWORD_CWORD_CWORD , /* 13 */
2791 CCTL_CCTL_CCTL_CCTL , /* 14 */
2794 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2795 * caller must ensure proper cast on it if c is *char_ptr!
2797 /* Values for syntax param */
2798 #define BASESYNTAX 0 /* not in quotes */
2799 #define DQSYNTAX 1 /* in double quotes */
2800 #define SQSYNTAX 2 /* in single quotes */
2801 #define ARISYNTAX 3 /* in arithmetic */
2802 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2804 #if USE_SIT_FUNCTION
2807 SIT(int c, int syntax)
2809 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2810 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2812 * This causes '/' to be prepended with CTLESC in dquoted string,
2813 * making "./file"* treated incorrectly because we feed
2814 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2815 * The "homegrown" glob implementation is okay with that,
2816 * but glibc one isn't. With '/' always treated as CWORD,
2819 # if ENABLE_ASH_ALIAS
2820 static const uint8_t syntax_index_table[] ALIGN1 = {
2821 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2822 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2823 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2827 static const uint8_t syntax_index_table[] ALIGN1 = {
2828 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2829 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2830 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2839 # if ENABLE_ASH_ALIAS
2845 /* Cast is purely for paranoia here,
2846 * just in case someone passed signed char to us */
2847 if ((unsigned char)c >= CTL_FIRST
2848 && (unsigned char)c <= CTL_LAST
2852 s = strchrnul(spec_symbls, c);
2855 indx = syntax_index_table[s - spec_symbls];
2857 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2860 #else /* !USE_SIT_FUNCTION */
2862 static const uint8_t syntax_index_table[] ALIGN1 = {
2863 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2864 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2874 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2875 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2897 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2898 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2899 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2901 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2902 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2904 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2905 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2906 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2907 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2909 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2911 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2912 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2927 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2928 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2957 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2958 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2962 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2990 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2991 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2992 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2993 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2995 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2996 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2997 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2998 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2999 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3000 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3001 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3002 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3121 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3122 # if ENABLE_ASH_ALIAS
3123 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3128 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3129 #else /* debug version, caught one signed char bug */
3130 # define SIT(c, syntax) \
3132 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3133 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3134 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3135 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3136 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3140 #endif /* !USE_SIT_FUNCTION */
3143 /* ============ Alias handling */
3145 #if ENABLE_ASH_ALIAS
3147 #define ALIASINUSE 1
3158 static struct alias **atab; // [ATABSIZE];
3159 #define INIT_G_alias() do { \
3160 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3164 static struct alias **
3165 __lookupalias(const char *name)
3167 unsigned int hashval;
3174 ch = (unsigned char)*p;
3178 ch = (unsigned char)*++p;
3180 app = &atab[hashval % ATABSIZE];
3182 for (; *app; app = &(*app)->next) {
3183 if (strcmp(name, (*app)->name) == 0) {
3191 static struct alias *
3192 lookupalias(const char *name, int check)
3194 struct alias *ap = *__lookupalias(name);
3196 if (check && ap && (ap->flag & ALIASINUSE))
3201 static struct alias *
3202 freealias(struct alias *ap)
3206 if (ap->flag & ALIASINUSE) {
3207 ap->flag |= ALIASDEAD;
3219 setalias(const char *name, const char *val)
3221 struct alias *ap, **app;
3223 app = __lookupalias(name);
3227 if (!(ap->flag & ALIASINUSE)) {
3230 ap->val = ckstrdup(val);
3231 ap->flag &= ~ALIASDEAD;
3234 ap = ckzalloc(sizeof(struct alias));
3235 ap->name = ckstrdup(name);
3236 ap->val = ckstrdup(val);
3237 /*ap->flag = 0; - ckzalloc did it */
3238 /*ap->next = NULL;*/
3245 unalias(const char *name)
3249 app = __lookupalias(name);
3253 *app = freealias(*app);
3264 struct alias *ap, **app;
3268 for (i = 0; i < ATABSIZE; i++) {
3270 for (ap = *app; ap; ap = *app) {
3271 *app = freealias(*app);
3281 printalias(const struct alias *ap)
3283 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3287 * TODO - sort output
3289 static int FAST_FUNC
3290 aliascmd(int argc UNUSED_PARAM, char **argv)
3299 for (i = 0; i < ATABSIZE; i++) {
3300 for (ap = atab[i]; ap; ap = ap->next) {
3306 while ((n = *++argv) != NULL) {
3307 v = strchr(n+1, '=');
3308 if (v == NULL) { /* n+1: funny ksh stuff */
3309 ap = *__lookupalias(n);
3311 fprintf(stderr, "%s: %s not found\n", "alias", n);
3324 static int FAST_FUNC
3325 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3329 while ((i = nextopt("a")) != '\0') {
3335 for (i = 0; *argptr; argptr++) {
3336 if (unalias(*argptr)) {
3337 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3345 #endif /* ASH_ALIAS */
3348 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3351 #define FORK_NOJOB 2
3353 /* mode flags for showjob(s) */
3354 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3355 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3356 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3357 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3360 * A job structure contains information about a job. A job is either a
3361 * single process or a set of processes contained in a pipeline. In the
3362 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3366 pid_t ps_pid; /* process id */
3367 int ps_status; /* last process status from wait() */
3368 char *ps_cmd; /* text of command being run */
3372 struct procstat ps0; /* status of process */
3373 struct procstat *ps; /* status or processes when more than one */
3375 int stopstatus; /* status of a stopped job */
3378 nprocs: 16, /* number of processes */
3380 #define JOBRUNNING 0 /* at least one proc running */
3381 #define JOBSTOPPED 1 /* all procs are stopped */
3382 #define JOBDONE 2 /* all procs are completed */
3384 sigint: 1, /* job was killed by SIGINT */
3385 jobctl: 1, /* job running under job control */
3387 waited: 1, /* true if this entry has been waited for */
3388 used: 1, /* true if this entry is in used */
3389 changed: 1; /* true if status has changed */
3390 struct job *prev_job; /* previous job */
3393 static struct job *makejob(/*union node *,*/ int);
3394 static int forkshell(struct job *, union node *, int);
3395 static int waitforjob(struct job *);
3398 enum { doing_jobctl = 0 };
3399 #define setjobctl(on) do {} while (0)
3401 static smallint doing_jobctl; //references:8
3402 static void setjobctl(int);
3409 ignoresig(int signo)
3411 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3412 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3413 /* No, need to do it */
3414 signal(signo, SIG_IGN);
3416 sigmode[signo - 1] = S_HARD_IGN;
3420 * Only one usage site - in setsignal()
3423 signal_handler(int signo)
3425 if (signo == SIGCHLD) {
3431 gotsig[signo - 1] = 1;
3432 pending_sig = signo;
3434 if (signo == SIGINT && !trap[SIGINT]) {
3435 if (!suppress_int) {
3437 raise_interrupt(); /* does not return */
3444 * Set the signal handler for the specified signal. The routine figures
3445 * out what it should be set to.
3448 setsignal(int signo)
3451 char cur_act, new_act;
3452 struct sigaction act;
3456 if (t != NULL) { /* trap for this sig is set */
3458 if (t[0] == '\0') /* trap is "": ignore this sig */
3462 if (rootshell && new_act == S_DFL) {
3465 if (iflag || minusc || sflag == 0)
3474 * "In all cases, bash ignores SIGQUIT. Non-builtin
3475 * commands run by bash have signal handlers
3476 * set to the values inherited by the shell
3477 * from its parent". */
3493 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3494 //whereas we have to restore it to what shell got on entry
3495 //from the parent. See comment above
3497 if (signo == SIGCHLD)
3500 t = &sigmode[signo - 1];
3503 /* current setting is not yet known */
3504 if (sigaction(signo, NULL, &act)) {
3505 /* pretend it worked; maybe we should give a warning,
3506 * but other shells don't. We don't alter sigmode,
3507 * so we retry every time.
3508 * btw, in Linux it never fails. --vda */
3511 if (act.sa_handler == SIG_IGN) {
3512 cur_act = S_HARD_IGN;
3514 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3516 cur_act = S_IGN; /* don't hard ignore these */
3520 if (cur_act == S_HARD_IGN || cur_act == new_act)
3523 act.sa_handler = SIG_DFL;
3526 act.sa_handler = signal_handler;
3529 act.sa_handler = SIG_IGN;
3533 /* flags and mask matter only if !DFL and !IGN, but we do it
3534 * for all cases for more deterministic behavior:
3537 sigfillset(&act.sa_mask);
3539 sigaction_set(signo, &act);
3544 /* mode flags for set_curjob */
3545 #define CUR_DELETE 2
3546 #define CUR_RUNNING 1
3547 #define CUR_STOPPED 0
3550 /* pgrp of shell on invocation */
3551 static int initialpgrp; //references:2
3552 static int ttyfd = -1; //5
3555 static struct job *jobtab; //5
3557 static unsigned njobs; //4
3559 static struct job *curjob; //lots
3560 /* number of presumed living untracked jobs */
3561 static int jobless; //4
3564 set_curjob(struct job *jp, unsigned mode)
3567 struct job **jpp, **curp;
3569 /* first remove from list */
3570 jpp = curp = &curjob;
3575 jpp = &jp1->prev_job;
3577 *jpp = jp1->prev_job;
3579 /* Then re-insert in correct position */
3587 /* job being deleted */
3590 /* newly created job or backgrounded job,
3591 * put after all stopped jobs.
3596 if (!jp1 || jp1->state != JOBSTOPPED)
3599 jpp = &jp1->prev_job;
3605 /* newly stopped job - becomes curjob */
3606 jp->prev_job = *jpp;
3614 jobno(const struct job *jp)
3616 return jp - jobtab + 1;
3621 * Convert a job name to a job structure.
3624 #define getjob(name, getctl) getjob(name)
3627 getjob(const char *name, int getctl)
3631 const char *err_msg = "%s: no such job";
3635 char *(*match)(const char *, const char *);
3650 if (c == '+' || c == '%') {
3652 err_msg = "No current job";
3658 err_msg = "No previous job";
3668 if (num > 0 && num <= njobs) {
3669 jp = jobtab + num - 1;
3684 if (match(jp->ps[0].ps_cmd, p)) {
3688 err_msg = "%s: ambiguous";
3698 err_msg = "job %s not created under job control";
3699 if (getctl && jp->jobctl == 0)
3704 ash_msg_and_raise_error(err_msg, name);
3708 * Mark a job structure as unused.
3711 freejob(struct job *jp)
3713 struct procstat *ps;
3717 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3718 if (ps->ps_cmd != nullstr)
3721 if (jp->ps != &jp->ps0)
3724 set_curjob(jp, CUR_DELETE);
3730 xtcsetpgrp(int fd, pid_t pgrp)
3732 if (tcsetpgrp(fd, pgrp))
3733 ash_msg_and_raise_error("can't set tty process group (%m)");
3737 * Turn job control on and off.
3739 * Note: This code assumes that the third arg to ioctl is a character
3740 * pointer, which is true on Berkeley systems but not System V. Since
3741 * System V doesn't have job control yet, this isn't a problem now.
3743 * Called with interrupts off.
3751 if (on == doing_jobctl || rootshell == 0)
3755 ofd = fd = open(_PATH_TTY, O_RDWR);
3757 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3758 * That sometimes helps to acquire controlling tty.
3759 * Obviously, a workaround for bugs when someone
3760 * failed to provide a controlling tty to bash! :) */
3766 /* fd is a tty at this point */
3767 fd = fcntl(fd, F_DUPFD, 10);
3768 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3771 goto out; /* F_DUPFD failed */
3772 close_on_exec_on(fd);
3773 while (1) { /* while we are in the background */
3774 pgrp = tcgetpgrp(fd);
3777 ash_msg("can't access tty; job control turned off");
3781 if (pgrp == getpgrp())
3792 xtcsetpgrp(fd, pgrp);
3794 /* turning job control off */
3797 /* was xtcsetpgrp, but this can make exiting ash
3798 * loop forever if pty is already deleted */
3799 tcsetpgrp(fd, pgrp);
3813 static int FAST_FUNC
3814 killcmd(int argc, char **argv)
3816 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3819 if (argv[i][0] == '%') {
3821 * "kill %N" - job kill
3822 * Converting to pgrp / pid kill
3828 jp = getjob(argv[i], 0);
3830 * In jobs started under job control, we signal
3831 * entire process group by kill -PGRP_ID.
3832 * This happens, f.e., in interactive shell.
3834 * Otherwise, we signal each child via
3835 * kill PID1 PID2 PID3.
3837 * sh -c 'sleep 1|sleep 1 & kill %1'
3838 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3839 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3841 n = jp->nprocs; /* can't be 0 (I hope) */
3844 dst = alloca(n * sizeof(int)*4);
3846 for (j = 0; j < n; j++) {
3847 struct procstat *ps = &jp->ps[j];
3848 /* Skip non-running and not-stopped members
3849 * (i.e. dead members) of the job
3851 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3854 * kill_main has matching code to expect
3855 * leading space. Needed to not confuse
3856 * negative pids with "kill -SIGNAL_NO" syntax
3858 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3862 } while (argv[++i]);
3864 return kill_main(argc, argv);
3868 showpipe(struct job *jp /*, FILE *out*/)
3870 struct procstat *ps;
3871 struct procstat *psend;
3873 psend = jp->ps + jp->nprocs;
3874 for (ps = jp->ps + 1; ps < psend; ps++)
3875 printf(" | %s", ps->ps_cmd);
3876 newline_and_flush(stdout);
3877 flush_stdout_stderr();
3882 restartjob(struct job *jp, int mode)
3884 struct procstat *ps;
3890 if (jp->state == JOBDONE)
3892 jp->state = JOBRUNNING;
3893 pgid = jp->ps[0].ps_pid;
3894 if (mode == FORK_FG)
3895 xtcsetpgrp(ttyfd, pgid);
3896 killpg(pgid, SIGCONT);
3900 if (WIFSTOPPED(ps->ps_status)) {
3906 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3911 static int FAST_FUNC
3912 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3918 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3922 jp = getjob(*argv, 1);
3923 if (mode == FORK_BG) {
3924 set_curjob(jp, CUR_RUNNING);
3925 printf("[%d] ", jobno(jp));
3927 out1str(jp->ps[0].ps_cmd);
3928 showpipe(jp /*, stdout*/);
3929 retval = restartjob(jp, mode);
3930 } while (*argv && *++argv);
3936 sprint_status48(char *s, int status, int sigonly)
3942 if (!WIFEXITED(status)) {
3943 if (JOBS && WIFSTOPPED(status))
3944 st = WSTOPSIG(status);
3946 st = WTERMSIG(status);
3948 if (st == SIGINT || st == SIGPIPE)
3950 if (JOBS && WIFSTOPPED(status))
3954 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3955 col = fmtstr(s, 32, strsignal(st));
3956 if (WCOREDUMP(status)) {
3957 strcpy(s + col, " (core dumped)");
3958 col += sizeof(" (core dumped)")-1;
3960 } else if (!sigonly) {
3961 st = WEXITSTATUS(status);
3962 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3969 wait_block_or_sig(int *status)
3976 /* Poll all children for changes in their state */
3978 /* if job control is active, accept stopped processes too */
3979 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3981 break; /* Error (e.g. EINTR, ECHILD) or pid */
3983 /* Children exist, but none are ready. Sleep until interesting signal */
3986 sigprocmask(SIG_SETMASK, &mask, &mask);
3987 while (!got_sigchld && !pending_sig)
3989 sigprocmask(SIG_SETMASK, &mask, NULL);
3990 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3991 while (!got_sigchld && !pending_sig)
3995 /* If it was SIGCHLD, poll children again */
3996 } while (got_sigchld);
4001 #define DOWAIT_NONBLOCK 0
4002 #define DOWAIT_BLOCK 1
4003 #define DOWAIT_BLOCK_OR_SIG 2
4006 dowait(int block, struct job *job)
4011 struct job *thisjob = NULL;
4013 TRACE(("dowait(0x%x) called\n", block));
4015 /* It's wrong to call waitpid() outside of INT_OFF region:
4016 * signal can arrive just after syscall return and handler can
4017 * longjmp away, losing stop/exit notification processing.
4018 * Thus, for "jobs" builtin, and for waiting for a fg job,
4019 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4021 * However, for "wait" builtin it is wrong to simply call waitpid()
4022 * in INT_OFF region: "wait" needs to wait for any running job
4023 * to change state, but should exit on any trap too.
4024 * In INT_OFF region, a signal just before syscall entry can set
4025 * pending_sig variables, but we can't check them, and we would
4026 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4028 * Because of this, we run inside INT_OFF, but use a special routine
4029 * which combines waitpid() and sigsuspend().
4030 * This is the reason why we need to have a handler for SIGCHLD:
4031 * SIG_DFL handler does not wake sigsuspend().
4034 if (block == DOWAIT_BLOCK_OR_SIG) {
4035 pid = wait_block_or_sig(&status);
4038 if (block == DOWAIT_NONBLOCK)
4039 wait_flags = WNOHANG;
4040 /* if job control is active, accept stopped processes too */
4042 wait_flags |= WUNTRACED;
4043 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4044 pid = waitpid(-1, &status, wait_flags);
4046 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4047 pid, status, errno, strerror(errno)));
4052 for (jp = curjob; jp; jp = jp->prev_job) {
4054 struct procstat *ps;
4055 struct procstat *psend;
4056 if (jp->state == JOBDONE)
4060 psend = ps + jp->nprocs;
4062 if (ps->ps_pid == pid) {
4063 TRACE(("Job %d: changing status of proc %d "
4064 "from 0x%x to 0x%x\n",
4065 jobno(jp), pid, ps->ps_status, status));
4066 ps->ps_status = status;
4069 if (ps->ps_status == -1)
4070 jobstate = JOBRUNNING;
4072 if (jobstate == JOBRUNNING)
4074 if (WIFSTOPPED(ps->ps_status)) {
4075 jp->stopstatus = ps->ps_status;
4076 jobstate = JOBSTOPPED;
4079 } while (++ps < psend);
4083 /* Found the job where one of its processes changed its state.
4084 * Is there at least one live and running process in this job? */
4085 if (jobstate != JOBRUNNING) {
4086 /* No. All live processes in the job are stopped
4087 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4089 thisjob->changed = 1;
4090 if (thisjob->state != jobstate) {
4091 TRACE(("Job %d: changing state from %d to %d\n",
4092 jobno(thisjob), thisjob->state, jobstate));
4093 thisjob->state = jobstate;
4095 if (jobstate == JOBSTOPPED)
4096 set_curjob(thisjob, CUR_STOPPED);
4102 /* The process wasn't found in job list */
4103 if (JOBS && !WIFSTOPPED(status))
4108 if (thisjob && thisjob == job) {
4112 len = sprint_status48(s, status, 1);
4124 showjob(struct job *jp, int mode)
4126 struct procstat *ps;
4127 struct procstat *psend;
4130 char s[16 + 16 + 48];
4131 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4135 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4136 /* just output process (group) id of pipeline */
4137 fprintf(out, "%d\n", ps->ps_pid);
4141 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4146 else if (curjob && jp == curjob->prev_job)
4149 if (mode & SHOW_PIDS)
4150 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4152 psend = ps + jp->nprocs;
4154 if (jp->state == JOBRUNNING) {
4155 strcpy(s + col, "Running");
4156 col += sizeof("Running") - 1;
4158 int status = psend[-1].ps_status;
4159 if (jp->state == JOBSTOPPED)
4160 status = jp->stopstatus;
4161 col += sprint_status48(s + col, status, 0);
4163 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4165 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4166 * or prints several "PID | <cmdN>" lines,
4167 * depending on SHOW_PIDS bit.
4168 * We do not print status of individual processes
4169 * between PID and <cmdN>. bash does it, but not very well:
4170 * first line shows overall job status, not process status,
4171 * making it impossible to know 1st process status.
4175 /* for each process */
4178 if (mode & SHOW_PIDS)
4179 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4181 fprintf(out, "%s%*c%s%s",
4183 33 - col >= 0 ? 33 - col : 0, ' ',
4184 ps == jp->ps ? "" : "| ",
4187 } while (++ps != psend);
4188 newline_and_flush(out);
4192 if (jp->state == JOBDONE) {
4193 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4199 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4200 * statuses have changed since the last call to showjobs.
4207 TRACE(("showjobs(0x%x) called\n", mode));
4209 /* Handle all finished jobs */
4210 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4213 for (jp = curjob; jp; jp = jp->prev_job) {
4214 if (!(mode & SHOW_CHANGED) || jp->changed) {
4220 static int FAST_FUNC
4221 jobscmd(int argc UNUSED_PARAM, char **argv)
4226 while ((m = nextopt("lp")) != '\0') {
4230 mode |= SHOW_ONLY_PGID;
4236 showjob(getjob(*argv, 0), mode);
4246 /* Called only on finished or stopped jobs (no members are running) */
4248 getstatus(struct job *job)
4252 struct procstat *ps;
4254 /* Fetch last member's status */
4255 ps = job->ps + job->nprocs - 1;
4256 status = ps->ps_status;
4258 /* "set -o pipefail" mode: use last _nonzero_ status */
4259 while (status == 0 && --ps >= job->ps)
4260 status = ps->ps_status;
4263 retval = WEXITSTATUS(status);
4264 if (!WIFEXITED(status)) {
4266 retval = WSTOPSIG(status);
4267 if (!WIFSTOPPED(status))
4270 /* XXX: limits number of signals */
4271 retval = WTERMSIG(status);
4273 if (retval == SIGINT)
4279 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4280 jobno(job), job->nprocs, status, retval));
4284 static int FAST_FUNC
4285 waitcmd(int argc UNUSED_PARAM, char **argv)
4296 /* wait for all jobs */
4300 if (!jp) /* no running procs */
4302 if (jp->state == JOBRUNNING)
4308 * "When bash is waiting for an asynchronous command via
4309 * the wait builtin, the reception of a signal for which a trap
4310 * has been set will cause the wait builtin to return immediately
4311 * with an exit status greater than 128, immediately after which
4312 * the trap is executed."
4314 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4315 /* if child sends us a signal *and immediately exits*,
4316 * dowait() returns pid > 0. Check this case,
4317 * not "if (dowait() < 0)"!
4326 if (**argv != '%') {
4327 pid_t pid = number(*argv);
4332 if (job->ps[job->nprocs - 1].ps_pid == pid)
4334 job = job->prev_job;
4337 job = getjob(*argv, 0);
4339 /* loop until process terminated or stopped */
4340 while (job->state == JOBRUNNING) {
4341 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4346 retval = getstatus(job);
4353 retval = 128 + pending_sig;
4362 struct job *jp, *jq;
4364 len = njobs * sizeof(*jp);
4366 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4368 offset = (char *)jp - (char *)jq;
4370 /* Relocate pointers */
4373 jq = (struct job *)((char *)jq + l);
4377 #define joff(p) ((struct job *)((char *)(p) + l))
4378 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4379 if (joff(jp)->ps == &jq->ps0)
4380 jmove(joff(jp)->ps);
4381 if (joff(jp)->prev_job)
4382 jmove(joff(jp)->prev_job);
4392 jp = (struct job *)((char *)jp + len);
4396 } while (--jq >= jp);
4401 * Return a new job structure.
4402 * Called with interrupts off.
4405 makejob(/*union node *node,*/ int nprocs)
4410 for (i = njobs, jp = jobtab; ; jp++) {
4417 if (jp->state != JOBDONE || !jp->waited)
4426 memset(jp, 0, sizeof(*jp));
4428 /* jp->jobctl is a bitfield.
4429 * "jp->jobctl |= jobctl" likely to give awful code */
4433 jp->prev_job = curjob;
4438 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4440 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4447 * Return a string identifying a command (to be printed by the
4450 static char *cmdnextc;
4453 cmdputs(const char *s)
4455 static const char vstype[VSTYPE + 1][3] = {
4456 "", "}", "-", "+", "?", "=",
4457 "%", "%%", "#", "##"
4458 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4461 const char *p, *str;
4465 unsigned char subtype = 0;
4469 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4471 while ((c = *p++) != '\0') {
4479 if ((subtype & VSTYPE) == VSLENGTH)
4485 str = "\"}" + !(quoted & 1);
4492 #if ENABLE_FEATURE_SH_MATH
4507 if ((subtype & VSTYPE) != VSNORMAL)
4509 str = vstype[subtype & VSTYPE];
4510 if (subtype & VSNUL)
4519 /* These can only happen inside quotes */
4532 while ((c = *str++) != '\0') {
4535 } /* while *p++ not NUL */
4538 USTPUTC('"', nextc);
4544 /* cmdtxt() and cmdlist() call each other */
4545 static void cmdtxt(union node *n);
4548 cmdlist(union node *np, int sep)
4550 for (; np; np = np->narg.next) {
4554 if (sep && np->narg.next)
4560 cmdtxt(union node *n)
4563 struct nodelist *lp;
4574 lp = n->npipe.cmdlist;
4592 cmdtxt(n->nbinary.ch1);
4608 cmdtxt(n->nif.test);
4610 if (n->nif.elsepart) {
4611 cmdtxt(n->nif.ifpart);
4613 n = n->nif.elsepart;
4631 cmdtxt(n->nbinary.ch1);
4641 cmdputs(n->nfor.var);
4643 cmdlist(n->nfor.args, 1);
4648 cmdputs(n->narg.text);
4652 cmdlist(n->ncmd.args, 1);
4653 cmdlist(n->ncmd.redirect, 0);
4666 cmdputs(n->ncase.expr->narg.text);
4668 for (np = n->ncase.cases; np; np = np->nclist.next) {
4669 cmdtxt(np->nclist.pattern);
4671 cmdtxt(np->nclist.body);
4685 #if ENABLE_ASH_BASH_COMPAT
4700 cmdputs(utoa(n->nfile.fd));
4702 if (n->type == NTOFD || n->type == NFROMFD) {
4703 cmdputs(utoa(n->ndup.dupfd));
4712 commandtext(union node *n)
4716 STARTSTACKSTR(cmdnextc);
4718 name = stackblock();
4719 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4720 return ckstrdup(name);
4725 * Fork off a subshell. If we are doing job control, give the subshell its
4726 * own process group. Jp is a job structure that the job is to be added to.
4727 * N is the command that will be evaluated by the child. Both jp and n may
4728 * be NULL. The mode parameter can be one of the following:
4729 * FORK_FG - Fork off a foreground process.
4730 * FORK_BG - Fork off a background process.
4731 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4732 * process group even if job control is on.
4734 * When job control is turned off, background processes have their standard
4735 * input redirected to /dev/null (except for the second and later processes
4738 * Called with interrupts off.
4741 * Clear traps on a fork.
4749 for (tp = trap; tp < &trap[NSIG]; tp++) {
4750 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4751 if (trap_ptr == trap)
4753 /* else: it "belongs" to trap_ptr vector, don't free */
4755 if ((tp - trap) != 0)
4756 setsignal(tp - trap);
4763 /* Lives far away from here, needed for forkchild */
4764 static void closescript(void);
4766 /* Called after fork(), in child */
4767 /* jp and n are NULL when called by openhere() for heredoc support */
4768 static NOINLINE void
4769 forkchild(struct job *jp, union node *n, int mode)
4773 TRACE(("Child shell %d\n", getpid()));
4777 /* man bash: "Non-builtin commands run by bash have signal handlers
4778 * set to the values inherited by the shell from its parent".
4779 * Do we do it correctly? */
4783 if (mode == FORK_NOJOB /* is it `xxx` ? */
4784 && n && n->type == NCMD /* is it single cmd? */
4785 /* && n->ncmd.args->type == NARG - always true? */
4786 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4787 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4788 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4790 TRACE(("Trap hack\n"));
4791 /* Awful hack for `trap` or $(trap).
4793 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4794 * contains an example where "trap" is executed in a subshell:
4796 * save_traps=$(trap)
4798 * eval "$save_traps"
4800 * Standard does not say that "trap" in subshell shall print
4801 * parent shell's traps. It only says that its output
4802 * must have suitable form, but then, in the above example
4803 * (which is not supposed to be normative), it implies that.
4805 * bash (and probably other shell) does implement it
4806 * (traps are reset to defaults, but "trap" still shows them),
4807 * but as a result, "trap" logic is hopelessly messed up:
4810 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4811 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4812 * # true | trap <--- trap is in subshell - no output (ditto)
4813 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4814 * trap -- 'echo Ho' SIGWINCH
4815 * # echo `(trap)` <--- in subshell in subshell - output
4816 * trap -- 'echo Ho' SIGWINCH
4817 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4818 * trap -- 'echo Ho' SIGWINCH
4820 * The rules when to forget and when to not forget traps
4821 * get really complex and nonsensical.
4823 * Our solution: ONLY bare $(trap) or `trap` is special.
4825 /* Save trap handler strings for trap builtin to print */
4826 trap_ptr = xmemdup(trap, sizeof(trap));
4827 /* Fall through into clearing traps */
4831 /* do job control only in root shell */
4833 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4836 if (jp->nprocs == 0)
4839 pgrp = jp->ps[0].ps_pid;
4840 /* this can fail because we are doing it in the parent also */
4842 if (mode == FORK_FG)
4843 xtcsetpgrp(ttyfd, pgrp);
4848 if (mode == FORK_BG) {
4849 /* man bash: "When job control is not in effect,
4850 * asynchronous commands ignore SIGINT and SIGQUIT" */
4853 if (jp->nprocs == 0) {
4855 if (open(bb_dev_null, O_RDONLY) != 0)
4856 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4860 if (iflag) { /* why if iflag only? */
4865 * "In all cases, bash ignores SIGQUIT. Non-builtin
4866 * commands run by bash have signal handlers
4867 * set to the values inherited by the shell
4869 * Take care of the second rule: */
4873 if (n && n->type == NCMD
4874 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4876 TRACE(("Job hack\n"));
4877 /* "jobs": we do not want to clear job list for it,
4878 * instead we remove only _its_ own_ job from job list.
4879 * This makes "jobs .... | cat" more useful.
4885 for (jp = curjob; jp; jp = jp->prev_job)
4890 /* Called after fork(), in parent */
4892 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4895 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4897 TRACE(("In parent shell: child = %d\n", pid));
4899 /* jp is NULL when called by openhere() for heredoc support */
4900 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4906 if (mode != FORK_NOJOB && jp->jobctl) {
4909 if (jp->nprocs == 0)
4912 pgrp = jp->ps[0].ps_pid;
4913 /* This can fail because we are doing it in the child also */
4917 if (mode == FORK_BG) {
4918 backgndpid = pid; /* set $! */
4919 set_curjob(jp, CUR_RUNNING);
4922 struct procstat *ps = &jp->ps[jp->nprocs++];
4925 ps->ps_cmd = nullstr;
4927 if (doing_jobctl && n)
4928 ps->ps_cmd = commandtext(n);
4933 /* jp and n are NULL when called by openhere() for heredoc support */
4935 forkshell(struct job *jp, union node *n, int mode)
4939 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4942 TRACE(("Fork failed, errno=%d", errno));
4945 ash_msg_and_raise_error("can't fork");
4948 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4949 forkchild(jp, n, mode);
4951 forkparent(jp, n, mode, pid);
4957 * Wait for job to finish.
4959 * Under job control we have the problem that while a child process
4960 * is running interrupts generated by the user are sent to the child
4961 * but not to the shell. This means that an infinite loop started by
4962 * an interactive user may be hard to kill. With job control turned off,
4963 * an interactive user may place an interactive program inside a loop.
4964 * If the interactive program catches interrupts, the user doesn't want
4965 * these interrupts to also abort the loop. The approach we take here
4966 * is to have the shell ignore interrupt signals while waiting for a
4967 * foreground process to terminate, and then send itself an interrupt
4968 * signal if the child process was terminated by an interrupt signal.
4969 * Unfortunately, some programs want to do a bit of cleanup and then
4970 * exit on interrupt; unless these processes terminate themselves by
4971 * sending a signal to themselves (instead of calling exit) they will
4972 * confuse this approach.
4974 * Called with interrupts off.
4977 waitforjob(struct job *jp)
4981 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4984 while (jp->state == JOBRUNNING) {
4985 /* In non-interactive shells, we _can_ get
4986 * a keyboard signal here and be EINTRed,
4987 * but we just loop back, waiting for command to complete.
4990 * "If bash is waiting for a command to complete and receives
4991 * a signal for which a trap has been set, the trap
4992 * will not be executed until the command completes."
4994 * Reality is that even if trap is not set, bash
4995 * will not act on the signal until command completes.
4996 * Try this. sleep5intoff.c:
4997 * #include <signal.h>
4998 * #include <unistd.h>
5001 * sigemptyset(&set);
5002 * sigaddset(&set, SIGINT);
5003 * sigaddset(&set, SIGQUIT);
5004 * sigprocmask(SIG_BLOCK, &set, NULL);
5008 * $ bash -c './sleep5intoff; echo hi'
5009 * ^C^C^C^C <--- pressing ^C once a second
5011 * $ bash -c './sleep5intoff; echo hi'
5012 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5015 dowait(DOWAIT_BLOCK, jp);
5022 xtcsetpgrp(ttyfd, rootpid);
5024 * This is truly gross.
5025 * If we're doing job control, then we did a TIOCSPGRP which
5026 * caused us (the shell) to no longer be in the controlling
5027 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5028 * intuit from the subprocess exit status whether a SIGINT
5029 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5031 if (jp->sigint) /* TODO: do the same with all signals */
5032 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5034 if (jp->state == JOBDONE)
5041 * return 1 if there are stopped jobs, otherwise 0
5053 if (jp && jp->state == JOBSTOPPED) {
5054 out2str("You have stopped jobs.\n");
5064 * Code for dealing with input/output redirection.
5069 #define EMPTY -2 /* marks an unused slot in redirtab */
5070 #define CLOSED -3 /* marks a slot of previously-closed fd */
5073 * Open a file in noclobber mode.
5074 * The code was copied from bash.
5077 noclobberopen(const char *fname)
5080 struct stat finfo, finfo2;
5083 * If the file exists and is a regular file, return an error
5086 r = stat(fname, &finfo);
5087 if (r == 0 && S_ISREG(finfo.st_mode)) {
5093 * If the file was not present (r != 0), make sure we open it
5094 * exclusively so that if it is created before we open it, our open
5095 * will fail. Make sure that we do not truncate an existing file.
5096 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5097 * file was not a regular file, we leave O_EXCL off.
5100 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5101 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5103 /* If the open failed, return the file descriptor right away. */
5108 * OK, the open succeeded, but the file may have been changed from a
5109 * non-regular file to a regular file between the stat and the open.
5110 * We are assuming that the O_EXCL open handles the case where FILENAME
5111 * did not exist and is symlinked to an existing file between the stat
5116 * If we can open it and fstat the file descriptor, and neither check
5117 * revealed that it was a regular file, and the file has not been
5118 * replaced, return the file descriptor.
5120 if (fstat(fd, &finfo2) == 0
5121 && !S_ISREG(finfo2.st_mode)
5122 && finfo.st_dev == finfo2.st_dev
5123 && finfo.st_ino == finfo2.st_ino
5128 /* The file has been replaced. badness. */
5135 * Handle here documents. Normally we fork off a process to write the
5136 * data to a pipe. If the document is short, we can stuff the data in
5137 * the pipe without forking.
5139 /* openhere needs this forward reference */
5140 static void expandhere(union node *arg, int fd);
5142 openhere(union node *redir)
5148 ash_msg_and_raise_error("pipe call failed");
5149 if (redir->type == NHERE) {
5150 len = strlen(redir->nhere.doc->narg.text);
5151 if (len <= PIPE_BUF) {
5152 full_write(pip[1], redir->nhere.doc->narg.text, len);
5156 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5159 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5160 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5161 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5162 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5163 signal(SIGPIPE, SIG_DFL);
5164 if (redir->type == NHERE)
5165 full_write(pip[1], redir->nhere.doc->narg.text, len);
5167 expandhere(redir->nhere.doc, pip[1]);
5168 _exit(EXIT_SUCCESS);
5176 openredirect(union node *redir)
5181 switch (redir->nfile.type) {
5182 /* Can't happen, our single caller does this itself */
5188 return openhere(redir);
5191 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5192 * allocated space. Do it only when we know it is safe.
5194 fname = redir->nfile.expfname;
5196 switch (redir->nfile.type) {
5202 f = open(fname, O_RDONLY);
5207 f = open(fname, O_RDWR|O_CREAT, 0666);
5212 #if ENABLE_ASH_BASH_COMPAT
5215 /* Take care of noclobber mode. */
5217 f = noclobberopen(fname);
5224 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5229 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5237 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5239 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5243 * Copy a file descriptor to be >= 10. Throws exception on error.
5251 newfd = fcntl(from, F_DUPFD, 10);
5252 err = newfd < 0 ? errno : 0;
5255 ash_msg_and_raise_error("%d: %m", from);
5257 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5263 dup2_or_raise(int from, int to)
5267 newfd = (from != to) ? dup2(from, to) : to;
5269 /* Happens when source fd is not open: try "echo >&99" */
5270 ash_msg_and_raise_error("%d: %m", from);
5275 /* Struct def and variable are moved down to the first usage site */
5280 struct redirtab *next;
5282 struct two_fd_t two_fd[];
5284 #define redirlist (G_var.redirlist)
5286 COPYFD_RESTORE = (int)~(INT_MAX),
5290 need_to_remember(struct redirtab *rp, int fd)
5294 if (!rp) /* remembering was not requested */
5297 for (i = 0; i < rp->pair_count; i++) {
5298 if (rp->two_fd[i].orig == fd) {
5299 /* already remembered */
5306 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5308 is_hidden_fd(struct redirtab *rp, int fd)
5311 struct parsefile *pf;
5315 /* Check open scripts' fds */
5318 /* We skip pf_fd == 0 case because of the following case:
5319 * $ ash # running ash interactively
5321 * and in script.sh: "exec 9>&0".
5322 * Even though top-level pf_fd _is_ 0,
5323 * it's still ok to use it: "read" builtin uses it,
5324 * why should we cripple "exec" builtin?
5326 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5334 /* Check saved fds of redirects */
5335 fd |= COPYFD_RESTORE;
5336 for (i = 0; i < rp->pair_count; i++) {
5337 if (rp->two_fd[i].copy == fd) {
5345 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5346 * old file descriptors are stashed away so that the redirection can be
5347 * undone by calling popredir.
5349 /* flags passed to redirect */
5350 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5351 #define REDIR_SAVEFD2 03 /* set preverrout */
5353 redirect(union node *redir, int flags)
5355 struct redirtab *sv;
5360 int copied_fd2 = -1;
5369 if (flags & REDIR_PUSH) {
5370 union node *tmp = redir;
5373 #if ENABLE_ASH_BASH_COMPAT
5374 if (tmp->nfile.type == NTO2)
5377 tmp = tmp->nfile.next;
5379 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5380 sv->next = redirlist;
5381 sv->pair_count = sv_pos;
5383 while (sv_pos > 0) {
5385 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5391 fd = redir->nfile.fd;
5392 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5393 right_fd = redir->ndup.dupfd;
5394 //bb_error_msg("doing %d > %d", fd, right_fd);
5395 /* redirect from/to same file descriptor? */
5398 /* "echo >&10" and 10 is a fd opened to a sh script? */
5399 if (is_hidden_fd(sv, right_fd)) {
5400 errno = EBADF; /* as if it is closed */
5401 ash_msg_and_raise_error("%d: %m", right_fd);
5405 newfd = openredirect(redir); /* always >= 0 */
5407 /* Descriptor wasn't open before redirect.
5408 * Mark it for close in the future */
5409 if (need_to_remember(sv, fd)) {
5410 goto remember_to_close;
5415 #if ENABLE_ASH_BASH_COMPAT
5418 if (need_to_remember(sv, fd)) {
5419 /* Copy old descriptor */
5420 /* Careful to not accidentally "save"
5421 * to the same fd as right side fd in N>&M */
5422 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5423 #if defined(F_DUPFD_CLOEXEC)
5424 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5426 i = fcntl(fd, F_DUPFD, minfd);
5431 /* Strange error (e.g. "too many files" EMFILE?) */
5435 ash_msg_and_raise_error("%d: %m", fd);
5438 /* EBADF: it is not open - good, remember to close it */
5441 } else { /* fd is open, save its copy */
5442 #if !defined(F_DUPFD_CLOEXEC)
5443 fcntl(i, F_SETFD, FD_CLOEXEC);
5445 /* "exec fd>&-" should not close fds
5446 * which point to script file(s).
5447 * Force them to be restored afterwards */
5448 if (is_hidden_fd(sv, fd))
5449 i |= COPYFD_RESTORE;
5453 sv->two_fd[sv_pos].orig = fd;
5454 sv->two_fd[sv_pos].copy = i;
5458 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5459 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5460 /* Don't want to trigger debugging */
5464 dup2_or_raise(redir->ndup.dupfd, fd);
5466 } else if (fd != newfd) { /* move newfd to fd */
5467 dup2_or_raise(newfd, fd);
5468 #if ENABLE_ASH_BASH_COMPAT
5469 if (!(redir->nfile.type == NTO2 && fd == 2))
5473 #if ENABLE_ASH_BASH_COMPAT
5474 if (redir->nfile.type == NTO2 && fd == 1) {
5475 /* We already redirected it to fd 1, now copy it to 2 */
5481 } while ((redir = redir->nfile.next) != NULL);
5484 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5485 preverrout_fd = copied_fd2;
5489 * Undo the effects of the last redirection.
5492 popredir(int drop, int restore)
5494 struct redirtab *rp;
5497 if (redirlist == NULL)
5501 for (i = 0; i < rp->pair_count; i++) {
5502 int fd = rp->two_fd[i].orig;
5503 int copy = rp->two_fd[i].copy;
5504 if (copy == CLOSED) {
5509 if (copy != EMPTY) {
5510 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5511 copy &= ~COPYFD_RESTORE;
5513 dup2_or_raise(copy, fd);
5515 close(copy & ~COPYFD_RESTORE);
5518 redirlist = rp->next;
5524 * Undo all redirections. Called on error or interrupt.
5528 redirectsafe(union node *redir, int flags)
5531 volatile int saveint;
5532 struct jmploc *volatile savehandler = exception_handler;
5533 struct jmploc jmploc;
5536 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5537 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5539 exception_handler = &jmploc;
5540 redirect(redir, flags);
5542 exception_handler = savehandler;
5543 if (err && exception_type != EXERROR)
5544 longjmp(exception_handler->loc, 1);
5545 RESTORE_INT(saveint);
5550 /* ============ Routines to expand arguments to commands
5552 * We have to deal with backquotes, shell variables, and file metacharacters.
5555 #if ENABLE_FEATURE_SH_MATH
5557 ash_arith(const char *s)
5559 arith_state_t math_state;
5562 math_state.lookupvar = lookupvar;
5563 math_state.setvar = setvar0;
5564 //math_state.endofname = endofname;
5567 result = arith(&math_state, s);
5568 if (math_state.errmsg)
5569 ash_msg_and_raise_error(math_state.errmsg);
5579 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5580 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5581 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5582 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5583 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5584 * POSIX says for this case:
5585 * Pathname expansion shall not be performed on the word by a
5586 * non-interactive shell; an interactive shell may perform it, but shall
5587 * do so only when the expansion would result in one word.
5588 * Currently, our code complies to the above rule by never globbing
5589 * redirection filenames.
5590 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5591 * (this means that on a typical Linux distro, bash almost always
5592 * performs globbing, and thus diverges from what we do).
5594 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5595 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5596 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5597 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5598 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5602 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5603 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5604 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5605 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5606 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5608 /* Add CTLESC when necessary. */
5609 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5610 /* Do not skip NUL characters. */
5611 #define QUOTES_KEEPNUL EXP_TILDE
5614 * Structure specifying which parts of the string should be searched
5615 * for IFS characters.
5618 struct ifsregion *next; /* next region in list */
5619 int begoff; /* offset of start of region */
5620 int endoff; /* offset of end of region */
5621 int nulonly; /* search for nul bytes only */
5625 struct strlist *list;
5626 struct strlist **lastp;
5629 /* output of current string */
5630 static char *expdest;
5631 /* list of back quote expressions */
5632 static struct nodelist *argbackq;
5633 /* first struct in list of ifs regions */
5634 static struct ifsregion ifsfirst;
5635 /* last struct in list */
5636 static struct ifsregion *ifslastp;
5637 /* holds expanded arg list */
5638 static struct arglist exparg;
5643 #if !ENABLE_FEATURE_SH_MATH
5644 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5645 typedef long arith_t;
5646 # define ARITH_FMT "%ld"
5653 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5654 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5655 STADJUST(len, expdest);
5660 * Break the argument string into pieces based upon IFS and add the
5661 * strings to the argument list. The regions of the string to be
5662 * searched for IFS characters have been stored by recordregion.
5665 ifsbreakup(char *string, struct arglist *arglist)
5667 struct ifsregion *ifsp;
5672 const char *ifs, *realifs;
5677 if (ifslastp != NULL) {
5680 realifs = ifsset() ? ifsval() : defifs;
5683 p = string + ifsp->begoff;
5684 nulonly = ifsp->nulonly;
5685 ifs = nulonly ? nullstr : realifs;
5687 while (p < string + ifsp->endoff) {
5689 if ((unsigned char)*p == CTLESC)
5691 if (!strchr(ifs, *p)) {
5696 ifsspc = (strchr(defifs, *p) != NULL);
5697 /* Ignore IFS whitespace at start */
5698 if (q == start && ifsspc) {
5704 sp = stzalloc(sizeof(*sp));
5706 *arglist->lastp = sp;
5707 arglist->lastp = &sp->next;
5711 if (p >= string + ifsp->endoff) {
5715 if ((unsigned char)*p == CTLESC)
5717 if (strchr(ifs, *p) == NULL) {
5721 if (strchr(defifs, *p) == NULL) {
5736 } while (ifsp != NULL);
5745 sp = stzalloc(sizeof(*sp));
5747 *arglist->lastp = sp;
5748 arglist->lastp = &sp->next;
5754 struct ifsregion *p = ifsfirst.next;
5761 struct ifsregion *ifsp;
5766 ifsfirst.next = NULL;
5773 esclen(const char *start, const char *p)
5777 while (p > start && (unsigned char)*--p == CTLESC) {
5784 * Remove any CTLESC characters from a string.
5787 rmescapes(char *str, int flag)
5789 static const char qchars[] ALIGN1 = {
5790 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5794 unsigned protect_against_glob;
5796 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5798 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5804 if (flag & RMESCAPE_ALLOC) {
5805 size_t len = p - str;
5806 size_t fulllen = len + strlen(p) + 1;
5808 if (flag & RMESCAPE_GROW) {
5809 int strloc = str - (char *)stackblock();
5810 r = makestrspace(fulllen, expdest);
5811 /* p and str may be invalidated by makestrspace */
5812 str = (char *)stackblock() + strloc;
5814 } else if (flag & RMESCAPE_HEAP) {
5815 r = ckmalloc(fulllen);
5817 r = stalloc(fulllen);
5821 q = (char *)memcpy(q, str, len) + len;
5826 globbing = flag & RMESCAPE_GLOB;
5827 protect_against_glob = globbing;
5829 if ((unsigned char)*p == CTLQUOTEMARK) {
5830 // Note: both inquotes and protect_against_glob only affect whether
5831 inquotes = ~inquotes;
5833 protect_against_glob = globbing;
5836 if ((unsigned char)*p == CTLESC) {
5840 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5842 if (protect_against_glob) {
5845 } else if (*p == '\\' && !inquotes) {
5846 /* naked back slash */
5847 protect_against_glob = 0;
5850 #if ENABLE_ASH_BASH_COMPAT
5851 else if (*p == '/' && slash) {
5852 /* stop handling globbing and mark location of slash */
5853 globbing = slash = 0;
5857 protect_against_glob = globbing;
5862 if (flag & RMESCAPE_GROW) {
5864 STADJUST(q - r + 1, expdest);
5868 #define pmatch(a, b) !fnmatch((a), (b), 0)
5871 * Prepare a pattern for a expmeta (internal glob(3)) call.
5873 * Returns an stalloced string.
5876 preglob(const char *pattern, int flag)
5878 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5882 * Put a string on the stack.
5885 memtodest(const char *p, size_t len, int syntax, int quotes)
5892 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5895 unsigned char c = *p++;
5897 if (quotes & QUOTES_ESC) {
5898 int n = SIT(c, syntax);
5900 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5907 } else if (!(quotes & QUOTES_KEEPNUL))
5916 strtodest(const char *p, int syntax, int quotes)
5918 size_t len = strlen(p);
5919 memtodest(p, len, syntax, quotes);
5924 * Record the fact that we have to scan this region of the
5925 * string for IFS characters.
5928 recordregion(int start, int end, int nulonly)
5930 struct ifsregion *ifsp;
5932 if (ifslastp == NULL) {
5936 ifsp = ckzalloc(sizeof(*ifsp));
5937 /*ifsp->next = NULL; - ckzalloc did it */
5938 ifslastp->next = ifsp;
5942 ifslastp->begoff = start;
5943 ifslastp->endoff = end;
5944 ifslastp->nulonly = nulonly;
5948 removerecordregions(int endoff)
5950 if (ifslastp == NULL)
5953 if (ifsfirst.endoff > endoff) {
5954 while (ifsfirst.next) {
5955 struct ifsregion *ifsp;
5957 ifsp = ifsfirst.next->next;
5958 free(ifsfirst.next);
5959 ifsfirst.next = ifsp;
5962 if (ifsfirst.begoff > endoff) {
5965 ifslastp = &ifsfirst;
5966 ifsfirst.endoff = endoff;
5971 ifslastp = &ifsfirst;
5972 while (ifslastp->next && ifslastp->next->begoff < endoff)
5973 ifslastp = ifslastp->next;
5974 while (ifslastp->next) {
5975 struct ifsregion *ifsp;
5977 ifsp = ifslastp->next->next;
5978 free(ifslastp->next);
5979 ifslastp->next = ifsp;
5982 if (ifslastp->endoff > endoff)
5983 ifslastp->endoff = endoff;
5987 exptilde(char *startp, char *p, int flags)
5993 int quotes = flags & QUOTES_ESC;
5997 while ((c = *++p) != '\0') {
6004 if (flags & EXP_VARTILDE)
6014 if (*name == '\0') {
6015 home = lookupvar("HOME");
6017 pw = getpwnam(name);
6022 if (!home || !*home)
6025 strtodest(home, SQSYNTAX, quotes);
6033 * Execute a command inside back quotes. If it's a builtin command, we
6034 * want to save its output in a block obtained from malloc. Otherwise
6035 * we fork off a subprocess and get the output of the command via a pipe.
6036 * Should be called with interrupts off.
6038 struct backcmd { /* result of evalbackcmd */
6039 int fd; /* file descriptor to read from */
6040 int nleft; /* number of chars in buffer */
6041 char *buf; /* buffer */
6042 struct job *jp; /* job structure for command */
6045 /* These forward decls are needed to use "eval" code for backticks handling: */
6046 #define EV_EXIT 01 /* exit after evaluating tree */
6047 static int evaltree(union node *, int);
6049 static void FAST_FUNC
6050 evalbackcmd(union node *n, struct backcmd *result)
6064 ash_msg_and_raise_error("pipe call failed");
6065 jp = makejob(/*n,*/ 1);
6066 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6072 dup2_or_raise(pip[1], 1);
6075 /* TODO: eflag clearing makes the following not abort:
6076 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6077 * which is what bash does (unless it is in POSIX mode).
6078 * dash deleted "eflag = 0" line in the commit
6079 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6080 * [EVAL] Don't clear eflag in evalbackcmd
6081 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6085 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6090 result->fd = pip[0];
6094 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6095 result->fd, result->buf, result->nleft, result->jp));
6099 * Expand stuff in backwards quotes.
6102 expbackq(union node *cmd, int flag)
6110 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6111 struct stackmark smark;
6114 startloc = expdest - (char *)stackblock();
6115 pushstackmark(&smark, startloc);
6116 evalbackcmd(cmd, &in);
6117 popstackmark(&smark);
6124 memtodest(p, i, syntax, flag & QUOTES_ESC);
6128 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6129 TRACE(("expbackq: read returns %d\n", i));
6138 back_exitstatus = waitforjob(in.jp);
6142 /* Eat all trailing newlines */
6144 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6148 if (!(flag & EXP_QUOTED))
6149 recordregion(startloc, dest - (char *)stackblock(), 0);
6150 TRACE(("evalbackq: size:%d:'%.*s'\n",
6151 (int)((dest - (char *)stackblock()) - startloc),
6152 (int)((dest - (char *)stackblock()) - startloc),
6153 stackblock() + startloc));
6156 #if ENABLE_FEATURE_SH_MATH
6158 * Expand arithmetic expression. Backup to start of expression,
6159 * evaluate, place result in (backed up) result, adjust string position.
6171 * This routine is slightly over-complicated for
6172 * efficiency. Next we scan backwards looking for the
6173 * start of arithmetic.
6175 start = stackblock();
6182 while ((unsigned char)*p != CTLARI) {
6186 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6191 esc = esclen(start, p);
6201 removerecordregions(begoff);
6205 if (flag & QUOTES_ESC)
6206 rmescapes(p + 1, 0);
6208 len = cvtnum(ash_arith(p + 1));
6210 if (!(flag & EXP_QUOTED))
6211 recordregion(begoff, begoff + len, 0);
6215 /* argstr needs it */
6216 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6219 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6220 * characters to allow for further processing. Otherwise treat
6221 * $@ like $* since no splitting will be performed.
6223 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6224 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6225 * for correct expansion of "B=$A" word.
6228 argstr(char *p, int flags, struct strlist *var_str_list)
6230 static const char spclchars[] ALIGN1 = {
6238 #if ENABLE_FEATURE_SH_MATH
6243 const char *reject = spclchars;
6244 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6249 if (!(flags & EXP_VARTILDE)) {
6251 } else if (flags & EXP_VARTILDE2) {
6256 if (flags & EXP_TILDE) {
6259 flags &= ~EXP_TILDE;
6263 p = exptilde(p, q, flags);
6266 startloc = expdest - (char *)stackblock();
6270 length += strcspn(p + length, reject);
6274 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6276 /* c == '=' || c == ':' || c == CTLENDARI */
6282 expdest = stack_nputstr(p, length, expdest);
6283 newloc = expdest - (char *)stackblock();
6284 if (breakall && !inquotes && newloc > startloc) {
6285 recordregion(startloc, newloc, 0);
6296 if (flags & EXP_VARTILDE2) {
6300 flags |= EXP_VARTILDE2;
6305 * sort of a hack - expand tildes in variable
6306 * assignments (after the first '=' and after ':'s).
6315 case CTLENDVAR: /* ??? */
6318 inquotes ^= EXP_QUOTED;
6319 /* "$@" syntax adherence hack */
6320 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6321 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6325 if (flags & QUOTES_ESC) {
6336 * Quoted parameter expansion pattern: remove quote
6337 * unless inside inner quotes or we have a literal
6340 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6341 EXP_QPAT && *p != '\\')
6346 TRACE(("argstr: evalvar('%s')\n", p));
6347 p = evalvar(p, flags | inquotes, var_str_list);
6348 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6351 expbackq(argbackq->n, flags | inquotes);
6352 argbackq = argbackq->next;
6354 #if ENABLE_FEATURE_SH_MATH
6357 expari(flags | inquotes);
6366 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6367 char *pattern, int quotes, int zero)
6376 const char *s = loc2;
6383 match = pmatch(pattern, s);
6388 if (quotes && (unsigned char)*loc == CTLESC)
6397 scanright(char *startp, char *rmesc, char *rmescend,
6398 char *pattern, int quotes, int match_at_start)
6400 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6401 int try2optimize = match_at_start;
6407 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6408 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6409 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6411 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6412 * and on each iteration they go back two/one char until they reach the beginning.
6413 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6415 /* TODO: document in what other circumstances we are called. */
6417 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6420 const char *s = loc2;
6421 if (match_at_start) {
6425 match = pmatch(pattern, s);
6426 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6430 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6432 /* Maybe we can optimize this:
6433 * if pattern ends with unescaped *, we can avoid checking
6434 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6435 * it wont match truncated "raw_value_of_" strings too.
6437 unsigned plen = strlen(pattern);
6438 /* Does it end with "*"? */
6439 if (plen != 0 && pattern[--plen] == '*') {
6440 /* "xxxx*" is not escaped */
6441 /* "xxx\*" is escaped */
6442 /* "xx\\*" is not escaped */
6443 /* "x\\\*" is escaped */
6445 while (plen != 0 && pattern[--plen] == '\\')
6448 break; /* ends with unescaped "*" */
6456 esc = esclen(startp, loc);
6467 static void varunset(const char *, const char *, const char *, int) NORETURN;
6469 varunset(const char *end, const char *var, const char *umsg, int varflags)
6475 msg = "parameter not set";
6477 if ((unsigned char)*end == CTLENDVAR) {
6478 if (varflags & VSNUL)
6484 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6488 subevalvar(char *p, char *varname, int strloc, int subtype,
6489 int startloc, int varflags, int flag, struct strlist *var_str_list)
6491 struct nodelist *saveargbackq = argbackq;
6492 int quotes = flag & QUOTES_ESC;
6495 char *rmesc, *rmescend;
6497 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6498 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6499 int amount, resetloc;
6500 IF_ASH_BASH_COMPAT(int workloc;)
6502 char *(*scan)(char*, char*, char*, char*, int, int);
6504 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6505 // p, varname, strloc, subtype, startloc, varflags, quotes);
6507 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6508 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6510 STPUTC('\0', expdest);
6511 argbackq = saveargbackq;
6512 startp = (char *)stackblock() + startloc;
6516 setvar0(varname, startp);
6517 amount = startp - expdest;
6518 STADJUST(amount, expdest);
6522 varunset(p, varname, startp, varflags);
6525 #if ENABLE_ASH_BASH_COMPAT
6527 //TODO: support more general format ${v:EXPR:EXPR},
6528 // where EXPR follows $(()) rules
6529 loc = str = stackblock() + strloc;
6530 /* Read POS in ${var:POS:LEN} */
6531 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6532 len = str - startp - 1;
6534 /* *loc != '\0', guaranteed by parser */
6538 /* Adjust the length by the number of escapes */
6539 for (ptr = startp; ptr < (str - 1); ptr++) {
6540 if ((unsigned char)*ptr == CTLESC) {
6548 if (*loc++ == ':') {
6552 /* Skip POS in ${var:POS:LEN} */
6554 while (*loc && *loc != ':') {
6556 * bash complains on: var=qwe; echo ${var:1a:123}
6558 ash_msg_and_raise_error(msg_illnum, str);
6562 if (*loc++ == ':') {
6567 /* ${VAR:$((-n)):l} starts n chars from the end */
6568 pos = orig_len + pos;
6570 if ((unsigned)pos >= orig_len) {
6571 /* apart from obvious ${VAR:999999:l},
6572 * covers ${VAR:$((-9999999)):l} - result is ""
6578 if (len > (orig_len - pos))
6579 len = orig_len - pos;
6581 for (str = startp; pos; str++, pos--) {
6582 if (quotes && (unsigned char)*str == CTLESC)
6585 for (loc = startp; len; len--) {
6586 if (quotes && (unsigned char)*str == CTLESC)
6591 amount = loc - expdest;
6592 STADJUST(amount, expdest);
6597 resetloc = expdest - (char *)stackblock();
6599 /* We'll comeback here if we grow the stack while handling
6600 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6601 * stack will need rebasing, and we'll need to remove our work
6604 IF_ASH_BASH_COMPAT(restart:)
6606 amount = expdest - ((char *)stackblock() + resetloc);
6607 STADJUST(-amount, expdest);
6608 startp = (char *)stackblock() + startloc;
6611 rmescend = (char *)stackblock() + strloc;
6613 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6614 if (rmesc != startp) {
6616 startp = (char *)stackblock() + startloc;
6620 str = (char *)stackblock() + strloc;
6622 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6623 * The result is a_\_z_c (not a\_\_z_c)!
6625 * The search pattern and replace string treat backslashes differently!
6626 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6627 * and string. It's only used on the first call.
6629 preglob(str, IF_ASH_BASH_COMPAT(
6630 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6631 RMESCAPE_SLASH :) 0);
6633 #if ENABLE_ASH_BASH_COMPAT
6634 workloc = expdest - (char *)stackblock();
6635 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6639 repl = strchr(str, CTLESC);
6645 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6647 /* If there's no pattern to match, return the expansion unmolested */
6656 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6657 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6659 /* No match, advance */
6660 char *restart_detect = stackblock();
6662 STPUTC(*idx, expdest);
6663 if (quotes && (unsigned char)*idx == CTLESC) {
6666 STPUTC(*idx, expdest);
6668 if (stackblock() != restart_detect)
6673 /* continue; - prone to quadratic behavior, smarter code: */
6676 if (str[0] == '*') {
6677 /* Pattern is "*foo". If "*foo" does not match "long_string",
6678 * it would never match "ong_string" etc, no point in trying.
6685 if (subtype == VSREPLACEALL) {
6687 if (quotes && (unsigned char)*idx == CTLESC)
6696 //bb_error_msg("repl:'%s'", repl);
6697 for (loc = (char*)repl; *loc; loc++) {
6698 char *restart_detect = stackblock();
6699 if (quotes && *loc == '\\') {
6700 STPUTC(CTLESC, expdest);
6703 STPUTC(*loc, expdest);
6704 if (stackblock() != restart_detect)
6709 if (subtype == VSREPLACE) {
6710 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6712 char *restart_detect = stackblock();
6713 STPUTC(*idx, expdest);
6714 if (stackblock() != restart_detect)
6723 /* We've put the replaced text into a buffer at workloc, now
6724 * move it to the right place and adjust the stack.
6726 STPUTC('\0', expdest);
6727 startp = (char *)stackblock() + startloc;
6728 memmove(startp, (char *)stackblock() + workloc, len + 1);
6729 //bb_error_msg("startp:'%s'", startp);
6730 amount = expdest - (startp + len);
6731 STADJUST(-amount, expdest);
6734 #endif /* ENABLE_ASH_BASH_COMPAT */
6736 subtype -= VSTRIMRIGHT;
6738 if (subtype < 0 || subtype > 7)
6741 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6742 zero = subtype >> 1;
6743 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6744 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6746 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6749 memmove(startp, loc, str - loc);
6750 loc = startp + (str - loc) - 1;
6753 amount = loc - expdest;
6754 STADJUST(amount, expdest);
6760 * Add the value of a specialized variable to the stack string.
6761 * name parameter (examples):
6762 * ash -c 'echo $1' name:'1='
6763 * ash -c 'echo $qwe' name:'qwe='
6764 * ash -c 'echo $$' name:'$='
6765 * ash -c 'echo ${$}' name:'$='
6766 * ash -c 'echo ${$##q}' name:'$=q'
6767 * ash -c 'echo ${#$}' name:'$='
6768 * note: examples with bad shell syntax:
6769 * ash -c 'echo ${#$1}' name:'$=1'
6770 * ash -c 'echo ${#1#}' name:'1=#'
6772 static NOINLINE ssize_t
6773 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6780 int quoted = *quotedp;
6781 int subtype = varflags & VSTYPE;
6782 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6783 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6786 sep = (flags & EXP_FULL) << CHAR_BIT;
6787 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6797 num = shellparam.nparam;
6805 goto check_1char_name;
6807 expdest = makestrspace(NOPTS, expdest);
6808 for (i = NOPTS - 1; i >= 0; i--) {
6810 USTPUTC(optletters(i), expdest);
6816 /* handles cases similar to ${#$1} */
6817 if (name[2] != '\0')
6818 raise_error_syntax("bad substitution");
6831 sep |= ifsset() ? ifsval()[0] : ' ';
6838 while ((p = *ap++) != NULL) {
6839 len += strtodest(p, syntax, quotes);
6843 memtodest(&sepc, 1, syntax, quotes);
6858 num = atoi(name); /* number(name) fails on ${N#str} etc */
6859 if (num < 0 || num > shellparam.nparam)
6861 p = num ? shellparam.p[num - 1] : arg0;
6864 /* NB: name has form "VAR=..." */
6866 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6867 * which should be considered before we check variables. */
6869 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6873 str = var_str_list->text;
6874 eq = strchr(str, '=');
6875 if (!eq) /* stop at first non-assignment */
6878 if (name_len == (unsigned)(eq - str)
6879 && strncmp(str, name, name_len) == 0
6882 /* goto value; - WRONG! */
6883 /* think "A=1 A=2 B=$A" */
6885 var_str_list = var_str_list->next;
6886 } while (var_str_list);
6890 p = lookupvar(name);
6895 len = strtodest(p, syntax, quotes);
6896 #if ENABLE_UNICODE_SUPPORT
6897 if (subtype == VSLENGTH && len > 0) {
6898 reinit_unicode_for_ash();
6899 if (unicode_status == UNICODE_ON) {
6900 STADJUST(-len, expdest);
6902 len = unicode_strlen(p);
6910 STADJUST(-len, expdest);
6915 * Expand a variable, and return a pointer to the next character in the
6919 evalvar(char *p, int flag, struct strlist *var_str_list)
6930 varflags = (unsigned char) *p++;
6931 subtype = varflags & VSTYPE;
6934 raise_error_syntax("bad substitution");
6936 quoted = flag & EXP_QUOTED;
6938 easy = (!quoted || (*var == '@' && shellparam.nparam));
6939 startloc = expdest - (char *)stackblock();
6940 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6943 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6944 if (varflags & VSNUL)
6947 if (subtype == VSPLUS) {
6948 varlen = -1 - varlen;
6952 if (subtype == VSMINUS) {
6957 flag | EXP_TILDE | EXP_WORD,
6965 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6969 subevalvar(p, var, 0, subtype, startloc, varflags,
6970 flag & ~QUOTES_ESC, var_str_list);
6973 * Remove any recorded regions beyond
6976 removerecordregions(startloc);
6980 if (varlen < 0 && uflag)
6981 varunset(p, var, 0, 0);
6983 if (subtype == VSLENGTH) {
6984 cvtnum(varlen > 0 ? varlen : 0);
6988 if (subtype == VSNORMAL) {
6992 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7001 case VSTRIMRIGHTMAX:
7002 #if ENABLE_ASH_BASH_COMPAT
7015 * Terminate the string and start recording the pattern
7018 STPUTC('\0', expdest);
7019 patloc = expdest - (char *)stackblock();
7020 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7021 startloc, varflags, flag, var_str_list)) {
7022 int amount = expdest - (
7023 (char *)stackblock() + patloc - 1
7025 STADJUST(-amount, expdest);
7027 /* Remove any recorded regions beyond start of variable */
7028 removerecordregions(startloc);
7033 if (subtype != VSNORMAL) { /* skip to end of alternative */
7036 unsigned char c = *p++;
7039 else if (c == CTLBACKQ) {
7041 argbackq = argbackq->next;
7042 } else if (c == CTLVAR) {
7043 if ((*p++ & VSTYPE) != VSNORMAL)
7045 } else if (c == CTLENDVAR) {
7055 * Add a file name to the list.
7058 addfname(const char *name)
7062 sp = stzalloc(sizeof(*sp));
7063 sp->text = sstrdup(name);
7065 exparg.lastp = &sp->next;
7068 /* If we want to use glob() from libc... */
7069 #if !ENABLE_ASH_INTERNAL_GLOB
7071 /* Add the result of glob() to the list */
7073 addglob(const glob_t *pglob)
7075 char **p = pglob->gl_pathv;
7082 expandmeta(struct strlist *str /*, int flag*/)
7084 /* TODO - EXP_REDIR */
7094 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7109 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7110 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7111 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7113 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7114 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7115 // Which means you need to unescape the string, right? Not so fast:
7116 // if there _is_ a file named "file\?" (with backslash), it is returned
7117 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7118 // You DONT KNOW by looking at the result whether you need to unescape it.
7120 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7121 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7122 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7123 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7124 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7125 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7126 i = glob(p, 0, NULL, &pglob);
7127 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7132 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7133 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7134 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7146 *exparg.lastp = str;
7147 rmescapes(str->text, 0);
7148 exparg.lastp = &str->next;
7150 default: /* GLOB_NOSPACE */
7153 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7160 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7163 * Do metacharacter (i.e. *, ?, [...]) expansion.
7166 expmeta(char *expdir, char *enddir, char *name)
7182 for (p = name; esc = 0, *p; p += esc + 1) {
7183 if (*p == '*' || *p == '?')
7185 else if (*p == '[') {
7192 if (*q == '/' || *q == '\0')
7202 if (p[esc] == '/') {
7205 start = p + esc + 1;
7209 if (metaflag == 0) { /* we've reached the end of the file name */
7210 if (enddir != expdir)
7218 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7229 } while (p < start);
7231 if (enddir == expdir) {
7233 } else if (enddir == expdir + 1 && *expdir == '/') {
7242 if (enddir != expdir)
7244 if (*endname == 0) {
7257 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7258 if (dp->d_name[0] == '.' && !matchdot)
7260 if (pmatch(start, dp->d_name)) {
7262 strcpy(enddir, dp->d_name);
7265 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7268 expmeta(expdir, p, endname);
7274 endname[-esc - 1] = esc ? '\\' : '/';
7277 static struct strlist *
7278 msort(struct strlist *list, int len)
7280 struct strlist *p, *q = NULL;
7281 struct strlist **lpp;
7289 for (n = half; --n >= 0;) {
7293 q->next = NULL; /* terminate first half of list */
7294 q = msort(list, half); /* sort first half of list */
7295 p = msort(p, len - half); /* sort second half */
7298 #if ENABLE_LOCALE_SUPPORT
7299 if (strcoll(p->text, q->text) < 0)
7301 if (strcmp(p->text, q->text) < 0)
7325 * Sort the results of file name expansion. It calculates the number of
7326 * strings to sort and then calls msort (short for merge sort) to do the
7329 static struct strlist *
7330 expsort(struct strlist *str)
7336 for (sp = str; sp; sp = sp->next)
7338 return msort(str, len);
7342 expandmeta(struct strlist *str /*, int flag*/)
7344 static const char metachars[] ALIGN1 = {
7347 /* TODO - EXP_REDIR */
7351 struct strlist **savelastp;
7357 if (!strpbrk(str->text, metachars))
7359 savelastp = exparg.lastp;
7362 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7364 int i = strlen(str->text);
7365 //BUGGY estimation of how long expanded name can be
7366 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7368 expmeta(expdir, expdir, p);
7373 if (exparg.lastp == savelastp) {
7378 *exparg.lastp = str;
7379 rmescapes(str->text, 0);
7380 exparg.lastp = &str->next;
7382 *exparg.lastp = NULL;
7383 *savelastp = sp = expsort(*savelastp);
7384 while (sp->next != NULL)
7386 exparg.lastp = &sp->next;
7391 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7394 * Perform variable substitution and command substitution on an argument,
7395 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7396 * perform splitting and file name expansion. When arglist is NULL, perform
7397 * here document expansion.
7400 expandarg(union node *arg, struct arglist *arglist, int flag)
7405 argbackq = arg->narg.backquote;
7406 STARTSTACKSTR(expdest);
7407 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7408 argstr(arg->narg.text, flag,
7409 /* var_str_list: */ arglist ? arglist->list : NULL);
7410 p = _STPUTC('\0', expdest);
7412 if (arglist == NULL) {
7413 /* here document expanded */
7416 p = grabstackstr(p);
7417 TRACE(("expandarg: p:'%s'\n", p));
7418 exparg.lastp = &exparg.list;
7422 if (flag & EXP_FULL) {
7423 ifsbreakup(p, &exparg);
7424 *exparg.lastp = NULL;
7425 exparg.lastp = &exparg.list;
7426 expandmeta(exparg.list /*, flag*/);
7428 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7430 TRACE(("expandarg: rmescapes:'%s'\n", p));
7432 sp = stzalloc(sizeof(*sp));
7435 exparg.lastp = &sp->next;
7437 *exparg.lastp = NULL;
7439 *arglist->lastp = exparg.list;
7440 arglist->lastp = exparg.lastp;
7448 * Expand shell variables and backquotes inside a here document.
7451 expandhere(union node *arg, int fd)
7453 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7454 full_write(fd, stackblock(), expdest - (char *)stackblock());
7458 * Returns true if the pattern matches the string.
7461 patmatch(char *pattern, const char *string)
7463 return pmatch(preglob(pattern, 0), string);
7467 * See if a pattern matches in a case statement.
7470 casematch(union node *pattern, char *val)
7472 struct stackmark smark;
7475 setstackmark(&smark);
7476 argbackq = pattern->narg.backquote;
7477 STARTSTACKSTR(expdest);
7478 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7479 /* var_str_list: */ NULL);
7480 STACKSTRNUL(expdest);
7482 result = patmatch(stackblock(), val);
7483 popstackmark(&smark);
7488 /* ============ find_command */
7492 int (*builtin)(int, char **) FAST_FUNC;
7493 /* unsigned flags; */
7495 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7496 /* "regular" builtins always take precedence over commands,
7497 * regardless of PATH=....%builtin... position */
7498 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7499 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7502 smallint cmdtype; /* CMDxxx */
7505 /* index >= 0 for commands without path (slashes) */
7506 /* (TODO: what exactly does the value mean? PATH position?) */
7507 /* index == -1 for commands with slashes */
7508 /* index == (-2 - applet_no) for NOFORK applets */
7509 const struct builtincmd *cmd;
7510 struct funcnode *func;
7513 /* values of cmdtype */
7514 #define CMDUNKNOWN -1 /* no entry in table for command */
7515 #define CMDNORMAL 0 /* command is an executable program */
7516 #define CMDFUNCTION 1 /* command is a shell function */
7517 #define CMDBUILTIN 2 /* command is a shell builtin */
7519 /* action to find_command() */
7520 #define DO_ERR 0x01 /* prints errors */
7521 #define DO_ABS 0x02 /* checks absolute paths */
7522 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7523 #define DO_ALTPATH 0x08 /* using alternate path */
7524 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7526 static void find_command(char *, struct cmdentry *, int, const char *);
7529 /* ============ Hashing commands */
7532 * When commands are first encountered, they are entered in a hash table.
7533 * This ensures that a full path search will not have to be done for them
7534 * on each invocation.
7536 * We should investigate converting to a linear search, even though that
7537 * would make the command name "hash" a misnomer.
7541 struct tblentry *next; /* next entry in hash chain */
7542 union param param; /* definition of builtin function */
7543 smallint cmdtype; /* CMDxxx */
7544 char rehash; /* if set, cd done since entry created */
7545 char cmdname[1]; /* name of command */
7548 static struct tblentry **cmdtable;
7549 #define INIT_G_cmdtable() do { \
7550 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7553 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7557 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7559 #if ENABLE_FEATURE_SH_STANDALONE
7560 if (applet_no >= 0) {
7561 if (APPLET_IS_NOEXEC(applet_no)) {
7565 run_applet_no_and_exit(applet_no, argv);
7567 /* re-exec ourselves with the new arguments */
7568 execve(bb_busybox_exec_path, argv, envp);
7569 /* If they called chroot or otherwise made the binary no longer
7570 * executable, fall through */
7577 execve(cmd, argv, envp);
7578 } while (errno == EINTR);
7580 execve(cmd, argv, envp);
7582 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7583 /* Run "cmd" as a shell script:
7584 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7585 * "If the execve() function fails with ENOEXEC, the shell
7586 * shall execute a command equivalent to having a shell invoked
7587 * with the command name as its first operand,
7588 * with any remaining arguments passed to the new shell"
7590 * That is, do not use $SHELL, user's shell, or /bin/sh;
7591 * just call ourselves.
7593 * Note that bash reads ~80 chars of the file, and if it sees
7594 * a zero byte before it sees newline, it doesn't try to
7595 * interpret it, but fails with "cannot execute binary file"
7596 * message and exit code 126. For one, this prevents attempts
7597 * to interpret foreign ELF binaries as shell scripts.
7600 cmd = (char*) bb_busybox_exec_path;
7601 /* NB: this is only possible because all callers of shellexec()
7602 * ensure that the argv[-1] slot exists!
7605 argv[0] = (char*) "ash";
7611 * Exec a program. Never returns. If you change this routine, you may
7612 * have to change the find_command routine as well.
7613 * argv[-1] must exist and be writable! See tryexec() for why.
7615 static void shellexec(char **, const char *, int) NORETURN;
7617 shellexec(char **argv, const char *path, int idx)
7623 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7625 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7626 if (strchr(argv[0], '/') != NULL
7627 #if ENABLE_FEATURE_SH_STANDALONE
7628 || (applet_no = find_applet_by_name(argv[0])) >= 0
7631 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7632 if (applet_no >= 0) {
7633 /* We tried execing ourself, but it didn't work.
7634 * Maybe /proc/self/exe doesn't exist?
7643 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7644 if (--idx < 0 && pathopt == NULL) {
7645 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7646 if (errno != ENOENT && errno != ENOTDIR)
7653 /* Map to POSIX errors */
7665 exitstatus = exerrno;
7666 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7667 argv[0], e, suppress_int));
7668 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7673 printentry(struct tblentry *cmdp)
7679 idx = cmdp->param.index;
7682 name = path_advance(&path, cmdp->cmdname);
7684 } while (--idx >= 0);
7685 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7689 * Clear out command entries. The argument specifies the first entry in
7690 * PATH which has changed.
7693 clearcmdentry(int firstchange)
7695 struct tblentry **tblp;
7696 struct tblentry **pp;
7697 struct tblentry *cmdp;
7700 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7702 while ((cmdp = *pp) != NULL) {
7703 if ((cmdp->cmdtype == CMDNORMAL &&
7704 cmdp->param.index >= firstchange)
7705 || (cmdp->cmdtype == CMDBUILTIN &&
7706 builtinloc >= firstchange)
7719 * Locate a command in the command hash table. If "add" is nonzero,
7720 * add the command to the table if it is not already present. The
7721 * variable "lastcmdentry" is set to point to the address of the link
7722 * pointing to the entry, so that delete_cmd_entry can delete the
7725 * Interrupts must be off if called with add != 0.
7727 static struct tblentry **lastcmdentry;
7729 static struct tblentry *
7730 cmdlookup(const char *name, int add)
7732 unsigned int hashval;
7734 struct tblentry *cmdp;
7735 struct tblentry **pp;
7738 hashval = (unsigned char)*p << 4;
7740 hashval += (unsigned char)*p++;
7742 pp = &cmdtable[hashval % CMDTABLESIZE];
7743 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7744 if (strcmp(cmdp->cmdname, name) == 0)
7748 if (add && cmdp == NULL) {
7749 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7751 /* + 1 - already done because
7752 * tblentry::cmdname is char[1] */);
7753 /*cmdp->next = NULL; - ckzalloc did it */
7754 cmdp->cmdtype = CMDUNKNOWN;
7755 strcpy(cmdp->cmdname, name);
7762 * Delete the command entry returned on the last lookup.
7765 delete_cmd_entry(void)
7767 struct tblentry *cmdp;
7770 cmdp = *lastcmdentry;
7771 *lastcmdentry = cmdp->next;
7772 if (cmdp->cmdtype == CMDFUNCTION)
7773 freefunc(cmdp->param.func);
7779 * Add a new command entry, replacing any existing command entry for
7780 * the same name - except special builtins.
7783 addcmdentry(char *name, struct cmdentry *entry)
7785 struct tblentry *cmdp;
7787 cmdp = cmdlookup(name, 1);
7788 if (cmdp->cmdtype == CMDFUNCTION) {
7789 freefunc(cmdp->param.func);
7791 cmdp->cmdtype = entry->cmdtype;
7792 cmdp->param = entry->u;
7796 static int FAST_FUNC
7797 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7799 struct tblentry **pp;
7800 struct tblentry *cmdp;
7802 struct cmdentry entry;
7805 if (nextopt("r") != '\0') {
7810 if (*argptr == NULL) {
7811 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7812 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7813 if (cmdp->cmdtype == CMDNORMAL)
7821 while ((name = *argptr) != NULL) {
7822 cmdp = cmdlookup(name, 0);
7824 && (cmdp->cmdtype == CMDNORMAL
7825 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7829 find_command(name, &entry, DO_ERR, pathval());
7830 if (entry.cmdtype == CMDUNKNOWN)
7838 * Called when a cd is done. Marks all commands so the next time they
7839 * are executed they will be rehashed.
7844 struct tblentry **pp;
7845 struct tblentry *cmdp;
7847 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7848 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7849 if (cmdp->cmdtype == CMDNORMAL
7850 || (cmdp->cmdtype == CMDBUILTIN
7851 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7861 * Fix command hash table when PATH changed.
7862 * Called before PATH is changed. The argument is the new value of PATH;
7863 * pathval() still returns the old value at this point.
7864 * Called with interrupts off.
7866 static void FAST_FUNC
7867 changepath(const char *new)
7875 firstchange = 9999; /* assume no change */
7881 if ((*old == '\0' && *new == ':')
7882 || (*old == ':' && *new == '\0')
7886 old = new; /* ignore subsequent differences */
7890 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7897 if (builtinloc < 0 && idx_bltin >= 0)
7898 builtinloc = idx_bltin; /* zap builtins */
7899 if (builtinloc >= 0 && idx_bltin < 0)
7901 clearcmdentry(firstchange);
7902 builtinloc = idx_bltin;
7927 #if ENABLE_ASH_BASH_COMPAT
7938 typedef smallint token_id_t;
7940 /* Nth bit indicates if token marks the end of a list */
7943 /* 0 */ | (1u << TEOF)
7944 /* 1 */ | (0u << TNL)
7945 /* 2 */ | (0u << TREDIR)
7946 /* 3 */ | (0u << TWORD)
7947 /* 4 */ | (0u << TSEMI)
7948 /* 5 */ | (0u << TBACKGND)
7949 /* 6 */ | (0u << TAND)
7950 /* 7 */ | (0u << TOR)
7951 /* 8 */ | (0u << TPIPE)
7952 /* 9 */ | (0u << TLP)
7953 /* 10 */ | (1u << TRP)
7954 /* 11 */ | (1u << TENDCASE)
7955 /* 12 */ | (1u << TENDBQUOTE)
7956 /* 13 */ | (0u << TNOT)
7957 /* 14 */ | (0u << TCASE)
7958 /* 15 */ | (1u << TDO)
7959 /* 16 */ | (1u << TDONE)
7960 /* 17 */ | (1u << TELIF)
7961 /* 18 */ | (1u << TELSE)
7962 /* 19 */ | (1u << TESAC)
7963 /* 20 */ | (1u << TFI)
7964 /* 21 */ | (0u << TFOR)
7965 #if ENABLE_ASH_BASH_COMPAT
7966 /* 22 */ | (0u << TFUNCTION)
7968 /* 23 */ | (0u << TIF)
7969 /* 24 */ | (0u << TIN)
7970 /* 25 */ | (1u << TTHEN)
7971 /* 26 */ | (0u << TUNTIL)
7972 /* 27 */ | (0u << TWHILE)
7973 /* 28 */ | (0u << TBEGIN)
7974 /* 29 */ | (1u << TEND)
7975 , /* thus far 29 bits used */
7978 static const char *const tokname_array[] = {
7992 #define KWDOFFSET 13
7993 /* the following are keywords */
8003 #if ENABLE_ASH_BASH_COMPAT
8015 /* Wrapper around strcmp for qsort/bsearch/... */
8017 pstrcmp(const void *a, const void *b)
8019 return strcmp((char*)a, *(char**)b);
8022 static const char *const *
8023 findkwd(const char *s)
8025 return bsearch(s, tokname_array + KWDOFFSET,
8026 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8027 sizeof(tokname_array[0]), pstrcmp);
8031 * Locate and print what a word is...
8034 describe_command(char *command, const char *path, int describe_command_verbose)
8036 struct cmdentry entry;
8037 struct tblentry *cmdp;
8038 #if ENABLE_ASH_ALIAS
8039 const struct alias *ap;
8042 path = path ? path : pathval();
8044 if (describe_command_verbose) {
8048 /* First look at the keywords */
8049 if (findkwd(command)) {
8050 out1str(describe_command_verbose ? " is a shell keyword" : command);
8054 #if ENABLE_ASH_ALIAS
8055 /* Then look at the aliases */
8056 ap = lookupalias(command, 0);
8058 if (!describe_command_verbose) {
8063 out1fmt(" is an alias for %s", ap->val);
8067 /* Then check if it is a tracked alias */
8068 cmdp = cmdlookup(command, 0);
8070 entry.cmdtype = cmdp->cmdtype;
8071 entry.u = cmdp->param;
8073 /* Finally use brute force */
8074 find_command(command, &entry, DO_ABS, path);
8077 switch (entry.cmdtype) {
8079 int j = entry.u.index;
8085 p = path_advance(&path, command);
8089 if (describe_command_verbose) {
8091 (cmdp ? " a tracked alias for" : nullstr), p
8100 if (describe_command_verbose) {
8101 out1str(" is a shell function");
8108 if (describe_command_verbose) {
8109 out1fmt(" is a %sshell builtin",
8110 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8111 "special " : nullstr
8119 if (describe_command_verbose) {
8120 out1str(": not found\n");
8129 static int FAST_FUNC
8130 typecmd(int argc UNUSED_PARAM, char **argv)
8136 /* type -p ... ? (we don't bother checking for 'p') */
8137 if (argv[1] && argv[1][0] == '-') {
8142 err |= describe_command(argv[i++], NULL, verbose);
8147 #if ENABLE_ASH_CMDCMD
8148 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8150 parse_command_args(char **argv, const char **path)
8163 if (c == '-' && !*cp) {
8171 *path = bb_default_path;
8174 /* run 'typecmd' for other options */
8183 static int FAST_FUNC
8184 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8192 const char *path = NULL;
8194 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8195 * never reaches this function.
8198 while ((c = nextopt("pvV")) != '\0')
8200 verify |= VERIFY_VERBOSE;
8202 /*verify |= VERIFY_BRIEF*/;
8208 path = bb_default_path;
8210 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8212 if (/*verify && */ cmd)
8213 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8220 /*static int funcblocksize; // size of structures in function */
8221 /*static int funcstringsize; // size of strings in node */
8222 static void *funcblock; /* block to allocate function from */
8223 static char *funcstring_end; /* end of block to allocate strings from */
8225 /* flags in argument to evaltree */
8226 #define EV_EXIT 01 /* exit after evaluating tree */
8227 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8229 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8230 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8231 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8232 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8233 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8234 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8235 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8236 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8237 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8238 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8239 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8240 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8241 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8242 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8243 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8244 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8245 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8246 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8247 #if ENABLE_ASH_BASH_COMPAT
8248 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8250 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8251 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8252 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8253 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8254 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8255 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8256 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8257 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8258 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8261 static int calcsize(int funcblocksize, union node *n);
8264 sizenodelist(int funcblocksize, struct nodelist *lp)
8267 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8268 funcblocksize = calcsize(funcblocksize, lp->n);
8271 return funcblocksize;
8275 calcsize(int funcblocksize, union node *n)
8278 return funcblocksize;
8279 funcblocksize += nodesize[n->type];
8282 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8283 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8284 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8287 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8292 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8293 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8300 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8301 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8304 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8305 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8306 funcblocksize = calcsize(funcblocksize, n->nif.test);
8309 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8310 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8311 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8314 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8315 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8318 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8319 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8320 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8324 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8325 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8326 funcblocksize = calcsize(funcblocksize, n->narg.next);
8329 #if ENABLE_ASH_BASH_COMPAT
8336 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8337 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8341 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8342 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8346 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8347 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8350 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8353 return funcblocksize;
8357 nodeckstrdup(char *s)
8359 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8360 return strcpy(funcstring_end, s);
8363 static union node *copynode(union node *);
8365 static struct nodelist *
8366 copynodelist(struct nodelist *lp)
8368 struct nodelist *start;
8369 struct nodelist **lpp;
8374 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8375 (*lpp)->n = copynode(lp->n);
8377 lpp = &(*lpp)->next;
8384 copynode(union node *n)
8391 funcblock = (char *) funcblock + nodesize[n->type];
8395 new->ncmd.redirect = copynode(n->ncmd.redirect);
8396 new->ncmd.args = copynode(n->ncmd.args);
8397 new->ncmd.assign = copynode(n->ncmd.assign);
8400 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8401 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8406 new->nredir.redirect = copynode(n->nredir.redirect);
8407 new->nredir.n = copynode(n->nredir.n);
8414 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8415 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8418 new->nif.elsepart = copynode(n->nif.elsepart);
8419 new->nif.ifpart = copynode(n->nif.ifpart);
8420 new->nif.test = copynode(n->nif.test);
8423 new->nfor.var = nodeckstrdup(n->nfor.var);
8424 new->nfor.body = copynode(n->nfor.body);
8425 new->nfor.args = copynode(n->nfor.args);
8428 new->ncase.cases = copynode(n->ncase.cases);
8429 new->ncase.expr = copynode(n->ncase.expr);
8432 new->nclist.body = copynode(n->nclist.body);
8433 new->nclist.pattern = copynode(n->nclist.pattern);
8434 new->nclist.next = copynode(n->nclist.next);
8438 new->narg.backquote = copynodelist(n->narg.backquote);
8439 new->narg.text = nodeckstrdup(n->narg.text);
8440 new->narg.next = copynode(n->narg.next);
8443 #if ENABLE_ASH_BASH_COMPAT
8450 new->nfile.fname = copynode(n->nfile.fname);
8451 new->nfile.fd = n->nfile.fd;
8452 new->nfile.next = copynode(n->nfile.next);
8456 new->ndup.vname = copynode(n->ndup.vname);
8457 new->ndup.dupfd = n->ndup.dupfd;
8458 new->ndup.fd = n->ndup.fd;
8459 new->ndup.next = copynode(n->ndup.next);
8463 new->nhere.doc = copynode(n->nhere.doc);
8464 new->nhere.fd = n->nhere.fd;
8465 new->nhere.next = copynode(n->nhere.next);
8468 new->nnot.com = copynode(n->nnot.com);
8471 new->type = n->type;
8476 * Make a copy of a parse tree.
8478 static struct funcnode *
8479 copyfunc(union node *n)
8484 /*funcstringsize = 0;*/
8485 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8486 f = ckzalloc(blocksize /* + funcstringsize */);
8487 funcblock = (char *) f + offsetof(struct funcnode, n);
8488 funcstring_end = (char *) f + blocksize;
8490 /* f->count = 0; - ckzalloc did it */
8495 * Define a shell function.
8498 defun(union node *func)
8500 struct cmdentry entry;
8503 entry.cmdtype = CMDFUNCTION;
8504 entry.u.func = copyfunc(func);
8505 addcmdentry(func->narg.text, &entry);
8509 /* Reasons for skipping commands (see comment on breakcmd routine) */
8510 #define SKIPBREAK (1 << 0)
8511 #define SKIPCONT (1 << 1)
8512 #define SKIPFUNC (1 << 2)
8513 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8514 static int skipcount; /* number of levels to skip */
8515 static int funcnest; /* depth of function calls */
8516 static int loopnest; /* current loop nesting level */
8518 /* Forward decl way out to parsing code - dotrap needs it */
8519 static int evalstring(char *s, int flags);
8521 /* Called to execute a trap.
8522 * Single callsite - at the end of evaltree().
8523 * If we return non-zero, evaltree raises EXEXIT exception.
8525 * Perhaps we should avoid entering new trap handlers
8526 * while we are executing a trap handler. [is it a TODO?]
8533 uint8_t last_status;
8538 last_status = exitstatus;
8542 TRACE(("dotrap entered\n"));
8543 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8555 /* non-trapped SIGINT is handled separately by raise_interrupt,
8556 * don't upset it by resetting gotsig[SIGINT-1] */
8557 if (sig == SIGINT && !p)
8560 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8566 exitstatus = last_status;
8567 TRACE(("dotrap returns\n"));
8570 /* forward declarations - evaluation is fairly recursive business... */
8571 static int evalloop(union node *, int);
8572 static int evalfor(union node *, int);
8573 static int evalcase(union node *, int);
8574 static int evalsubshell(union node *, int);
8575 static void expredir(union node *);
8576 static int evalpipe(union node *, int);
8577 static int evalcommand(union node *, int);
8578 static int evalbltin(const struct builtincmd *, int, char **, int);
8579 static void prehash(union node *);
8582 * Evaluate a parse tree. The value is left in the global variable
8586 evaltree(union node *n, int flags)
8589 int (*evalfn)(union node *, int);
8593 TRACE(("evaltree(NULL) called\n"));
8596 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8603 out1fmt("Node type = %d\n", n->type);
8608 status = !evaltree(n->nnot.com, EV_TESTED);
8611 expredir(n->nredir.redirect);
8612 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8614 status = evaltree(n->nredir.n, flags & EV_TESTED);
8616 if (n->nredir.redirect)
8617 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8620 evalfn = evalcommand;
8622 if (eflag && !(flags & EV_TESTED))
8634 evalfn = evalsubshell;
8647 #error NAND + 1 != NOR
8649 #if NOR + 1 != NSEMI
8650 #error NOR + 1 != NSEMI
8652 unsigned is_or = n->type - NAND;
8655 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8657 if ((!status) == is_or || evalskip)
8663 status = evalfn(n, flags);
8667 status = evaltree(n->nif.test, EV_TESTED);
8674 if (n->nif.elsepart) {
8675 n = n->nif.elsepart;
8682 /* Not necessary. To test it:
8683 * "false; f() { qwerty; }; echo $?" should print 0.
8687 exitstatus = status;
8691 /* Order of checks below is important:
8692 * signal handlers trigger before exit caused by "set -e".
8696 if (checkexit & status)
8697 raise_exception(EXEXIT);
8698 if (flags & EV_EXIT)
8699 raise_exception(EXEXIT);
8701 TRACE(("leaving evaltree (no interrupts)\n"));
8705 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8708 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8713 int skip = evalskip;
8720 if (--skipcount <= 0) {
8731 evalloop(union node *n, int flags)
8742 i = evaltree(n->nbinary.ch1, EV_TESTED);
8744 if (skip == SKIPFUNC)
8748 if (n->type != NWHILE)
8752 status = evaltree(n->nbinary.ch2, flags);
8754 } while (!(skip & ~SKIPCONT));
8761 evalfor(union node *n, int flags)
8763 struct arglist arglist;
8766 struct stackmark smark;
8769 setstackmark(&smark);
8770 arglist.list = NULL;
8771 arglist.lastp = &arglist.list;
8772 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8773 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8775 *arglist.lastp = NULL;
8779 for (sp = arglist.list; sp; sp = sp->next) {
8780 setvar0(n->nfor.var, sp->text);
8781 status = evaltree(n->nfor.body, flags);
8782 if (skiploop() & ~SKIPCONT)
8786 popstackmark(&smark);
8792 evalcase(union node *n, int flags)
8796 struct arglist arglist;
8797 struct stackmark smark;
8800 setstackmark(&smark);
8801 arglist.list = NULL;
8802 arglist.lastp = &arglist.list;
8803 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8804 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8805 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8806 if (casematch(patp, arglist.list->text)) {
8807 /* Ensure body is non-empty as otherwise
8808 * EV_EXIT may prevent us from setting the
8811 if (evalskip == 0 && cp->nclist.body) {
8812 status = evaltree(cp->nclist.body, flags);
8819 popstackmark(&smark);
8825 * Kick off a subshell to evaluate a tree.
8828 evalsubshell(union node *n, int flags)
8831 int backgnd = (n->type == NBACKGND);
8834 expredir(n->nredir.redirect);
8835 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8838 jp = makejob(/*n,*/ 1);
8839 if (forkshell(jp, n, backgnd) == 0) {
8844 flags &= ~EV_TESTED;
8846 redirect(n->nredir.redirect, 0);
8847 evaltreenr(n->nredir.n, flags);
8853 status = waitforjob(jp);
8859 * Compute the names of the files in a redirection list.
8861 static void fixredir(union node *, const char *, int);
8863 expredir(union node *n)
8867 for (redir = n; redir; redir = redir->nfile.next) {
8871 fn.lastp = &fn.list;
8872 switch (redir->type) {
8876 #if ENABLE_ASH_BASH_COMPAT
8881 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8882 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8883 #if ENABLE_ASH_BASH_COMPAT
8887 // By the design of stack allocator, the loop of this kind:
8888 // while true; do while true; do break; done </dev/null; done
8889 // will look like a memory leak: ash plans to free expfname's
8890 // of "/dev/null" as soon as it finishes running the loop
8891 // (in this case, never).
8892 // This "fix" is wrong:
8893 if (redir->nfile.expfname)
8894 stunalloc(redir->nfile.expfname);
8895 // It results in corrupted state of stacked allocations.
8897 redir->nfile.expfname = fn.list->text;
8900 case NTOFD: /* >& */
8901 if (redir->ndup.vname) {
8902 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8903 if (fn.list == NULL)
8904 ash_msg_and_raise_error("redir error");
8905 #if ENABLE_ASH_BASH_COMPAT
8906 //FIXME: we used expandarg with different args!
8907 if (!isdigit_str9(fn.list->text)) {
8908 /* >&file, not >&fd */
8909 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8910 ash_msg_and_raise_error("redir error");
8912 goto store_expfname;
8915 fixredir(redir, fn.list->text, 1);
8923 * Evaluate a pipeline. All the processes in the pipeline are children
8924 * of the process creating the pipeline. (This differs from some versions
8925 * of the shell, which make the last process in a pipeline the parent
8929 evalpipe(union node *n, int flags)
8932 struct nodelist *lp;
8938 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8940 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8944 jp = makejob(/*n,*/ pipelen);
8946 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8950 if (pipe(pip) < 0) {
8952 ash_msg_and_raise_error("pipe call failed");
8955 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8969 evaltreenr(lp->n, flags);
8976 /* Don't want to trigger debugging */
8980 if (n->npipe.pipe_backgnd == 0) {
8981 status = waitforjob(jp);
8982 TRACE(("evalpipe: job done exit status %d\n", status));
8990 * Controls whether the shell is interactive or not.
8993 setinteractive(int on)
8995 static smallint is_interactive;
8997 if (++on == is_interactive)
8999 is_interactive = on;
9003 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9004 if (is_interactive > 1) {
9005 /* Looks like they want an interactive shell */
9006 static smallint did_banner;
9009 /* note: ash and hush share this string */
9010 out1fmt("\n\n%s %s\n"
9011 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9014 "built-in shell (ash)"
9028 setinteractive(iflag);
9030 #if ENABLE_FEATURE_EDITING_VI
9032 line_input_state->flags |= VI_MODE;
9034 line_input_state->flags &= ~VI_MODE;
9036 viflag = 0; /* forcibly keep the option off */
9040 static struct localvar *localvars;
9043 * Called after a function returns.
9044 * Interrupts must be off.
9049 struct localvar *lvp;
9052 while ((lvp = localvars) != NULL) {
9053 localvars = lvp->next;
9055 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9056 if (vp == NULL) { /* $- saved */
9057 memcpy(optlist, lvp->text, sizeof(optlist));
9058 free((char*)lvp->text);
9060 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9061 unsetvar(vp->var_text);
9064 vp->var_func(var_end(lvp->text));
9065 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9066 free((char*)vp->var_text);
9067 vp->flags = lvp->flags;
9068 vp->var_text = lvp->text;
9075 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9077 volatile struct shparam saveparam;
9078 struct localvar *volatile savelocalvars;
9079 struct jmploc *volatile savehandler;
9080 struct jmploc jmploc;
9083 saveparam = shellparam;
9084 savelocalvars = localvars;
9085 savehandler = exception_handler;
9086 e = setjmp(jmploc.loc);
9091 exception_handler = &jmploc;
9093 shellparam.malloced = 0;
9097 shellparam.nparam = argc - 1;
9098 shellparam.p = argv + 1;
9099 #if ENABLE_ASH_GETOPTS
9100 shellparam.optind = 1;
9101 shellparam.optoff = -1;
9103 evaltree(func->n.narg.next, flags & EV_TESTED);
9109 localvars = savelocalvars;
9110 freeparam(&shellparam);
9111 shellparam = saveparam;
9112 exception_handler = savehandler;
9114 evalskip &= ~SKIPFUNC;
9119 * Make a variable a local variable. When a variable is made local, it's
9120 * value and flags are saved in a localvar structure. The saved values
9121 * will be restored when the shell function returns. We handle the name
9122 * "-" as a special case: it makes changes to "set +-options" local
9123 * (options will be restored on return from the function).
9128 struct localvar *lvp;
9131 char *eq = strchr(name, '=');
9134 /* Cater for duplicate "local". Examples:
9135 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9136 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9140 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9144 * it's a duplicate "local VAR" declaration, do nothing
9151 lvp = ckzalloc(sizeof(*lvp));
9152 if (LONE_DASH(name)) {
9154 p = ckmalloc(sizeof(optlist));
9155 lvp->text = memcpy(p, optlist, sizeof(optlist));
9158 vpp = hashvar(name);
9159 vp = *findvar(vpp, name);
9161 /* variable did not exist yet */
9163 setvareq(name, VSTRFIXED);
9165 setvar(name, NULL, VSTRFIXED);
9166 vp = *vpp; /* the new variable */
9167 lvp->flags = VUNSET;
9169 lvp->text = vp->var_text;
9170 lvp->flags = vp->flags;
9171 /* make sure neither "struct var" nor string gets freed
9172 * during (un)setting:
9174 vp->flags |= VSTRFIXED|VTEXTFIXED;
9178 /* "local VAR" unsets VAR: */
9179 setvar0(name, NULL);
9183 lvp->next = localvars;
9190 * The "local" command.
9192 static int FAST_FUNC
9193 localcmd(int argc UNUSED_PARAM, char **argv)
9198 ash_msg_and_raise_error("not in a function");
9201 while ((name = *argv++) != NULL) {
9207 static int FAST_FUNC
9208 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9213 static int FAST_FUNC
9214 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9219 static int FAST_FUNC
9220 execcmd(int argc UNUSED_PARAM, char **argv)
9223 iflag = 0; /* exit on error */
9226 /* We should set up signals for "exec CMD"
9227 * the same way as for "CMD" without "exec".
9228 * But optschanged->setinteractive->setsignal
9229 * still thought we are a root shell. Therefore, for example,
9230 * SIGQUIT is still set to IGN. Fix it:
9234 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9235 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9236 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9238 shellexec(argv + 1, pathval(), 0);
9245 * The return command.
9247 static int FAST_FUNC
9248 returncmd(int argc UNUSED_PARAM, char **argv)
9251 * If called outside a function, do what ksh does;
9252 * skip the rest of the file.
9254 evalskip = SKIPFUNC;
9255 return argv[1] ? number(argv[1]) : exitstatus;
9258 /* Forward declarations for builtintab[] */
9259 static int breakcmd(int, char **) FAST_FUNC;
9260 static int dotcmd(int, char **) FAST_FUNC;
9261 static int evalcmd(int, char **, int) FAST_FUNC;
9262 static int exitcmd(int, char **) FAST_FUNC;
9263 static int exportcmd(int, char **) FAST_FUNC;
9264 #if ENABLE_ASH_GETOPTS
9265 static int getoptscmd(int, char **) FAST_FUNC;
9268 static int helpcmd(int, char **) FAST_FUNC;
9271 static int historycmd(int, char **) FAST_FUNC;
9273 #if ENABLE_FEATURE_SH_MATH
9274 static int letcmd(int, char **) FAST_FUNC;
9276 static int readcmd(int, char **) FAST_FUNC;
9277 static int setcmd(int, char **) FAST_FUNC;
9278 static int shiftcmd(int, char **) FAST_FUNC;
9279 static int timescmd(int, char **) FAST_FUNC;
9280 static int trapcmd(int, char **) FAST_FUNC;
9281 static int umaskcmd(int, char **) FAST_FUNC;
9282 static int unsetcmd(int, char **) FAST_FUNC;
9283 static int ulimitcmd(int, char **) FAST_FUNC;
9285 #define BUILTIN_NOSPEC "0"
9286 #define BUILTIN_SPECIAL "1"
9287 #define BUILTIN_REGULAR "2"
9288 #define BUILTIN_SPEC_REG "3"
9289 #define BUILTIN_ASSIGN "4"
9290 #define BUILTIN_SPEC_ASSG "5"
9291 #define BUILTIN_REG_ASSG "6"
9292 #define BUILTIN_SPEC_REG_ASSG "7"
9294 /* Stubs for calling non-FAST_FUNC's */
9296 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9298 #if ENABLE_ASH_PRINTF
9299 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9302 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9305 /* Keep these in proper order since it is searched via bsearch() */
9306 static const struct builtincmd builtintab[] = {
9307 { BUILTIN_SPEC_REG "." , dotcmd },
9308 { BUILTIN_SPEC_REG ":" , truecmd },
9310 { BUILTIN_REGULAR "[" , testcmd },
9311 # if ENABLE_ASH_BASH_COMPAT
9312 { BUILTIN_REGULAR "[[" , testcmd },
9315 #if ENABLE_ASH_ALIAS
9316 { BUILTIN_REG_ASSG "alias" , aliascmd },
9319 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9321 { BUILTIN_SPEC_REG "break" , breakcmd },
9322 { BUILTIN_REGULAR "cd" , cdcmd },
9323 { BUILTIN_NOSPEC "chdir" , cdcmd },
9324 #if ENABLE_ASH_CMDCMD
9325 { BUILTIN_REGULAR "command" , commandcmd },
9327 { BUILTIN_SPEC_REG "continue", breakcmd },
9329 { BUILTIN_REGULAR "echo" , echocmd },
9331 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9332 { BUILTIN_SPEC_REG "exec" , execcmd },
9333 { BUILTIN_SPEC_REG "exit" , exitcmd },
9334 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9335 { BUILTIN_REGULAR "false" , falsecmd },
9337 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9339 #if ENABLE_ASH_GETOPTS
9340 { BUILTIN_REGULAR "getopts" , getoptscmd },
9342 { BUILTIN_NOSPEC "hash" , hashcmd },
9344 { BUILTIN_NOSPEC "help" , helpcmd },
9347 { BUILTIN_NOSPEC "history" , historycmd },
9350 { BUILTIN_REGULAR "jobs" , jobscmd },
9351 { BUILTIN_REGULAR "kill" , killcmd },
9353 #if ENABLE_FEATURE_SH_MATH
9354 { BUILTIN_NOSPEC "let" , letcmd },
9356 { BUILTIN_ASSIGN "local" , localcmd },
9357 #if ENABLE_ASH_PRINTF
9358 { BUILTIN_REGULAR "printf" , printfcmd },
9360 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9361 { BUILTIN_REGULAR "read" , readcmd },
9362 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9363 { BUILTIN_SPEC_REG "return" , returncmd },
9364 { BUILTIN_SPEC_REG "set" , setcmd },
9365 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9366 #if ENABLE_ASH_BASH_COMPAT
9367 { BUILTIN_SPEC_REG "source" , dotcmd },
9370 { BUILTIN_REGULAR "test" , testcmd },
9372 { BUILTIN_SPEC_REG "times" , timescmd },
9373 { BUILTIN_SPEC_REG "trap" , trapcmd },
9374 { BUILTIN_REGULAR "true" , truecmd },
9375 { BUILTIN_NOSPEC "type" , typecmd },
9376 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9377 { BUILTIN_REGULAR "umask" , umaskcmd },
9378 #if ENABLE_ASH_ALIAS
9379 { BUILTIN_REGULAR "unalias" , unaliascmd },
9381 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9382 { BUILTIN_REGULAR "wait" , waitcmd },
9385 /* Should match the above table! */
9386 #define COMMANDCMD (builtintab + \
9388 /* [ */ 1 * ENABLE_ASH_TEST + \
9389 /* [[ */ 1 * ENABLE_ASH_TEST * ENABLE_ASH_BASH_COMPAT + \
9390 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9391 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9392 /* break cd cddir */ 3)
9393 #define EVALCMD (COMMANDCMD + \
9394 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9395 /* continue */ 1 + \
9396 /* echo */ 1 * ENABLE_ASH_ECHO + \
9398 #define EXECCMD (EVALCMD + \
9402 * Search the table of builtin commands.
9405 pstrcmp1(const void *a, const void *b)
9407 return strcmp((char*)a, *(char**)b + 1);
9409 static struct builtincmd *
9410 find_builtin(const char *name)
9412 struct builtincmd *bp;
9415 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9422 * Execute a simple command.
9425 isassignment(const char *p)
9427 const char *q = endofname(p);
9432 static int FAST_FUNC
9433 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9435 /* Preserve exitstatus of a previous possible redirection
9436 * as POSIX mandates */
9437 return back_exitstatus;
9440 evalcommand(union node *cmd, int flags)
9442 static const struct builtincmd null_bltin = {
9443 "\0\0", bltincmd /* why three NULs? */
9445 struct stackmark smark;
9447 struct arglist arglist;
9448 struct arglist varlist;
9451 const struct strlist *sp;
9452 struct cmdentry cmdentry;
9459 struct builtincmd *bcmd;
9460 smallint cmd_is_exec;
9461 smallint pseudovarflag = 0;
9463 /* First expand the arguments. */
9464 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9465 setstackmark(&smark);
9466 back_exitstatus = 0;
9468 cmdentry.cmdtype = CMDBUILTIN;
9469 cmdentry.u.cmd = &null_bltin;
9470 varlist.lastp = &varlist.list;
9471 *varlist.lastp = NULL;
9472 arglist.lastp = &arglist.list;
9473 *arglist.lastp = NULL;
9476 if (cmd->ncmd.args) {
9477 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9478 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9481 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9482 struct strlist **spp;
9484 spp = arglist.lastp;
9485 if (pseudovarflag && isassignment(argp->narg.text))
9486 expandarg(argp, &arglist, EXP_VARTILDE);
9488 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9490 for (sp = *spp; sp; sp = sp->next)
9494 /* Reserve one extra spot at the front for shellexec. */
9495 nargv = stalloc(sizeof(char *) * (argc + 2));
9497 for (sp = arglist.list; sp; sp = sp->next) {
9498 TRACE(("evalcommand arg: %s\n", sp->text));
9499 *nargv++ = sp->text;
9504 if (iflag && funcnest == 0 && argc > 0)
9505 lastarg = nargv[-1];
9508 expredir(cmd->ncmd.redirect);
9509 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9511 path = vpath.var_text;
9512 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9513 struct strlist **spp;
9516 spp = varlist.lastp;
9517 expandarg(argp, &varlist, EXP_VARTILDE);
9520 * Modify the command lookup path, if a PATH= assignment
9524 if (varcmp(p, path) == 0)
9528 /* Print the command if xflag is set. */
9531 const char *p = " %s" + 1;
9533 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9535 for (n = 0; n < 2; n++) {
9537 fdprintf(preverrout_fd, p, sp->text);
9543 safe_write(preverrout_fd, "\n", 1);
9549 /* Now locate the command. */
9551 int cmd_flag = DO_ERR;
9552 #if ENABLE_ASH_CMDCMD
9553 const char *oldpath = path + 5;
9557 find_command(argv[0], &cmdentry, cmd_flag, path);
9558 if (cmdentry.cmdtype == CMDUNKNOWN) {
9559 flush_stdout_stderr();
9564 /* implement bltin and command here */
9565 if (cmdentry.cmdtype != CMDBUILTIN)
9568 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9569 if (cmdentry.u.cmd == EXECCMD)
9571 #if ENABLE_ASH_CMDCMD
9572 if (cmdentry.u.cmd == COMMANDCMD) {
9574 nargv = parse_command_args(argv, &path);
9577 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9578 * nargv => "PROG". path is updated if -p.
9580 argc -= nargv - argv;
9582 cmd_flag |= DO_NOFUNC;
9591 exitstatus = status;
9593 /* We have a redirection error. */
9595 raise_exception(EXERROR);
9600 /* Execute the command. */
9601 switch (cmdentry.cmdtype) {
9604 #if ENABLE_FEATURE_SH_NOFORK
9605 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9606 * around run_nofork_applet() call.
9607 * (2) Should this check also be done in forkshell()?
9608 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9610 /* find_command() encodes applet_no as (-2 - applet_no) */
9611 int applet_no = (- cmdentry.u.index - 2);
9612 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9613 listsetvar(varlist.list, VEXPORT|VSTACK);
9614 /* run <applet>_main() */
9615 status = run_nofork_applet(applet_no, argv);
9619 /* Can we avoid forking off? For example, very last command
9620 * in a script or a subshell does not need forking,
9621 * we can just exec it.
9623 if (!(flags & EV_EXIT) || may_have_traps) {
9624 /* No, forking off a child is necessary */
9626 jp = makejob(/*cmd,*/ 1);
9627 if (forkshell(jp, cmd, FORK_FG) != 0) {
9629 status = waitforjob(jp);
9631 TRACE(("forked child exited with %d\n", status));
9636 /* fall through to exec'ing external program */
9638 listsetvar(varlist.list, VEXPORT|VSTACK);
9639 shellexec(argv, path, cmdentry.u.index);
9643 cmdenviron = varlist.list;
9645 struct strlist *list = cmdenviron;
9647 if (spclbltin > 0 || argc == 0) {
9649 if (cmd_is_exec && argc > 1)
9652 listsetvar(list, i);
9654 /* Tight loop with builtins only:
9655 * "while kill -0 $child; do true; done"
9656 * will never exit even if $child died, unless we do this
9657 * to reap the zombie and make kill detect that it's gone: */
9658 dowait(DOWAIT_NONBLOCK, NULL);
9660 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9661 if (exception_type == EXERROR && spclbltin <= 0) {
9666 longjmp(exception_handler->loc, 1);
9671 listsetvar(varlist.list, 0);
9672 /* See above for the rationale */
9673 dowait(DOWAIT_NONBLOCK, NULL);
9674 if (evalfun(cmdentry.u.func, argc, argv, flags))
9677 status = exitstatus;
9682 if (cmd->ncmd.redirect)
9683 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9685 /* dsl: I think this is intended to be used to support
9686 * '_' in 'vi' command mode during line editing...
9687 * However I implemented that within libedit itself.
9689 setvar0("_", lastarg);
9691 popstackmark(&smark);
9697 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9699 char *volatile savecmdname;
9700 struct jmploc *volatile savehandler;
9701 struct jmploc jmploc;
9705 savecmdname = commandname;
9706 savehandler = exception_handler;
9707 i = setjmp(jmploc.loc);
9710 exception_handler = &jmploc;
9711 commandname = argv[0];
9713 optptr = NULL; /* initialize nextopt */
9715 status = evalcmd(argc, argv, flags);
9717 status = (*cmd->builtin)(argc, argv);
9718 flush_stdout_stderr();
9719 status |= ferror(stdout);
9720 exitstatus = status;
9723 commandname = savecmdname;
9724 exception_handler = savehandler;
9730 goodname(const char *p)
9732 return endofname(p)[0] == '\0';
9737 * Search for a command. This is called before we fork so that the
9738 * location of the command will be available in the parent as well as
9739 * the child. The check for "goodname" is an overly conservative
9740 * check that the name will not be subject to expansion.
9743 prehash(union node *n)
9745 struct cmdentry entry;
9747 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9748 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9752 /* ============ Builtin commands
9754 * Builtin commands whose functions are closely tied to evaluation
9755 * are implemented here.
9759 * Handle break and continue commands. Break, continue, and return are
9760 * all handled by setting the evalskip flag. The evaluation routines
9761 * above all check this flag, and if it is set they start skipping
9762 * commands rather than executing them. The variable skipcount is
9763 * the number of loops to break/continue, or the number of function
9764 * levels to return. (The latter is always 1.) It should probably
9765 * be an error to break out of more loops than exist, but it isn't
9766 * in the standard shell so we don't make it one here.
9768 static int FAST_FUNC
9769 breakcmd(int argc UNUSED_PARAM, char **argv)
9771 int n = argv[1] ? number(argv[1]) : 1;
9774 ash_msg_and_raise_error(msg_illnum, argv[1]);
9778 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9786 * This implements the input routines used by the parser.
9790 INPUT_PUSH_FILE = 1,
9791 INPUT_NOFILE_OK = 2,
9794 static smallint checkkwd;
9795 /* values of checkkwd variable */
9796 #define CHKALIAS 0x1
9801 * Push a string back onto the input at this current parsefile level.
9802 * We handle aliases this way.
9804 #if !ENABLE_ASH_ALIAS
9805 #define pushstring(s, ap) pushstring(s)
9808 pushstring(char *s, struct alias *ap)
9815 if (g_parsefile->strpush) {
9816 sp = ckzalloc(sizeof(*sp));
9817 sp->prev = g_parsefile->strpush;
9819 sp = &(g_parsefile->basestrpush);
9821 g_parsefile->strpush = sp;
9822 sp->prev_string = g_parsefile->next_to_pgetc;
9823 sp->prev_left_in_line = g_parsefile->left_in_line;
9824 sp->unget = g_parsefile->unget;
9825 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9826 #if ENABLE_ASH_ALIAS
9829 ap->flag |= ALIASINUSE;
9833 g_parsefile->next_to_pgetc = s;
9834 g_parsefile->left_in_line = len;
9835 g_parsefile->unget = 0;
9842 struct strpush *sp = g_parsefile->strpush;
9845 #if ENABLE_ASH_ALIAS
9847 if (g_parsefile->next_to_pgetc[-1] == ' '
9848 || g_parsefile->next_to_pgetc[-1] == '\t'
9850 checkkwd |= CHKALIAS;
9852 if (sp->string != sp->ap->val) {
9855 sp->ap->flag &= ~ALIASINUSE;
9856 if (sp->ap->flag & ALIASDEAD) {
9857 unalias(sp->ap->name);
9861 g_parsefile->next_to_pgetc = sp->prev_string;
9862 g_parsefile->left_in_line = sp->prev_left_in_line;
9863 g_parsefile->unget = sp->unget;
9864 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9865 g_parsefile->strpush = sp->prev;
9866 if (sp != &(g_parsefile->basestrpush))
9875 char *buf = g_parsefile->buf;
9877 g_parsefile->next_to_pgetc = buf;
9878 #if ENABLE_FEATURE_EDITING
9880 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9881 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9884 # if ENABLE_ASH_IDLE_TIMEOUT
9886 const char *tmout_var = lookupvar("TMOUT");
9888 timeout = atoi(tmout_var) * 1000;
9894 # if ENABLE_FEATURE_TAB_COMPLETION
9895 line_input_state->path_lookup = pathval();
9897 reinit_unicode_for_ash();
9898 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9900 /* ^C pressed, "convert" to SIGINT */
9901 write(STDOUT_FILENO, "^C", 2);
9908 exitstatus = 128 + SIGINT;
9914 /* Ctrl+D pressed */
9917 # if ENABLE_ASH_IDLE_TIMEOUT
9918 else if (errno == EAGAIN && timeout > 0) {
9919 puts("\007timed out waiting for input: auto-logout");
9926 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9929 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9931 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9932 int flags = fcntl(0, F_GETFL);
9933 if (flags >= 0 && (flags & O_NONBLOCK)) {
9934 flags &= ~O_NONBLOCK;
9935 if (fcntl(0, F_SETFL, flags) >= 0) {
9936 out2str("sh: turning off NDELAY mode\n");
9947 * Refill the input buffer and return the next input character:
9949 * 1) If a string was pushed back on the input, pop it;
9950 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9951 * or we are reading from a string so we can't refill the buffer,
9953 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9954 * 4) Process input up to the next newline, deleting nul characters.
9956 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9957 #define pgetc_debug(...) ((void)0)
9958 static int pgetc(void);
9965 if (g_parsefile->strpush) {
9966 #if ENABLE_ASH_ALIAS
9967 if (g_parsefile->left_in_line == -1
9968 && g_parsefile->strpush->ap
9969 && g_parsefile->next_to_pgetc[-1] != ' '
9970 && g_parsefile->next_to_pgetc[-1] != '\t'
9972 pgetc_debug("preadbuffer PEOA");
9979 /* on both branches above g_parsefile->left_in_line < 0.
9980 * "pgetc" needs refilling.
9983 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9984 * pungetc() may increment it a few times.
9985 * Assuming it won't increment it to less than -90.
9987 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9988 pgetc_debug("preadbuffer PEOF1");
9989 /* even in failure keep left_in_line and next_to_pgetc
9990 * in lock step, for correct multi-layer pungetc.
9991 * left_in_line was decremented before preadbuffer(),
9992 * must inc next_to_pgetc: */
9993 g_parsefile->next_to_pgetc++;
9997 more = g_parsefile->left_in_buffer;
9999 flush_stdout_stderr();
10003 /* don't try reading again */
10004 g_parsefile->left_in_line = -99;
10005 pgetc_debug("preadbuffer PEOF2");
10006 g_parsefile->next_to_pgetc++;
10011 /* Find out where's the end of line.
10012 * Set g_parsefile->left_in_line
10013 * and g_parsefile->left_in_buffer acordingly.
10014 * NUL chars are deleted.
10016 q = g_parsefile->next_to_pgetc;
10024 memmove(q, q + 1, more);
10028 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10034 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10035 if (g_parsefile->left_in_line < 0)
10040 g_parsefile->left_in_buffer = more;
10045 out2str(g_parsefile->next_to_pgetc);
10049 pgetc_debug("preadbuffer at %d:%p'%s'",
10050 g_parsefile->left_in_line,
10051 g_parsefile->next_to_pgetc,
10052 g_parsefile->next_to_pgetc);
10053 return (unsigned char)*g_parsefile->next_to_pgetc++;
10059 g_parsefile->linno++;
10060 setprompt_if(doprompt, 2);
10065 g_parsefile->linno++;
10066 needprompt = doprompt;
10074 pgetc_debug("pgetc at %d:%p'%s'",
10075 g_parsefile->left_in_line,
10076 g_parsefile->next_to_pgetc,
10077 g_parsefile->next_to_pgetc);
10078 if (g_parsefile->unget)
10079 return g_parsefile->lastc[--g_parsefile->unget];
10081 if (--g_parsefile->left_in_line >= 0)
10082 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10086 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10087 g_parsefile->lastc[0] = c;
10092 #if ENABLE_ASH_ALIAS
10094 pgetc_without_PEOA(void)
10098 pgetc_debug("pgetc at %d:%p'%s'",
10099 g_parsefile->left_in_line,
10100 g_parsefile->next_to_pgetc,
10101 g_parsefile->next_to_pgetc);
10103 } while (c == PEOA);
10107 # define pgetc_without_PEOA() pgetc()
10111 * Read a line from the script.
10114 pfgets(char *line, int len)
10120 while (--nleft > 0) {
10121 c = pgetc_without_PEOA();
10136 * Undo a call to pgetc. Only two characters may be pushed back.
10137 * PEOF may be pushed back.
10142 g_parsefile->unget++;
10145 /* This one eats backslash+newline */
10151 while ((c = pgetc()) == '\\') {
10152 if (pgetc() != '\n') {
10164 * To handle the "." command, a stack of input files is used. Pushfile
10165 * adds a new entry to the stack and popfile restores the previous level.
10170 struct parsefile *pf;
10172 pf = ckzalloc(sizeof(*pf));
10173 pf->prev = g_parsefile;
10175 /*pf->strpush = NULL; - ckzalloc did it */
10176 /*pf->basestrpush.prev = NULL;*/
10184 struct parsefile *pf = g_parsefile;
10190 if (pf->pf_fd >= 0)
10193 while (pf->strpush)
10195 g_parsefile = pf->prev;
10201 * Return to top level.
10206 while (g_parsefile != &basepf)
10211 * Close the file(s) that the shell is reading commands from. Called
10212 * after a fork is done.
10218 if (g_parsefile->pf_fd > 0) {
10219 close(g_parsefile->pf_fd);
10220 g_parsefile->pf_fd = 0;
10225 * Like setinputfile, but takes an open file descriptor. Call this with
10229 setinputfd(int fd, int push)
10233 g_parsefile->buf = NULL;
10235 g_parsefile->pf_fd = fd;
10236 if (g_parsefile->buf == NULL)
10237 g_parsefile->buf = ckmalloc(IBUFSIZ);
10238 g_parsefile->left_in_buffer = 0;
10239 g_parsefile->left_in_line = 0;
10240 g_parsefile->linno = 1;
10244 * Set the input to take input from a file. If push is set, push the
10245 * old input onto the stack first.
10248 setinputfile(const char *fname, int flags)
10253 fd = open(fname, O_RDONLY);
10255 if (flags & INPUT_NOFILE_OK)
10258 ash_msg_and_raise_error("can't open '%s'", fname);
10263 close_on_exec_on(fd);
10264 setinputfd(fd, flags & INPUT_PUSH_FILE);
10271 * Like setinputfile, but takes input from a string.
10274 setinputstring(char *string)
10278 g_parsefile->next_to_pgetc = string;
10279 g_parsefile->left_in_line = strlen(string);
10280 g_parsefile->buf = NULL;
10281 g_parsefile->linno = 1;
10287 * Routines to check for mail.
10290 #if ENABLE_ASH_MAIL
10292 /* Hash of mtimes of mailboxes */
10293 static unsigned mailtime_hash;
10294 /* Set if MAIL or MAILPATH is changed. */
10295 static smallint mail_var_path_changed;
10298 * Print appropriate message(s) if mail has arrived.
10299 * If mail_var_path_changed is set,
10300 * then the value of MAIL has mail_var_path_changed,
10301 * so we just update the values.
10310 struct stackmark smark;
10313 setstackmark(&smark);
10314 mpath = mpathset() ? mpathval() : mailval();
10317 p = path_advance(&mpath, nullstr);
10322 for (q = p; *q; q++)
10328 q[-1] = '\0'; /* delete trailing '/' */
10329 if (stat(p, &statb) < 0) {
10332 /* Very simplistic "hash": just a sum of all mtimes */
10333 new_hash += (unsigned)statb.st_mtime;
10335 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10336 if (mailtime_hash != 0)
10337 out2str("you have mail\n");
10338 mailtime_hash = new_hash;
10340 mail_var_path_changed = 0;
10341 popstackmark(&smark);
10344 static void FAST_FUNC
10345 changemail(const char *val UNUSED_PARAM)
10347 mail_var_path_changed = 1;
10350 #endif /* ASH_MAIL */
10353 /* ============ ??? */
10356 * Set the shell parameters.
10359 setparam(char **argv)
10365 for (nparam = 0; argv[nparam]; nparam++)
10367 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10369 *ap++ = ckstrdup(*argv++);
10372 freeparam(&shellparam);
10373 shellparam.malloced = 1;
10374 shellparam.nparam = nparam;
10375 shellparam.p = newparam;
10376 #if ENABLE_ASH_GETOPTS
10377 shellparam.optind = 1;
10378 shellparam.optoff = -1;
10383 * Process shell options. The global variable argptr contains a pointer
10384 * to the argument list; we advance it past the options.
10386 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10387 * For a non-interactive shell, an error condition encountered
10388 * by a special built-in ... shall cause the shell to write a diagnostic message
10389 * to standard error and exit as shown in the following table:
10390 * Error Special Built-In
10392 * Utility syntax error (option or operand error) Shall exit
10394 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10395 * we see that bash does not do that (set "finishes" with error code 1 instead,
10396 * and shell continues), and people rely on this behavior!
10398 * set -o barfoo 2>/dev/null
10401 * Oh well. Let's mimic that.
10404 plus_minus_o(char *name, int val)
10409 for (i = 0; i < NOPTS; i++) {
10410 if (strcmp(name, optnames(i)) == 0) {
10415 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10418 for (i = 0; i < NOPTS; i++) {
10420 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10422 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10428 setoption(int flag, int val)
10432 for (i = 0; i < NOPTS; i++) {
10433 if (optletters(i) == flag) {
10438 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10442 options(int cmdline)
10450 while ((p = *argptr) != NULL) {
10452 if (c != '-' && c != '+')
10455 val = 0; /* val = 0 if c == '+' */
10458 if (p[0] == '\0' || LONE_DASH(p)) {
10460 /* "-" means turn off -x and -v */
10463 /* "--" means reset params */
10464 else if (*argptr == NULL)
10467 break; /* "-" or "--" terminates options */
10470 /* first char was + or - */
10471 while ((c = *p++) != '\0') {
10472 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10473 if (c == 'c' && cmdline) {
10474 minusc = p; /* command is after shell args */
10475 } else if (c == 'o') {
10476 if (plus_minus_o(*argptr, val)) {
10477 /* it already printed err message */
10478 return 1; /* error */
10482 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10484 /* bash does not accept +-login, we also won't */
10485 } else if (cmdline && val && (c == '-')) { /* long options */
10486 if (strcmp(p, "login") == 0)
10498 * The shift builtin command.
10500 static int FAST_FUNC
10501 shiftcmd(int argc UNUSED_PARAM, char **argv)
10508 n = number(argv[1]);
10509 if (n > shellparam.nparam)
10510 n = 0; /* bash compat, was = shellparam.nparam; */
10512 shellparam.nparam -= n;
10513 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10514 if (shellparam.malloced)
10517 ap2 = shellparam.p;
10518 while ((*ap2++ = *ap1++) != NULL)
10520 #if ENABLE_ASH_GETOPTS
10521 shellparam.optind = 1;
10522 shellparam.optoff = -1;
10529 * POSIX requires that 'set' (but not export or readonly) output the
10530 * variables in lexicographic order - by the locale's collating order (sigh).
10531 * Maybe we could keep them in an ordered balanced binary tree
10532 * instead of hashed lists.
10533 * For now just roll 'em through qsort for printing...
10536 showvars(const char *sep_prefix, int on, int off)
10539 char **ep, **epend;
10541 ep = listvars(on, off, &epend);
10542 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10544 sep = *sep_prefix ? " " : sep_prefix;
10546 for (; ep < epend; ep++) {
10550 p = strchrnul(*ep, '=');
10553 q = single_quote(++p);
10554 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10560 * The set command builtin.
10562 static int FAST_FUNC
10563 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10568 return showvars(nullstr, 0, VUNSET);
10571 retval = options(/*cmdline:*/ 0);
10572 if (retval == 0) { /* if no parse error... */
10574 if (*argptr != NULL) {
10582 #if ENABLE_ASH_RANDOM_SUPPORT
10583 static void FAST_FUNC
10584 change_random(const char *value)
10588 if (value == NULL) {
10589 /* "get", generate */
10590 t = next_random(&random_gen);
10591 /* set without recursion */
10592 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10593 vrandom.flags &= ~VNOFUNC;
10596 t = strtoul(value, NULL, 10);
10597 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10602 #if ENABLE_ASH_GETOPTS
10604 getopts(char *optstr, char *optvar, char **optfirst)
10611 int ind = shellparam.optind;
10612 int off = shellparam.optoff;
10616 shellparam.optind = -1;
10617 optnext = optfirst + ind - 1;
10619 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10622 p = optnext[-1] + off;
10623 if (p == NULL || *p == '\0') {
10624 /* Current word is done, advance */
10626 if (p == NULL || *p != '-' || *++p == '\0') {
10633 if (LONE_DASH(p)) /* check for "--" */
10638 for (q = optstr; *q != c;) {
10640 if (optstr[0] == ':') {
10642 /*sbuf[1] = '\0'; - already is */
10643 setvar0("OPTARG", sbuf);
10645 fprintf(stderr, "Illegal option -%c\n", c);
10646 unsetvar("OPTARG");
10656 if (*p == '\0' && (p = *optnext) == NULL) {
10657 if (optstr[0] == ':') {
10659 /*sbuf[1] = '\0'; - already is */
10660 setvar0("OPTARG", sbuf);
10663 fprintf(stderr, "No arg for -%c option\n", c);
10664 unsetvar("OPTARG");
10672 setvar0("OPTARG", p);
10675 setvar0("OPTARG", nullstr);
10677 ind = optnext - optfirst + 1;
10678 setvar("OPTIND", itoa(ind), VNOFUNC);
10680 /*sbuf[1] = '\0'; - already is */
10681 setvar0(optvar, sbuf);
10683 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10684 shellparam.optind = ind;
10690 * The getopts builtin. Shellparam.optnext points to the next argument
10691 * to be processed. Shellparam.optptr points to the next character to
10692 * be processed in the current argument. If shellparam.optnext is NULL,
10693 * then it's the first time getopts has been called.
10695 static int FAST_FUNC
10696 getoptscmd(int argc, char **argv)
10701 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10703 optbase = shellparam.p;
10704 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10705 shellparam.optind = 1;
10706 shellparam.optoff = -1;
10709 optbase = &argv[3];
10710 if ((unsigned)shellparam.optind > argc - 2) {
10711 shellparam.optind = 1;
10712 shellparam.optoff = -1;
10716 return getopts(argv[1], argv[2], optbase);
10718 #endif /* ASH_GETOPTS */
10721 /* ============ Shell parser */
10724 struct heredoc *next; /* next here document in list */
10725 union node *here; /* redirection node */
10726 char *eofmark; /* string indicating end of input */
10727 smallint striptabs; /* if set, strip leading tabs */
10730 static smallint tokpushback; /* last token pushed back */
10731 static smallint quoteflag; /* set if (part of) last token was quoted */
10732 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10733 static struct heredoc *heredoclist; /* list of here documents to read */
10734 static char *wordtext; /* text of last word returned by readtoken */
10735 static struct nodelist *backquotelist;
10736 static union node *redirnode;
10737 static struct heredoc *heredoc;
10739 static const char *
10740 tokname(char *buf, int tok)
10743 return tokname_array[tok];
10744 sprintf(buf, "\"%s\"", tokname_array[tok]);
10748 /* raise_error_unexpected_syntax:
10749 * Called when an unexpected token is read during the parse. The argument
10750 * is the token that is expected, or -1 if more than one type of token can
10751 * occur at this point.
10753 static void raise_error_unexpected_syntax(int) NORETURN;
10755 raise_error_unexpected_syntax(int token)
10761 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10763 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10764 raise_error_syntax(msg);
10768 #define EOFMARKLEN 79
10770 /* parsing is heavily cross-recursive, need these forward decls */
10771 static union node *andor(void);
10772 static union node *pipeline(void);
10773 static union node *parse_command(void);
10774 static void parseheredoc(void);
10775 static int peektoken(void);
10776 static int readtoken(void);
10778 static union node *
10781 union node *n1, *n2, *n3;
10786 switch (peektoken()) {
10794 if (!n1 && (nlflag & 1))
10800 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10801 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10807 if (tok == TBACKGND) {
10808 if (n2->type == NPIPE) {
10809 n2->npipe.pipe_backgnd = 1;
10811 if (n2->type != NREDIR) {
10812 n3 = stzalloc(sizeof(struct nredir));
10814 /*n3->nredir.redirect = NULL; - stzalloc did it */
10817 n2->type = NBACKGND;
10823 n3 = stzalloc(sizeof(struct nbinary));
10825 n3->nbinary.ch1 = n1;
10826 n3->nbinary.ch2 = n2;
10839 raise_error_unexpected_syntax(-1);
10846 static union node *
10849 union node *n1, *n2, *n3;
10857 } else if (t == TOR) {
10863 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10865 n3 = stzalloc(sizeof(struct nbinary));
10867 n3->nbinary.ch1 = n1;
10868 n3->nbinary.ch2 = n2;
10873 static union node *
10876 union node *n1, *n2, *pipenode;
10877 struct nodelist *lp, *prev;
10881 TRACE(("pipeline: entered\n"));
10882 if (readtoken() == TNOT) {
10884 checkkwd = CHKKWD | CHKALIAS;
10887 n1 = parse_command();
10888 if (readtoken() == TPIPE) {
10889 pipenode = stzalloc(sizeof(struct npipe));
10890 pipenode->type = NPIPE;
10891 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10892 lp = stzalloc(sizeof(struct nodelist));
10893 pipenode->npipe.cmdlist = lp;
10897 lp = stzalloc(sizeof(struct nodelist));
10898 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10899 lp->n = parse_command();
10901 } while (readtoken() == TPIPE);
10907 n2 = stzalloc(sizeof(struct nnot));
10915 static union node *
10920 n = stzalloc(sizeof(struct narg));
10922 /*n->narg.next = NULL; - stzalloc did it */
10923 n->narg.text = wordtext;
10924 n->narg.backquote = backquotelist;
10929 fixredir(union node *n, const char *text, int err)
10933 TRACE(("Fix redir %s %d\n", text, err));
10935 n->ndup.vname = NULL;
10937 fd = bb_strtou(text, NULL, 10);
10938 if (!errno && fd >= 0)
10939 n->ndup.dupfd = fd;
10940 else if (LONE_DASH(text))
10941 n->ndup.dupfd = -1;
10944 raise_error_syntax("bad fd number");
10945 n->ndup.vname = makename();
10950 * Returns true if the text contains nothing to expand (no dollar signs
10954 noexpand(const char *text)
10958 while ((c = *text++) != '\0') {
10959 if (c == CTLQUOTEMARK)
10963 else if (SIT(c, BASESYNTAX) == CCTL)
10972 union node *n = redirnode;
10974 if (readtoken() != TWORD)
10975 raise_error_unexpected_syntax(-1);
10976 if (n->type == NHERE) {
10977 struct heredoc *here = heredoc;
10981 if (quoteflag == 0)
10983 TRACE(("Here document %d\n", n->type));
10984 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10985 raise_error_syntax("illegal eof marker for << redirection");
10986 rmescapes(wordtext, 0);
10987 here->eofmark = wordtext;
10989 if (heredoclist == NULL)
10990 heredoclist = here;
10992 for (p = heredoclist; p->next; p = p->next)
10996 } else if (n->type == NTOFD || n->type == NFROMFD) {
10997 fixredir(n, wordtext, 0);
10999 n->nfile.fname = makename();
11003 static union node *
11006 union node *args, **app;
11007 union node *n = NULL;
11008 union node *vars, **vpp;
11009 union node **rpp, *redir;
11011 #if ENABLE_ASH_BASH_COMPAT
11012 smallint double_brackets_flag = 0;
11013 smallint function_flag = 0;
11023 savecheckkwd = CHKALIAS;
11026 checkkwd = savecheckkwd;
11029 #if ENABLE_ASH_BASH_COMPAT
11031 if (peektoken() != TWORD)
11032 raise_error_unexpected_syntax(TWORD);
11035 case TAND: /* "&&" */
11036 case TOR: /* "||" */
11037 if (!double_brackets_flag) {
11041 wordtext = (char *) (t == TAND ? "-a" : "-o");
11044 n = stzalloc(sizeof(struct narg));
11046 /*n->narg.next = NULL; - stzalloc did it */
11047 n->narg.text = wordtext;
11048 #if ENABLE_ASH_BASH_COMPAT
11049 if (strcmp("[[", wordtext) == 0)
11050 double_brackets_flag = 1;
11051 else if (strcmp("]]", wordtext) == 0)
11052 double_brackets_flag = 0;
11054 n->narg.backquote = backquotelist;
11055 if (savecheckkwd && isassignment(wordtext)) {
11057 vpp = &n->narg.next;
11060 app = &n->narg.next;
11063 #if ENABLE_ASH_BASH_COMPAT
11064 if (function_flag) {
11065 checkkwd = CHKNL | CHKKWD;
11066 switch (peektoken()) {
11078 if (strcmp("[[", wordtext) == 0)
11082 raise_error_unexpected_syntax(-1);
11088 *rpp = n = redirnode;
11089 rpp = &n->nfile.next;
11090 parsefname(); /* read name of redirection file */
11093 IF_ASH_BASH_COMPAT(do_func:)
11094 if (args && app == &args->narg.next
11097 struct builtincmd *bcmd;
11100 /* We have a function */
11101 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11102 raise_error_unexpected_syntax(TRP);
11103 name = n->narg.text;
11104 if (!goodname(name)
11105 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11107 raise_error_syntax("bad function name");
11110 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11111 n->narg.next = parse_command();
11114 IF_ASH_BASH_COMPAT(function_flag = 0;)
11125 n = stzalloc(sizeof(struct ncmd));
11127 n->ncmd.args = args;
11128 n->ncmd.assign = vars;
11129 n->ncmd.redirect = redir;
11133 static union node *
11134 parse_command(void)
11136 union node *n1, *n2;
11137 union node *ap, **app;
11138 union node *cp, **cpp;
11139 union node *redir, **rpp;
11146 switch (readtoken()) {
11148 raise_error_unexpected_syntax(-1);
11151 n1 = stzalloc(sizeof(struct nif));
11153 n1->nif.test = list(0);
11154 if (readtoken() != TTHEN)
11155 raise_error_unexpected_syntax(TTHEN);
11156 n1->nif.ifpart = list(0);
11158 while (readtoken() == TELIF) {
11159 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11160 n2 = n2->nif.elsepart;
11162 n2->nif.test = list(0);
11163 if (readtoken() != TTHEN)
11164 raise_error_unexpected_syntax(TTHEN);
11165 n2->nif.ifpart = list(0);
11167 if (lasttoken == TELSE)
11168 n2->nif.elsepart = list(0);
11170 n2->nif.elsepart = NULL;
11178 n1 = stzalloc(sizeof(struct nbinary));
11179 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11180 n1->nbinary.ch1 = list(0);
11183 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11184 got == TWORD ? wordtext : ""));
11185 raise_error_unexpected_syntax(TDO);
11187 n1->nbinary.ch2 = list(0);
11192 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11193 raise_error_syntax("bad for loop variable");
11194 n1 = stzalloc(sizeof(struct nfor));
11196 n1->nfor.var = wordtext;
11197 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11198 if (readtoken() == TIN) {
11200 while (readtoken() == TWORD) {
11201 n2 = stzalloc(sizeof(struct narg));
11203 /*n2->narg.next = NULL; - stzalloc did it */
11204 n2->narg.text = wordtext;
11205 n2->narg.backquote = backquotelist;
11207 app = &n2->narg.next;
11210 n1->nfor.args = ap;
11211 if (lasttoken != TNL && lasttoken != TSEMI)
11212 raise_error_unexpected_syntax(-1);
11214 n2 = stzalloc(sizeof(struct narg));
11216 /*n2->narg.next = NULL; - stzalloc did it */
11217 n2->narg.text = (char *)dolatstr;
11218 /*n2->narg.backquote = NULL;*/
11219 n1->nfor.args = n2;
11221 * Newline or semicolon here is optional (but note
11222 * that the original Bourne shell only allowed NL).
11224 if (lasttoken != TSEMI)
11227 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11228 if (readtoken() != TDO)
11229 raise_error_unexpected_syntax(TDO);
11230 n1->nfor.body = list(0);
11234 n1 = stzalloc(sizeof(struct ncase));
11236 if (readtoken() != TWORD)
11237 raise_error_unexpected_syntax(TWORD);
11238 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11240 /*n2->narg.next = NULL; - stzalloc did it */
11241 n2->narg.text = wordtext;
11242 n2->narg.backquote = backquotelist;
11243 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11244 if (readtoken() != TIN)
11245 raise_error_unexpected_syntax(TIN);
11246 cpp = &n1->ncase.cases;
11248 checkkwd = CHKNL | CHKKWD;
11250 while (t != TESAC) {
11251 if (lasttoken == TLP)
11253 *cpp = cp = stzalloc(sizeof(struct nclist));
11255 app = &cp->nclist.pattern;
11257 *app = ap = stzalloc(sizeof(struct narg));
11259 /*ap->narg.next = NULL; - stzalloc did it */
11260 ap->narg.text = wordtext;
11261 ap->narg.backquote = backquotelist;
11262 if (readtoken() != TPIPE)
11264 app = &ap->narg.next;
11267 //ap->narg.next = NULL;
11268 if (lasttoken != TRP)
11269 raise_error_unexpected_syntax(TRP);
11270 cp->nclist.body = list(2);
11272 cpp = &cp->nclist.next;
11274 checkkwd = CHKNL | CHKKWD;
11278 raise_error_unexpected_syntax(TENDCASE);
11285 n1 = stzalloc(sizeof(struct nredir));
11286 n1->type = NSUBSHELL;
11287 n1->nredir.n = list(0);
11288 /*n1->nredir.redirect = NULL; - stzalloc did it */
11295 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11299 return simplecmd();
11302 if (readtoken() != t)
11303 raise_error_unexpected_syntax(t);
11306 /* Now check for redirection which may follow command */
11307 checkkwd = CHKKWD | CHKALIAS;
11309 while (readtoken() == TREDIR) {
11310 *rpp = n2 = redirnode;
11311 rpp = &n2->nfile.next;
11317 if (n1->type != NSUBSHELL) {
11318 n2 = stzalloc(sizeof(struct nredir));
11323 n1->nredir.redirect = redir;
11328 #if ENABLE_ASH_BASH_COMPAT
11330 decode_dollar_squote(void)
11332 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11338 p = strchr(C_escapes, c);
11343 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11347 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11349 } else if (c == 'x') { /* \xHH */
11353 } while (isxdigit(c) && --cnt);
11355 if (cnt == 3) { /* \x but next char is "bad" */
11359 } else { /* simple seq like \\ or \t */
11364 c = bb_process_escape_sequence((void*)&p);
11365 } else { /* unrecognized "\z": print both chars unless ' or " */
11366 if (c != '\'' && c != '"') {
11368 c |= 0x100; /* "please encode \, then me" */
11376 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11377 * is not NULL, read a here document. In the latter case, eofmark is the
11378 * word which marks the end of the document and striptabs is true if
11379 * leading tabs should be stripped from the document. The argument c
11380 * is the first character of the input token or document.
11382 * Because C does not have internal subroutines, I have simulated them
11383 * using goto's to implement the subroutine linkage. The following macros
11384 * will run code that appears at the end of readtoken1.
11386 #define CHECKEND() {goto checkend; checkend_return:;}
11387 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11388 #define PARSESUB() {goto parsesub; parsesub_return:;}
11389 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11390 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11391 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11393 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11395 /* NB: syntax parameter fits into smallint */
11396 /* c parameter is an unsigned char or PEOF or PEOA */
11399 char line[EOFMARKLEN + 1];
11400 struct nodelist *bqlist;
11404 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11405 #if ENABLE_ASH_EXPAND_PRMT
11406 smallint pssyntax; /* we are expanding a prompt string */
11408 int varnest; /* levels of variables expansion */
11409 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11410 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11411 int dqvarnest; /* levels of variables expansion within double quotes */
11413 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11415 startlinno = g_parsefile->linno;
11418 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11419 #if ENABLE_ASH_EXPAND_PRMT
11420 pssyntax = (syntax == PSSYNTAX);
11424 dblquote = (syntax == DQSYNTAX);
11426 IF_FEATURE_SH_MATH(arinest = 0;)
11427 IF_FEATURE_SH_MATH(parenlevel = 0;)
11430 STARTSTACKSTR(out);
11432 /* For each line, until end of word */
11433 CHECKEND(); /* set c to PEOF if at end of here document */
11434 for (;;) { /* until end of line or end of word */
11435 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11436 switch (SIT(c, syntax)) {
11437 case CNL: /* '\n' */
11438 if (syntax == BASESYNTAX)
11439 goto endword; /* exit outer loop */
11443 goto loop; /* continue outer loop */
11448 #if ENABLE_ASH_BASH_COMPAT
11449 if (c == '\\' && bash_dollar_squote) {
11450 c = decode_dollar_squote();
11452 /* skip $'\000', $'\x00' (like bash) */
11456 /* Unknown escape. Encode as '\z' */
11457 c = (unsigned char)c;
11458 if (eofmark == NULL || dblquote)
11459 USTPUTC(CTLESC, out);
11460 USTPUTC('\\', out);
11464 if (eofmark == NULL || dblquote)
11465 USTPUTC(CTLESC, out);
11468 case CBACK: /* backslash */
11469 c = pgetc_without_PEOA();
11471 USTPUTC(CTLESC, out);
11472 USTPUTC('\\', out);
11474 } else if (c == '\n') {
11477 #if ENABLE_ASH_EXPAND_PRMT
11478 if (c == '$' && pssyntax) {
11479 USTPUTC(CTLESC, out);
11480 USTPUTC('\\', out);
11483 /* Backslash is retained if we are in "str" and next char isn't special */
11488 && (c != '"' || eofmark != NULL)
11490 USTPUTC('\\', out);
11492 USTPUTC(CTLESC, out);
11500 if (eofmark == NULL) {
11501 USTPUTC(CTLQUOTEMARK, out);
11509 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11510 if (eofmark != NULL && varnest == 0) {
11513 if (dqvarnest == 0) {
11514 syntax = BASESYNTAX;
11521 case CVAR: /* '$' */
11522 PARSESUB(); /* parse substitution */
11524 case CENDVAR: /* '}' */
11527 if (dqvarnest > 0) {
11534 #if ENABLE_FEATURE_SH_MATH
11535 case CLP: /* '(' in arithmetic */
11539 case CRP: /* ')' in arithmetic */
11540 if (parenlevel > 0) {
11543 if (pgetc_eatbnl() == ')') {
11545 if (--arinest == 0) {
11546 syntax = prevsyntax;
11550 * unbalanced parens
11551 * (don't 2nd guess - no error)
11559 case CBQUOTE: /* '`' */
11563 goto endword; /* exit outer loop */
11567 if (varnest == 0) {
11568 #if ENABLE_ASH_BASH_COMPAT
11570 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11571 if (pgetc() == '>')
11572 c = 0x100 + '>'; /* flag &> */
11576 goto endword; /* exit outer loop */
11578 IF_ASH_ALIAS(if (c != PEOA))
11585 #if ENABLE_FEATURE_SH_MATH
11586 if (syntax == ARISYNTAX)
11587 raise_error_syntax("missing '))'");
11589 if (syntax != BASESYNTAX && eofmark == NULL)
11590 raise_error_syntax("unterminated quoted string");
11591 if (varnest != 0) {
11592 startlinno = g_parsefile->linno;
11594 raise_error_syntax("missing '}'");
11596 USTPUTC('\0', out);
11597 len = out - (char *)stackblock();
11598 out = stackblock();
11599 if (eofmark == NULL) {
11600 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11603 if (isdigit_str9(out)) {
11604 PARSEREDIR(); /* passed as params: out, c */
11605 lasttoken = TREDIR;
11608 /* else: non-number X seen, interpret it
11609 * as "NNNX>file" = "NNNX >file" */
11613 quoteflag = quotef;
11614 backquotelist = bqlist;
11615 grabstackblock(len);
11619 /* end of readtoken routine */
11622 * Check to see whether we are at the end of the here document. When this
11623 * is called, c is set to the first character of the next input line. If
11624 * we are at the end of the here document, this routine sets the c to PEOF.
11628 #if ENABLE_ASH_ALIAS
11630 c = pgetc_without_PEOA();
11633 while (c == '\t') {
11634 c = pgetc_without_PEOA();
11637 if (c == *eofmark) {
11638 if (pfgets(line, sizeof(line)) != NULL) {
11643 for (q = eofmark + 1;; p++, q++) {
11647 if (!*q || cc != *q)
11654 pushstring(line, NULL);
11659 goto checkend_return;
11663 * Parse a redirection operator. The variable "out" points to a string
11664 * specifying the fd to be redirected. The variable "c" contains the
11665 * first character of the redirection operator.
11668 /* out is already checked to be a valid number or "" */
11669 int fd = (*out == '\0' ? -1 : atoi(out));
11672 np = stzalloc(sizeof(struct nfile));
11677 np->type = NAPPEND;
11679 np->type = NCLOBBER;
11682 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11688 #if ENABLE_ASH_BASH_COMPAT
11689 else if (c == 0x100 + '>') { /* this flags &> redirection */
11691 pgetc(); /* this is '>', no need to check */
11695 else { /* c == '<' */
11696 /*np->nfile.fd = 0; - stzalloc did it */
11700 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11701 np = stzalloc(sizeof(struct nhere));
11702 /*np->nfile.fd = 0; - stzalloc did it */
11705 heredoc = stzalloc(sizeof(struct heredoc));
11706 heredoc->here = np;
11709 heredoc->striptabs = 1;
11711 /*heredoc->striptabs = 0; - stzalloc did it */
11717 np->type = NFROMFD;
11721 np->type = NFROMTO;
11733 goto parseredir_return;
11737 * Parse a substitution. At this point, we have read the dollar sign
11738 * and nothing else.
11741 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11742 * (assuming ascii char codes, as the original implementation did) */
11743 #define is_special(c) \
11744 (((unsigned)(c) - 33 < 32) \
11745 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11747 unsigned char subtype;
11750 c = pgetc_eatbnl();
11751 if (c > 255 /* PEOA or PEOF */
11752 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11754 #if ENABLE_ASH_BASH_COMPAT
11755 if (syntax != DQSYNTAX && c == '\'')
11756 bash_dollar_squote = 1;
11761 } else if (c == '(') {
11762 /* $(command) or $((arith)) */
11763 if (pgetc_eatbnl() == '(') {
11764 #if ENABLE_FEATURE_SH_MATH
11767 raise_error_syntax("you disabled math support for $((arith)) syntax");
11774 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11775 USTPUTC(CTLVAR, out);
11776 typeloc = out - (char *)stackblock();
11778 subtype = VSNORMAL;
11780 c = pgetc_eatbnl();
11785 /* $[{[#]]NAME[}] */
11788 c = pgetc_eatbnl();
11789 } while (is_in_name(c));
11790 } else if (isdigit(c)) {
11791 /* $[{[#]]NUM[}] */
11794 c = pgetc_eatbnl();
11795 } while (isdigit(c));
11796 } else if (is_special(c)) {
11797 /* $[{[#]]<specialchar>[}] */
11800 c = pgetc_eatbnl();
11801 if (!subtype && cc == '#') {
11802 subtype = VSLENGTH;
11803 if (c == '_' || isalnum(c))
11806 c = pgetc_eatbnl();
11807 if (cc == '}' || c != '}') {
11818 if (c != '}' && subtype == VSLENGTH) {
11819 /* ${#VAR didn't end with } */
11823 if (subtype == 0) {
11824 static const char types[] ALIGN1 = "}-+?=";
11825 /* ${VAR...} but not $VAR or ${#VAR} */
11826 /* c == first char after VAR */
11829 c = pgetc_eatbnl();
11830 #if ENABLE_ASH_BASH_COMPAT
11831 /* This check is only needed to not misinterpret
11832 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11835 if (!strchr(types, c)) {
11836 subtype = VSSUBSTR;
11838 break; /* "goto badsub" is bigger (!) */
11844 const char *p = strchr(types, c);
11847 subtype |= p - types + VSNORMAL;
11853 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11854 c = pgetc_eatbnl();
11860 #if ENABLE_ASH_BASH_COMPAT
11862 /* ${v/[/]pattern/repl} */
11863 //TODO: encode pattern and repl separately.
11864 // Currently ${v/$var_with_slash/repl} is horribly broken
11865 subtype = VSREPLACE;
11866 c = pgetc_eatbnl();
11869 subtype++; /* VSREPLACEALL */
11877 ((unsigned char *)stackblock())[typeloc] = subtype;
11878 if (subtype != VSNORMAL) {
11885 goto parsesub_return;
11889 * Called to parse command substitutions. Newstyle is set if the command
11890 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11891 * list of commands (passed by reference), and savelen is the number of
11892 * characters on the top of the stack which must be preserved.
11895 struct nodelist **nlpp;
11899 smallint saveprompt = 0;
11902 savelen = out - (char *)stackblock();
11905 * FIXME: this can allocate very large block on stack and SEGV.
11907 * echo "..<100kbytes>..`true` $(true) `true` ..."
11908 * allocates 100kb for every command subst. With about
11909 * a hundred command substitutions stack overflows.
11910 * With larger prepended string, SEGV happens sooner.
11912 str = alloca(savelen);
11913 memcpy(str, stackblock(), savelen);
11917 /* We must read until the closing backquote, giving special
11918 * treatment to some slashes, and then push the string and
11919 * reread it as input, interpreting it normally.
11925 STARTSTACKSTR(pout);
11929 setprompt_if(needprompt, 2);
11940 * If eating a newline, avoid putting
11941 * the newline into the new character
11942 * stream (via the STPUTC after the
11947 if (pc != '\\' && pc != '`' && pc != '$'
11948 && (!dblquote || pc != '"')
11950 STPUTC('\\', pout);
11952 if (pc <= 255 /* not PEOA or PEOF */) {
11958 IF_ASH_ALIAS(case PEOA:)
11959 startlinno = g_parsefile->linno;
11960 raise_error_syntax("EOF in backquote substitution");
11972 STPUTC('\0', pout);
11973 psavelen = pout - (char *)stackblock();
11974 if (psavelen > 0) {
11975 pstr = grabstackstr(pout);
11976 setinputstring(pstr);
11981 nlpp = &(*nlpp)->next;
11982 *nlpp = stzalloc(sizeof(**nlpp));
11983 /* (*nlpp)->next = NULL; - stzalloc did it */
11986 saveprompt = doprompt;
11993 doprompt = saveprompt;
11994 else if (readtoken() != TRP)
11995 raise_error_unexpected_syntax(TRP);
12000 * Start reading from old file again, ignoring any pushed back
12001 * tokens left from the backquote parsing
12006 while (stackblocksize() <= savelen)
12008 STARTSTACKSTR(out);
12010 memcpy(out, str, savelen);
12011 STADJUST(savelen, out);
12013 USTPUTC(CTLBACKQ, out);
12015 goto parsebackq_oldreturn;
12016 goto parsebackq_newreturn;
12019 #if ENABLE_FEATURE_SH_MATH
12021 * Parse an arithmetic expansion (indicate start of one and set state)
12024 if (++arinest == 1) {
12025 prevsyntax = syntax;
12026 syntax = ARISYNTAX;
12028 USTPUTC(CTLARI, out);
12029 goto parsearith_return;
12032 } /* end of readtoken */
12035 * Read the next input token.
12036 * If the token is a word, we set backquotelist to the list of cmds in
12037 * backquotes. We set quoteflag to true if any part of the word was
12039 * If the token is TREDIR, then we set redirnode to a structure containing
12041 * In all cases, the variable startlinno is set to the number of the line
12042 * on which the token starts.
12044 * [Change comment: here documents and internal procedures]
12045 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12046 * word parsing code into a separate routine. In this case, readtoken
12047 * doesn't need to have any internal procedures, but parseword does.
12048 * We could also make parseoperator in essence the main routine, and
12049 * have parseword (readtoken1?) handle both words and redirection.]
12051 #define NEW_xxreadtoken
12052 #ifdef NEW_xxreadtoken
12053 /* singles must be first! */
12054 static const char xxreadtoken_chars[7] ALIGN1 = {
12055 '\n', '(', ')', /* singles */
12056 '&', '|', ';', /* doubles */
12060 #define xxreadtoken_singles 3
12061 #define xxreadtoken_doubles 3
12063 static const char xxreadtoken_tokens[] ALIGN1 = {
12064 TNL, TLP, TRP, /* only single occurrence allowed */
12065 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12066 TEOF, /* corresponds to trailing nul */
12067 TAND, TOR, TENDCASE /* if double occurrence */
12079 setprompt_if(needprompt, 2);
12080 startlinno = g_parsefile->linno;
12081 for (;;) { /* until token or start of word found */
12083 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12087 while ((c = pgetc()) != '\n' && c != PEOF)
12090 } else if (c == '\\') {
12091 if (pgetc() != '\n') {
12093 break; /* return readtoken1(...) */
12099 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12105 p = strchr(xxreadtoken_chars, c);
12107 break; /* return readtoken1(...) */
12109 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12111 if (cc == c) { /* double occurrence? */
12112 p += xxreadtoken_doubles + 1;
12115 #if ENABLE_ASH_BASH_COMPAT
12116 if (c == '&' && cc == '>') /* &> */
12117 break; /* return readtoken1(...) */
12122 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12127 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12129 #else /* old xxreadtoken */
12130 #define RETURN(token) return lasttoken = token
12140 setprompt_if(needprompt, 2);
12141 startlinno = g_parsefile->linno;
12142 for (;;) { /* until token or start of word found */
12145 case ' ': case '\t':
12146 IF_ASH_ALIAS(case PEOA:)
12149 while ((c = pgetc()) != '\n' && c != PEOF)
12154 if (pgetc() == '\n') {
12166 if (pgetc() == '&')
12171 if (pgetc() == '|')
12176 if (pgetc() == ';')
12189 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12192 #endif /* old xxreadtoken */
12198 int kwd = checkkwd;
12200 smallint alreadyseen = tokpushback;
12203 #if ENABLE_ASH_ALIAS
12219 if (t != TWORD || quoteflag) {
12224 * check for keywords
12226 if (kwd & CHKKWD) {
12227 const char *const *pp;
12229 pp = findkwd(wordtext);
12231 lasttoken = t = pp - tokname_array;
12232 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12237 if (checkkwd & CHKALIAS) {
12238 #if ENABLE_ASH_ALIAS
12240 ap = lookupalias(wordtext, 1);
12243 pushstring(ap->val, ap);
12253 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12255 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12271 * Read and parse a command. Returns NODE_EOF on end of file.
12272 * (NULL is a valid parse tree indicating a blank line.)
12274 static union node *
12275 parsecmd(int interact)
12280 doprompt = interact;
12281 setprompt_if(doprompt, doprompt);
12287 * Input any here documents.
12292 struct heredoc *here;
12295 here = heredoclist;
12296 heredoclist = NULL;
12299 setprompt_if(needprompt, 2);
12300 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12301 here->eofmark, here->striptabs);
12302 n = stzalloc(sizeof(struct narg));
12303 n->narg.type = NARG;
12304 /*n->narg.next = NULL; - stzalloc did it */
12305 n->narg.text = wordtext;
12306 n->narg.backquote = backquotelist;
12307 here->here->nhere.doc = n;
12314 * called by editline -- any expansions to the prompt should be added here.
12316 #if ENABLE_ASH_EXPAND_PRMT
12317 static const char *
12318 expandstr(const char *ps)
12323 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12324 * and token processing _can_ alter it (delete NULs etc). */
12325 setinputstring((char *)ps);
12327 saveprompt = doprompt;
12329 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12330 doprompt = saveprompt;
12334 n.narg.type = NARG;
12335 n.narg.next = NULL;
12336 n.narg.text = wordtext;
12337 n.narg.backquote = backquotelist;
12339 expandarg(&n, NULL, EXP_QUOTED);
12340 return stackblock();
12345 * Execute a command or commands contained in a string.
12348 evalstring(char *s, int flags)
12350 struct jmploc *volatile savehandler;
12351 struct jmploc jmploc;
12355 struct stackmark smark;
12360 setstackmark(&smark);
12363 /* On exception inside execution loop, we must popfile().
12364 * Try interactively:
12366 * command eval "a=b" # throws "is read only" error
12367 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12368 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12370 savehandler = exception_handler;
12371 ex = setjmp(jmploc.loc);
12374 exception_handler = &jmploc;
12376 while ((n = parsecmd(0)) != NODE_EOF) {
12379 i = evaltree(n, flags);
12382 popstackmark(&smark);
12387 popstackmark(&smark);
12391 exception_handler = savehandler;
12393 longjmp(exception_handler->loc, ex);
12399 * The eval command.
12401 static int FAST_FUNC
12402 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12411 STARTSTACKSTR(concat);
12413 concat = stack_putstr(p, concat);
12417 STPUTC(' ', concat);
12419 STPUTC('\0', concat);
12420 p = grabstackstr(concat);
12422 return evalstring(p, flags & EV_TESTED);
12428 * Read and execute commands.
12429 * "Top" is nonzero for the top level command loop;
12430 * it turns on prompting if the shell is interactive.
12436 struct stackmark smark;
12441 TRACE(("cmdloop(%d) called\n", top));
12445 setstackmark(&smark);
12448 showjobs(SHOW_CHANGED|SHOW_STDERR);
12451 if (iflag && top) {
12455 n = parsecmd(inter);
12457 if (DEBUG > 2 && debug && (n != NODE_EOF))
12460 if (n == NODE_EOF) {
12461 if (!top || numeof >= 50)
12463 if (!stoppedjobs()) {
12466 out2str("\nUse \"exit\" to leave shell.\n");
12469 } else if (nflag == 0) {
12472 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12475 i = evaltree(n, 0);
12479 popstackmark(&smark);
12483 evalskip &= ~SKIPFUNC;
12491 * Take commands from a file. To be compatible we should do a path
12492 * search for the file, which is necessary to find sub-commands.
12495 find_dot_file(char *name)
12498 const char *path = pathval();
12501 /* don't try this for absolute or relative paths */
12502 if (strchr(name, '/'))
12505 /* IIRC standards do not say whether . is to be searched.
12506 * And it is even smaller this way, making it unconditional for now:
12508 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12513 while ((fullname = path_advance(&path, name)) != NULL) {
12515 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12517 * Don't bother freeing here, since it will
12518 * be freed by the caller.
12522 if (fullname != name)
12523 stunalloc(fullname);
12526 /* not found in the PATH */
12527 ash_msg_and_raise_error("%s: not found", name);
12531 static int FAST_FUNC
12532 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12534 /* "false; . empty_file; echo $?" should print 0, not 1: */
12538 char *args_need_save;
12539 struct strlist *sp;
12540 volatile struct shparam saveparam;
12542 for (sp = cmdenviron; sp; sp = sp->next)
12543 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12545 nextopt(nullstr); /* handle possible "--" */
12549 /* bash says: "bash: .: filename argument required" */
12550 return 2; /* bash compat */
12553 /* This aborts if file isn't found, which is POSIXly correct.
12554 * bash returns exitcode 1 instead.
12556 fullname = find_dot_file(argv[0]);
12558 args_need_save = argv[0];
12559 if (args_need_save) { /* . FILE ARGS, ARGS exist */
12561 saveparam = shellparam;
12562 shellparam.malloced = 0;
12566 shellparam.nparam = argc;
12567 shellparam.p = argv;
12570 /* This aborts if file can't be opened, which is POSIXly correct.
12571 * bash returns exitcode 1 instead.
12573 setinputfile(fullname, INPUT_PUSH_FILE);
12574 commandname = fullname;
12575 status = cmdloop(0);
12578 if (args_need_save) {
12579 freeparam(&shellparam);
12580 shellparam = saveparam;
12586 static int FAST_FUNC
12587 exitcmd(int argc UNUSED_PARAM, char **argv)
12592 exitstatus = number(argv[1]);
12593 raise_exception(EXEXIT);
12598 * Read a file containing shell functions.
12601 readcmdfile(char *name)
12603 setinputfile(name, INPUT_PUSH_FILE);
12609 /* ============ find_command inplementation */
12612 * Resolve a command name. If you change this routine, you may have to
12613 * change the shellexec routine as well.
12616 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12618 struct tblentry *cmdp;
12625 struct builtincmd *bcmd;
12627 /* If name contains a slash, don't use PATH or hash table */
12628 if (strchr(name, '/') != NULL) {
12629 entry->u.index = -1;
12630 if (act & DO_ABS) {
12631 while (stat(name, &statb) < 0) {
12633 if (errno == EINTR)
12636 entry->cmdtype = CMDUNKNOWN;
12640 entry->cmdtype = CMDNORMAL;
12644 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12646 updatetbl = (path == pathval());
12649 if (strstr(path, "%builtin") != NULL)
12650 act |= DO_ALTBLTIN;
12653 /* If name is in the table, check answer will be ok */
12654 cmdp = cmdlookup(name, 0);
12655 if (cmdp != NULL) {
12658 switch (cmdp->cmdtype) {
12676 } else if (cmdp->rehash == 0)
12677 /* if not invalidated by cd, we're done */
12681 /* If %builtin not in path, check for builtin next */
12682 bcmd = find_builtin(name);
12684 if (IS_BUILTIN_REGULAR(bcmd))
12685 goto builtin_success;
12686 if (act & DO_ALTPATH) {
12687 if (!(act & DO_ALTBLTIN))
12688 goto builtin_success;
12689 } else if (builtinloc <= 0) {
12690 goto builtin_success;
12694 #if ENABLE_FEATURE_SH_STANDALONE
12696 int applet_no = find_applet_by_name(name);
12697 if (applet_no >= 0) {
12698 entry->cmdtype = CMDNORMAL;
12699 entry->u.index = -2 - applet_no;
12705 /* We have to search path. */
12706 prev = -1; /* where to start */
12707 if (cmdp && cmdp->rehash) { /* doing a rehash */
12708 if (cmdp->cmdtype == CMDBUILTIN)
12711 prev = cmdp->param.index;
12717 while ((fullname = path_advance(&path, name)) != NULL) {
12718 stunalloc(fullname);
12719 /* NB: code below will still use fullname
12720 * despite it being "unallocated" */
12723 if (prefix(pathopt, "builtin")) {
12725 goto builtin_success;
12728 if ((act & DO_NOFUNC)
12729 || !prefix(pathopt, "func")
12730 ) { /* ignore unimplemented options */
12734 /* if rehash, don't redo absolute path names */
12735 if (fullname[0] == '/' && idx <= prev) {
12738 TRACE(("searchexec \"%s\": no change\n", name));
12741 while (stat(fullname, &statb) < 0) {
12743 if (errno == EINTR)
12746 if (errno != ENOENT && errno != ENOTDIR)
12750 e = EACCES; /* if we fail, this will be the error */
12751 if (!S_ISREG(statb.st_mode))
12753 if (pathopt) { /* this is a %func directory */
12754 stalloc(strlen(fullname) + 1);
12755 /* NB: stalloc will return space pointed by fullname
12756 * (because we don't have any intervening allocations
12757 * between stunalloc above and this stalloc) */
12758 readcmdfile(fullname);
12759 cmdp = cmdlookup(name, 0);
12760 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12761 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12762 stunalloc(fullname);
12765 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12767 entry->cmdtype = CMDNORMAL;
12768 entry->u.index = idx;
12772 cmdp = cmdlookup(name, 1);
12773 cmdp->cmdtype = CMDNORMAL;
12774 cmdp->param.index = idx;
12779 /* We failed. If there was an entry for this command, delete it */
12780 if (cmdp && updatetbl)
12781 delete_cmd_entry();
12783 ash_msg("%s: %s", name, errmsg(e, "not found"));
12784 entry->cmdtype = CMDUNKNOWN;
12789 entry->cmdtype = CMDBUILTIN;
12790 entry->u.cmd = bcmd;
12794 cmdp = cmdlookup(name, 1);
12795 cmdp->cmdtype = CMDBUILTIN;
12796 cmdp->param.cmd = bcmd;
12800 entry->cmdtype = cmdp->cmdtype;
12801 entry->u = cmdp->param;
12806 * The trap builtin.
12808 static int FAST_FUNC
12809 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12813 int signo, exitcode;
12818 for (signo = 0; signo < NSIG; signo++) {
12819 char *tr = trap_ptr[signo];
12821 /* note: bash adds "SIG", but only if invoked
12822 * as "bash". If called as "sh", or if set -o posix,
12823 * then it prints short signal names.
12824 * We are printing short names: */
12825 out1fmt("trap -- %s %s\n",
12827 get_signame(signo));
12828 /* trap_ptr != trap only if we are in special-cased `trap` code.
12829 * In this case, we will exit very soon, no need to free(). */
12830 /* if (trap_ptr != trap && tp[0]) */
12835 if (trap_ptr != trap) {
12848 signo = get_signum(*ap);
12850 /* Mimic bash message exactly */
12851 ash_msg("%s: invalid signal specification", *ap);
12857 if (LONE_DASH(action))
12860 if (action[0]) /* not NULL and not "" and not "-" */
12861 may_have_traps = 1;
12862 action = ckstrdup(action);
12866 trap[signo] = action;
12877 /* ============ Builtins */
12879 #if ENABLE_ASH_HELP
12880 static int FAST_FUNC
12881 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12887 "Built-in commands:\n"
12888 "------------------\n");
12889 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12890 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12891 builtintab[i].name + 1);
12897 # if ENABLE_FEATURE_SH_STANDALONE
12899 const char *a = applet_names;
12901 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12906 while (*a++ != '\0')
12911 newline_and_flush(stdout);
12912 return EXIT_SUCCESS;
12917 static int FAST_FUNC
12918 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12920 show_history(line_input_state);
12921 return EXIT_SUCCESS;
12926 * The export and readonly commands.
12928 static int FAST_FUNC
12929 exportcmd(int argc UNUSED_PARAM, char **argv)
12939 /* "readonly" in bash accepts, but ignores -n.
12940 * We do the same: it saves a conditional in nextopt's param.
12943 while ((opt = nextopt("np")) != '\0') {
12945 flag_off = VEXPORT;
12948 if (argv[0][0] == 'r') {
12950 flag_off = 0; /* readonly ignores -n */
12952 flag_off = ~flag_off;
12954 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12960 p = strchr(name, '=');
12964 vp = *findvar(hashvar(name), name);
12966 vp->flags = ((vp->flags | flag) & flag_off);
12970 setvar(name, p, (flag & flag_off));
12971 } while ((name = *++aptr) != NULL);
12976 /* No arguments. Show the list of exported or readonly vars.
12979 showvars(argv[0], flag, 0);
12984 * Delete a function if it exists.
12987 unsetfunc(const char *name)
12989 struct tblentry *cmdp;
12991 cmdp = cmdlookup(name, 0);
12992 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12993 delete_cmd_entry();
12997 * The unset builtin command. We unset the function before we unset the
12998 * variable to allow a function to be unset when there is a readonly variable
12999 * with the same name.
13001 static int FAST_FUNC
13002 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13009 while ((i = nextopt("vf")) != 0) {
13013 for (ap = argptr; *ap; ap++) {
13026 static const unsigned char timescmd_str[] ALIGN1 = {
13027 ' ', offsetof(struct tms, tms_utime),
13028 '\n', offsetof(struct tms, tms_stime),
13029 ' ', offsetof(struct tms, tms_cutime),
13030 '\n', offsetof(struct tms, tms_cstime),
13033 static int FAST_FUNC
13034 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13036 unsigned long clk_tck, s, t;
13037 const unsigned char *p;
13040 clk_tck = bb_clk_tck();
13045 t = *(clock_t *)(((char *) &buf) + p[1]);
13048 out1fmt("%lum%lu.%03lus%c",
13050 (t * 1000) / clk_tck,
13058 #if ENABLE_FEATURE_SH_MATH
13060 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13061 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13063 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13065 static int FAST_FUNC
13066 letcmd(int argc UNUSED_PARAM, char **argv)
13072 ash_msg_and_raise_error("expression expected");
13074 i = ash_arith(*argv);
13082 * The read builtin. Options:
13083 * -r Do not interpret '\' specially
13084 * -s Turn off echo (tty only)
13085 * -n NCHARS Read NCHARS max
13086 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13087 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13088 * -u FD Read from given FD instead of fd 0
13089 * This uses unbuffered input, which may be avoidable in some cases.
13090 * TODO: bash also has:
13091 * -a ARRAY Read into array[0],[1],etc
13092 * -d DELIM End on DELIM char, not newline
13093 * -e Use line editing (tty only)
13095 static int FAST_FUNC
13096 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13098 char *opt_n = NULL;
13099 char *opt_p = NULL;
13100 char *opt_t = NULL;
13101 char *opt_u = NULL;
13102 int read_flags = 0;
13106 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13115 read_flags |= BUILTIN_READ_SILENT;
13121 read_flags |= BUILTIN_READ_RAW;
13131 /* "read -s" needs to save/restore termios, can't allow ^C
13132 * to jump out of it.
13135 r = shell_builtin_read(setvar0,
13137 bltinlookup("IFS"), /* can be NULL */
13146 if ((uintptr_t)r > 1)
13147 ash_msg_and_raise_error(r);
13149 return (uintptr_t)r;
13152 static int FAST_FUNC
13153 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13155 static const char permuser[3] ALIGN1 = "ogu";
13158 int symbolic_mode = 0;
13160 while (nextopt("S") != '\0') {
13169 if (*argptr == NULL) {
13170 if (symbolic_mode) {
13171 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13178 *p++ = permuser[i];
13180 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13181 if (!(mask & 0400)) *p++ = 'r';
13182 if (!(mask & 0200)) *p++ = 'w';
13183 if (!(mask & 0100)) *p++ = 'x';
13191 out1fmt("%04o\n", mask);
13194 char *modestr = *argptr;
13195 /* numeric umasks are taken as-is */
13196 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13197 if (!isdigit(modestr[0]))
13199 mask = bb_parse_mode(modestr, mask);
13200 if ((unsigned)mask > 0777) {
13201 ash_msg_and_raise_error("illegal mode: %s", modestr);
13203 if (!isdigit(modestr[0]))
13210 static int FAST_FUNC
13211 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13213 return shell_builtin_ulimit(argv);
13216 /* ============ main() and helpers */
13219 * Called to exit the shell.
13228 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13229 save_history(line_input_state);
13231 status = exitstatus;
13232 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13233 if (setjmp(loc.loc)) {
13234 if (exception_type == EXEXIT)
13235 status = exitstatus;
13238 exception_handler = &loc;
13244 /*free(p); - we'll exit soon */
13247 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13248 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13251 flush_stdout_stderr();
13259 /* we will never free this */
13260 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13262 sigmode[SIGCHLD - 1] = S_DFL;
13263 setsignal(SIGCHLD);
13265 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13266 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13268 signal(SIGHUP, SIG_DFL);
13273 struct stat st1, st2;
13276 for (envp = environ; envp && *envp; envp++) {
13277 p = endofname(*envp);
13278 if (p != *envp && *p == '=') {
13279 setvareq(*envp, VEXPORT|VTEXTFIXED);
13283 setvareq((char*)defoptindvar, VTEXTFIXED);
13285 setvar0("PPID", utoa(getppid()));
13286 #if ENABLE_ASH_BASH_COMPAT
13287 p = lookupvar("SHLVL");
13288 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13289 if (!lookupvar("HOSTNAME")) {
13290 struct utsname uts;
13292 setvar0("HOSTNAME", uts.nodename);
13295 p = lookupvar("PWD");
13297 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13298 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13308 //usage:#define ash_trivial_usage
13309 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13310 //usage:#define ash_full_usage "\n\n"
13311 //usage: "Unix shell interpreter"
13314 * Process the shell command line arguments.
13317 procargs(char **argv)
13320 const char *xminusc;
13325 /* if (xargv[0]) - mmm, this is always true! */
13327 for (i = 0; i < NOPTS; i++)
13330 if (options(/*cmdline:*/ 1)) {
13331 /* it already printed err message */
13332 raise_exception(EXERROR);
13336 if (*xargv == NULL) {
13338 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13341 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13345 for (i = 0; i < NOPTS; i++)
13346 if (optlist[i] == 2)
13351 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13356 } else if (!sflag) {
13357 setinputfile(*xargv, 0);
13360 commandname = arg0;
13363 shellparam.p = xargv;
13364 #if ENABLE_ASH_GETOPTS
13365 shellparam.optind = 1;
13366 shellparam.optoff = -1;
13368 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13370 shellparam.nparam++;
13377 * Read /etc/profile, ~/.profile, $ENV.
13380 read_profile(const char *name)
13382 name = expandstr(name);
13383 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13390 * This routine is called when an error or an interrupt occurs in an
13391 * interactive shell and control is returned to the main command loop.
13392 * (In dash, this function is auto-generated by build machinery).
13401 /* from expand.c: */
13404 /* from input.c: */
13405 g_parsefile->left_in_buffer = 0;
13406 g_parsefile->left_in_line = 0; /* clear input buffer */
13409 /* from redir.c: */
13411 popredir(/*drop:*/ 0, /*restore:*/ 0);
13415 static short profile_buf[16384];
13416 extern int etext();
13420 * Main routine. We initialize things, parse the arguments, execute
13421 * profiles if we're a login shell, and then call cmdloop to execute
13422 * commands. The setjmp call sets up the location to jump to when an
13423 * exception occurs. When an exception occurs the variable "state"
13424 * is used to figure out how far we had gotten.
13426 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13427 int ash_main(int argc UNUSED_PARAM, char **argv)
13429 volatile smallint state;
13430 struct jmploc jmploc;
13431 struct stackmark smark;
13433 /* Initialize global data */
13437 #if ENABLE_ASH_ALIAS
13443 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13446 #if ENABLE_FEATURE_EDITING
13447 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13450 if (setjmp(jmploc.loc)) {
13456 e = exception_type;
13458 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13462 newline_and_flush(stderr);
13465 popstackmark(&smark);
13466 FORCE_INT_ON; /* enable interrupts */
13475 exception_handler = &jmploc;
13476 rootpid = getpid();
13479 setstackmark(&smark);
13482 TRACE(("Shell args: "));
13483 trace_puts_args(argv);
13486 if (argv[0] && argv[0][0] == '-')
13492 read_profile("/etc/profile");
13495 hp = lookupvar("HOME");
13497 read_profile("$HOME/.profile");
13503 getuid() == geteuid() && getgid() == getegid() &&
13507 const char *shinit = lookupvar("ENV");
13508 if (shinit != NULL && *shinit != '\0')
13509 read_profile(shinit);
13511 popstackmark(&smark);
13515 /* evalstring pushes parsefile stack.
13516 * Ensure we don't falsely claim that 0 (stdin)
13517 * is one of stacked source fds.
13518 * Testcase: ash -c 'exec 1>&0' must not complain. */
13519 // if (!sflag) g_parsefile->pf_fd = -1;
13520 // ^^ not necessary since now we special-case fd 0
13521 // in is_hidden_fd() to not be considered "hidden fd"
13522 evalstring(minusc, 0);
13525 if (sflag || minusc == NULL) {
13526 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13528 const char *hp = lookupvar("HISTFILE");
13530 hp = lookupvar("HOME");
13532 hp = concat_path_file(hp, ".ash_history");
13533 setvar0("HISTFILE", hp);
13535 hp = lookupvar("HISTFILE");
13539 line_input_state->hist_file = hp;
13540 # if ENABLE_FEATURE_SH_HISTFILESIZE
13541 hp = lookupvar("HISTFILESIZE");
13542 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13546 state4: /* XXX ??? - why isn't this before the "if" statement */
13554 extern void _mcleanup(void);
13558 TRACE(("End of main reached\n"));
13565 * Copyright (c) 1989, 1991, 1993, 1994
13566 * The Regents of the University of California. All rights reserved.
13568 * This code is derived from software contributed to Berkeley by
13569 * Kenneth Almquist.
13571 * Redistribution and use in source and binary forms, with or without
13572 * modification, are permitted provided that the following conditions
13574 * 1. Redistributions of source code must retain the above copyright
13575 * notice, this list of conditions and the following disclaimer.
13576 * 2. Redistributions in binary form must reproduce the above copyright
13577 * notice, this list of conditions and the following disclaimer in the
13578 * documentation and/or other materials provided with the distribution.
13579 * 3. Neither the name of the University nor the names of its contributors
13580 * may be used to endorse or promote products derived from this software
13581 * without specific prior written permission.
13583 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13584 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13585 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13586 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13587 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13588 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13589 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13590 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13591 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13592 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF