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:config ASH_OPTIMIZE_FOR_SIZE
30 //config: bool "Optimize for size instead of speed"
32 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
34 //config: Compile ash for reduced size at the price of speed.
36 //config:config ASH_INTERNAL_GLOB
37 //config: bool "Use internal glob() implementation"
38 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
39 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
41 //config: Do not use glob() function from libc, use internal implementation.
42 //config: Use this if you are getting "glob.h: No such file or directory"
43 //config: or similar build errors.
45 //config:config ASH_RANDOM_SUPPORT
46 //config: bool "Pseudorandom generator and $RANDOM variable"
48 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
50 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
51 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
52 //config: You can reset the generator by using a specified start value.
53 //config: After "unset RANDOM" the generator will switch off and this
54 //config: variable will no longer have special treatment.
56 //config:config ASH_EXPAND_PRMT
57 //config: bool "Expand prompt string"
59 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
61 //config: "PS#" may contain volatile content, such as backquote commands.
62 //config: This option recreates the prompt string from the environment
63 //config: variable each time it is displayed.
65 //config:config ASH_BASH_COMPAT
66 //config: bool "bash-compatible extensions"
68 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
70 //config: Enable bash-compatible extensions.
72 //config:config ASH_IDLE_TIMEOUT
73 //config: bool "Idle timeout variable"
75 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
77 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
79 //config:config ASH_JOB_CONTROL
80 //config: bool "Job control"
82 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
84 //config: Enable job control in the ash shell.
86 //config:config ASH_ALIAS
87 //config: bool "Alias support"
89 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
91 //config: Enable alias support in the ash shell.
93 //config:config ASH_GETOPTS
94 //config: bool "Builtin getopt to parse positional parameters"
96 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
98 //config: Enable support for getopts builtin in ash.
100 //config:config ASH_BUILTIN_ECHO
101 //config: bool "Builtin version of 'echo'"
103 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config: Enable support for echo builtin in ash.
107 //config:config ASH_BUILTIN_PRINTF
108 //config: bool "Builtin version of 'printf'"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config: Enable support for printf builtin in ash.
114 //config:config ASH_BUILTIN_TEST
115 //config: bool "Builtin version of 'test'"
117 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
119 //config: Enable support for test builtin in ash.
121 //config:config ASH_HELP
122 //config: bool "help builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config: Enable help builtin in ash.
128 //config:config ASH_CMDCMD
129 //config: bool "'command' command to override shell builtins"
131 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
133 //config: Enable support for the ash 'command' builtin, which allows
134 //config: you to run the specified command with the specified arguments,
135 //config: even when there is an ash builtin command with the same name.
137 //config:config ASH_MAIL
138 //config: bool "Check for new mail on interactive shells"
140 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
142 //config: Enable "check for new mail" function in the ash shell.
144 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
145 //applet:IF_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
146 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
148 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
149 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
150 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
151 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
154 * The following should be set to reflect the type of system you have:
155 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
156 * define SYSV if you are running under System V.
157 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
158 * define DEBUG=2 to compile in and turn on debugging.
160 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
161 * debugging info will be written to ./trace and a quit signal
162 * will generate a core dump.
165 /* Tweak debug output verbosity here */
169 #define DEBUG_INTONOFF 0
173 #define JOBS ENABLE_ASH_JOB_CONTROL
177 #include <sys/times.h>
178 #include <sys/utsname.h> /* for setting $HOSTNAME */
180 #include "busybox.h" /* for applet_names */
182 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
183 /* Bionic at least up to version 24 has no glob() */
184 # undef ENABLE_ASH_INTERNAL_GLOB
185 # define ENABLE_ASH_INTERNAL_GLOB 1
188 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
189 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
190 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
191 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
192 # error glob() should unbackslash them and match. uClibc does not unbackslash,
193 # error fails to match dirname, subsequently not expanding <pattern> in it.
195 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
196 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
199 #if !ENABLE_ASH_INTERNAL_GLOB
204 #include "shell_common.h"
205 #if ENABLE_FEATURE_SH_MATH
208 #if ENABLE_ASH_RANDOM_SUPPORT
211 # define CLEAR_RANDOM_T(rnd) ((void)0)
214 #include "NUM_APPLETS.h"
216 /* STANDALONE does not make sense, and won't compile */
217 # undef CONFIG_FEATURE_SH_STANDALONE
218 # undef ENABLE_FEATURE_SH_STANDALONE
219 # undef IF_FEATURE_SH_STANDALONE
220 # undef IF_NOT_FEATURE_SH_STANDALONE
221 # define ENABLE_FEATURE_SH_STANDALONE 0
222 # define IF_FEATURE_SH_STANDALONE(...)
223 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
227 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
231 # error "Do not even bother, ash will not run on NOMMU machine"
235 /* ============ Hash table sizes. Configurable. */
239 #define CMDTABLESIZE 31 /* should be prime */
242 /* ============ Shell options */
244 static const char *const optletters_optnames[] = {
259 #if ENABLE_ASH_BASH_COMPAT
268 #define optletters(n) optletters_optnames[n][0]
269 #define optnames(n) (optletters_optnames[n] + 1)
271 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
274 /* ============ Misc data */
276 #define msg_illnum "Illegal number: %s"
279 * We enclose jmp_buf in a structure so that we can declare pointers to
280 * jump locations. The global variable handler contains the location to
281 * jump to when an exception occurs, and the global variable exception_type
282 * contains a code identifying the exception. To implement nested
283 * exception handlers, the user should save the value of handler on entry
284 * to an inner scope, set handler to point to a jmploc structure for the
285 * inner scope, and restore handler on exit from the scope.
291 struct globals_misc {
292 uint8_t exitstatus; /* exit status of last command */
293 uint8_t back_exitstatus;/* exit status of backquoted command */
294 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
295 int rootpid; /* pid of main shell */
296 /* shell level: 0 for the main shell, 1 for its children, and so on */
298 #define rootshell (!shlvl)
299 char *minusc; /* argument to -c option */
301 char *curdir; // = nullstr; /* current working directory */
302 char *physdir; // = nullstr; /* physical working directory */
304 char *arg0; /* value of $0 */
306 struct jmploc *exception_handler;
308 volatile int suppress_int; /* counter */
309 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
310 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
311 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
312 smallint exception_type; /* kind of exception (0..5) */
314 #define EXINT 0 /* SIGINT received */
315 #define EXERROR 1 /* a generic error */
316 #define EXEXIT 4 /* exit the shell */
319 char nullstr[1]; /* zero length string */
322 #define eflag optlist[0]
323 #define fflag optlist[1]
324 #define Iflag optlist[2]
325 #define iflag optlist[3]
326 #define mflag optlist[4]
327 #define nflag optlist[5]
328 #define sflag optlist[6]
329 #define xflag optlist[7]
330 #define vflag optlist[8]
331 #define Cflag optlist[9]
332 #define aflag optlist[10]
333 #define bflag optlist[11]
334 #define uflag optlist[12]
335 #define viflag optlist[13]
336 #if ENABLE_ASH_BASH_COMPAT
337 # define pipefail optlist[14]
342 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
343 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
346 /* trap handler commands */
348 * Sigmode records the current value of the signal handlers for the various
349 * modes. A value of zero means that the current handler is not known.
350 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
352 char sigmode[NSIG - 1];
353 #define S_DFL 1 /* default signal handling (SIG_DFL) */
354 #define S_CATCH 2 /* signal is caught */
355 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
356 #define S_HARD_IGN 4 /* signal is ignored permanently */
358 /* indicates specified signal received */
359 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
360 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
362 char **trap_ptr; /* used only by "trap hack" */
364 /* Rarely referenced stuff */
365 #if ENABLE_ASH_RANDOM_SUPPORT
368 pid_t backgndpid; /* pid of last background process */
370 extern struct globals_misc *const ash_ptr_to_globals_misc;
371 #define G_misc (*ash_ptr_to_globals_misc)
372 #define exitstatus (G_misc.exitstatus )
373 #define back_exitstatus (G_misc.back_exitstatus )
374 #define job_warning (G_misc.job_warning)
375 #define rootpid (G_misc.rootpid )
376 #define shlvl (G_misc.shlvl )
377 #define minusc (G_misc.minusc )
378 #define curdir (G_misc.curdir )
379 #define physdir (G_misc.physdir )
380 #define arg0 (G_misc.arg0 )
381 #define exception_handler (G_misc.exception_handler)
382 #define exception_type (G_misc.exception_type )
383 #define suppress_int (G_misc.suppress_int )
384 #define pending_int (G_misc.pending_int )
385 #define got_sigchld (G_misc.got_sigchld )
386 #define pending_sig (G_misc.pending_sig )
387 #define isloginsh (G_misc.isloginsh )
388 #define nullstr (G_misc.nullstr )
389 #define optlist (G_misc.optlist )
390 #define sigmode (G_misc.sigmode )
391 #define gotsig (G_misc.gotsig )
392 #define may_have_traps (G_misc.may_have_traps )
393 #define trap (G_misc.trap )
394 #define trap_ptr (G_misc.trap_ptr )
395 #define random_gen (G_misc.random_gen )
396 #define backgndpid (G_misc.backgndpid )
397 #define INIT_G_misc() do { \
398 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
406 /* ============ DEBUG */
408 static void trace_printf(const char *fmt, ...);
409 static void trace_vprintf(const char *fmt, va_list va);
410 # define TRACE(param) trace_printf param
411 # define TRACEV(param) trace_vprintf param
412 # define close(fd) do { \
414 if (close(dfd) < 0) \
415 bb_error_msg("bug on %d: closing %d(0x%x)", \
416 __LINE__, dfd, dfd); \
419 # define TRACE(param)
420 # define TRACEV(param)
424 /* ============ Utility functions */
425 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
426 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
429 isdigit_str9(const char *str)
431 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
432 while (--maxlen && isdigit(*str))
434 return (*str == '\0');
438 var_end(const char *var)
447 /* ============ Interrupts / exceptions */
449 static void exitshell(void) NORETURN;
452 * These macros allow the user to suspend the handling of interrupt signals
453 * over a period of time. This is similar to SIGHOLD or to sigblock, but
454 * much more efficient and portable. (But hacking the kernel is so much
455 * more fun than worrying about efficiency and portability. :-))
458 # define INT_OFF do { \
459 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
464 # define INT_OFF do { \
471 * Called to raise an exception. Since C doesn't include exceptions, we
472 * just do a longjmp to the exception handler. The type of exception is
473 * stored in the global variable "exception_type".
475 static void raise_exception(int) NORETURN;
477 raise_exception(int e)
480 if (exception_handler == NULL)
485 longjmp(exception_handler->loc, 1);
488 #define raise_exception(e) do { \
489 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
490 raise_exception(e); \
495 * Called when a SIGINT is received. (If the user specifies
496 * that SIGINT is to be trapped or ignored using the trap builtin, then
497 * this routine is not called.) Suppressint is nonzero when interrupts
498 * are held using the INT_OFF macro. (The test for iflag is just
499 * defensive programming.)
501 static void raise_interrupt(void) NORETURN;
503 raise_interrupt(void)
506 /* Signal is not automatically unmasked after it is raised,
507 * do it ourself - unmask all signals */
508 sigprocmask_allsigs(SIG_UNBLOCK);
509 /* pending_sig = 0; - now done in signal_handler() */
511 if (!(rootshell && iflag)) {
512 /* Kill ourself with SIGINT */
513 signal(SIGINT, SIG_DFL);
516 /* bash: ^C even on empty command line sets $? */
517 exitstatus = SIGINT + 128;
518 raise_exception(EXINT);
522 #define raise_interrupt() do { \
523 TRACE(("raising interrupt on line %d\n", __LINE__)); \
528 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
532 if (--suppress_int == 0 && pending_int) {
537 # define INT_ON do { \
538 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
542 # define INT_ON int_on()
544 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
552 #define FORCE_INT_ON force_int_on()
554 #define SAVE_INT(v) ((v) = suppress_int)
556 #define RESTORE_INT(v) do { \
558 suppress_int = (v); \
559 if (suppress_int == 0 && pending_int) \
564 /* ============ Stdout/stderr output */
567 outstr(const char *p, FILE *file)
575 flush_stdout_stderr(void)
582 /* Was called outcslow(c,FILE*), but c was always '\n' */
584 newline_and_flush(FILE *dest)
592 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
594 out1fmt(const char *fmt, ...)
601 r = vprintf(fmt, ap);
607 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
609 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
616 ret = vsnprintf(outbuf, length, fmt, ap);
623 out1str(const char *p)
629 out2str(const char *p)
632 flush_stdout_stderr();
636 /* ============ Parser structures */
638 /* control characters in argument strings */
639 #define CTL_FIRST CTLESC
640 #define CTLESC ((unsigned char)'\201') /* escape next character */
641 #define CTLVAR ((unsigned char)'\202') /* variable defn */
642 #define CTLENDVAR ((unsigned char)'\203')
643 #define CTLBACKQ ((unsigned char)'\204')
644 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
645 #define CTLENDARI ((unsigned char)'\207')
646 #define CTLQUOTEMARK ((unsigned char)'\210')
647 #define CTL_LAST CTLQUOTEMARK
649 /* variable substitution byte (follows CTLVAR) */
650 #define VSTYPE 0x0f /* type of variable substitution */
651 #define VSNUL 0x10 /* colon--treat the empty string as unset */
653 /* values of VSTYPE field */
654 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
655 #define VSMINUS 0x2 /* ${var-text} */
656 #define VSPLUS 0x3 /* ${var+text} */
657 #define VSQUESTION 0x4 /* ${var?message} */
658 #define VSASSIGN 0x5 /* ${var=text} */
659 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
660 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
661 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
662 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
663 #define VSLENGTH 0xa /* ${#var} */
664 #if ENABLE_ASH_BASH_COMPAT
665 #define VSSUBSTR 0xc /* ${var:position:length} */
666 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
667 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
670 static const char dolatstr[] ALIGN1 = {
671 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
673 #define DOLATSTRLEN 6
692 #if ENABLE_ASH_BASH_COMPAT
709 smallint type; /* Nxxxx */
712 union node *redirect;
717 smallint pipe_backgnd;
718 struct nodelist *cmdlist;
724 union node *redirect;
737 union node *elsepart;
764 struct nodelist *backquote;
767 /* nfile and ndup layout must match!
768 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
769 * that it is actually NTO2 (>&file), and change its type.
786 char *_unused_expfname;
805 struct nredir nredir;
806 struct nbinary nbinary;
810 struct nclist nclist;
819 * NODE_EOF is returned by parsecmd when it encounters an end of file.
820 * It must be distinct from NULL.
822 #define NODE_EOF ((union node *) -1L)
825 struct nodelist *next;
838 freefunc(struct funcnode *f)
840 if (f && --f->count < 0)
845 /* ============ Debugging output */
849 static FILE *tracefile;
852 trace_printf(const char *fmt, ...)
859 fprintf(tracefile, "%u ", (int) time(NULL));
861 fprintf(tracefile, "[%u] ", (int) getpid());
863 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
865 vfprintf(tracefile, fmt, va);
870 trace_vprintf(const char *fmt, va_list va)
874 vfprintf(tracefile, fmt, va);
875 fprintf(tracefile, "\n");
879 trace_puts(const char *s)
887 trace_puts_quoted(char *s)
894 putc('"', tracefile);
895 for (p = s; *p; p++) {
896 switch ((unsigned char)*p) {
897 case '\n': c = 'n'; goto backslash;
898 case '\t': c = 't'; goto backslash;
899 case '\r': c = 'r'; goto backslash;
900 case '\"': c = '\"'; goto backslash;
901 case '\\': c = '\\'; goto backslash;
902 case CTLESC: c = 'e'; goto backslash;
903 case CTLVAR: c = 'v'; goto backslash;
904 case CTLBACKQ: c = 'q'; goto backslash;
906 putc('\\', tracefile);
910 if (*p >= ' ' && *p <= '~')
913 putc('\\', tracefile);
914 putc((*p >> 6) & 03, tracefile);
915 putc((*p >> 3) & 07, tracefile);
916 putc(*p & 07, tracefile);
921 putc('"', tracefile);
925 trace_puts_args(char **ap)
932 trace_puts_quoted(*ap);
934 putc('\n', tracefile);
937 putc(' ', tracefile);
952 /* leave open because libedit might be using it */
955 strcpy(s, "./trace");
957 if (!freopen(s, "a", tracefile)) {
958 fprintf(stderr, "Can't re-open %s\n", s);
963 tracefile = fopen(s, "a");
964 if (tracefile == NULL) {
965 fprintf(stderr, "Can't open %s\n", s);
971 flags = fcntl(fileno(tracefile), F_GETFL);
973 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
975 setlinebuf(tracefile);
976 fputs("\nTracing started.\n", tracefile);
980 indent(int amount, char *pfx, FILE *fp)
984 for (i = 0; i < amount; i++) {
985 if (pfx && i == amount - 1)
991 /* little circular references here... */
992 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
995 sharg(union node *arg, FILE *fp)
998 struct nodelist *bqlist;
999 unsigned char subtype;
1001 if (arg->type != NARG) {
1002 out1fmt("<node type %d>\n", arg->type);
1005 bqlist = arg->narg.backquote;
1006 for (p = arg->narg.text; *p; p++) {
1007 switch ((unsigned char)*p) {
1016 if (subtype == VSLENGTH)
1024 if (subtype & VSNUL)
1027 switch (subtype & VSTYPE) {
1053 case VSTRIMRIGHTMAX:
1060 out1fmt("<subtype %d>", subtype);
1069 shtree(bqlist->n, -1, NULL, fp);
1080 shcmd(union node *cmd, FILE *fp)
1088 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1094 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1098 switch (np->nfile.type) {
1099 case NTO: s = ">>"+1; dftfd = 1; break;
1100 case NCLOBBER: s = ">|"; dftfd = 1; break;
1101 case NAPPEND: s = ">>"; dftfd = 1; break;
1102 #if ENABLE_ASH_BASH_COMPAT
1105 case NTOFD: s = ">&"; dftfd = 1; break;
1106 case NFROM: s = "<"; break;
1107 case NFROMFD: s = "<&"; break;
1108 case NFROMTO: s = "<>"; break;
1109 default: s = "*error*"; break;
1111 if (np->nfile.fd != dftfd)
1112 fprintf(fp, "%d", np->nfile.fd);
1114 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1115 fprintf(fp, "%d", np->ndup.dupfd);
1117 sharg(np->nfile.fname, fp);
1124 shtree(union node *n, int ind, char *pfx, FILE *fp)
1126 struct nodelist *lp;
1132 indent(ind, pfx, fp);
1134 if (n == NODE_EOF) {
1149 shtree(n->nbinary.ch1, ind, NULL, fp);
1152 shtree(n->nbinary.ch2, ind, NULL, fp);
1160 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1161 shtree(lp->n, 0, NULL, fp);
1165 if (n->npipe.pipe_backgnd)
1171 fprintf(fp, "<node type %d>", n->type);
1179 showtree(union node *n)
1181 trace_puts("showtree called\n");
1182 shtree(n, 1, NULL, stderr);
1188 /* ============ Parser data */
1191 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1194 struct strlist *next;
1201 struct strpush *prev; /* preceding string on stack */
1203 int prev_left_in_line;
1204 #if ENABLE_ASH_ALIAS
1205 struct alias *ap; /* if push was associated with an alias */
1207 char *string; /* remember the string since it may change */
1209 /* Remember last two characters for pungetc. */
1212 /* Number of outstanding calls to pungetc. */
1217 struct parsefile *prev; /* preceding file on stack */
1218 int linno; /* current line */
1219 int pf_fd; /* file descriptor (or -1 if string) */
1220 int left_in_line; /* number of chars left in this line */
1221 int left_in_buffer; /* number of chars left in this buffer past the line */
1222 char *next_to_pgetc; /* next char in buffer */
1223 char *buf; /* input buffer */
1224 struct strpush *strpush; /* for pushing strings at this level */
1225 struct strpush basestrpush; /* so pushing one is fast */
1227 /* Remember last two characters for pungetc. */
1230 /* Number of outstanding calls to pungetc. */
1234 static struct parsefile basepf; /* top level input file */
1235 static struct parsefile *g_parsefile = &basepf; /* current input file */
1236 static int startlinno; /* line # where last token started */
1237 static char *commandname; /* currently executing command */
1238 static struct strlist *cmdenviron; /* environment for builtin command */
1241 /* ============ Message printing */
1244 ash_vmsg(const char *msg, va_list ap)
1246 fprintf(stderr, "%s: ", arg0);
1248 if (strcmp(arg0, commandname))
1249 fprintf(stderr, "%s: ", commandname);
1250 if (!iflag || g_parsefile->pf_fd > 0)
1251 fprintf(stderr, "line %d: ", startlinno);
1253 vfprintf(stderr, msg, ap);
1254 newline_and_flush(stderr);
1258 * Exverror is called to raise the error exception. If the second argument
1259 * is not NULL then error prints an error message using printf style
1260 * formatting. It then raises the error exception.
1262 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1264 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1268 TRACE(("ash_vmsg_and_raise(%d):", cond));
1271 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1276 flush_stdout_stderr();
1277 raise_exception(cond);
1281 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1283 ash_msg_and_raise_error(const char *msg, ...)
1288 ash_vmsg_and_raise(EXERROR, msg, ap);
1293 static void raise_error_syntax(const char *) NORETURN;
1295 raise_error_syntax(const char *msg)
1297 ash_msg_and_raise_error("syntax error: %s", msg);
1301 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1303 ash_msg_and_raise(int cond, const char *msg, ...)
1308 ash_vmsg_and_raise(cond, msg, ap);
1314 * error/warning routines for external builtins
1317 ash_msg(const char *fmt, ...)
1327 * Return a string describing an error. The returned string may be a
1328 * pointer to a static buffer that will be overwritten on the next call.
1329 * Action describes the operation that got the error.
1332 errmsg(int e, const char *em)
1334 if (e == ENOENT || e == ENOTDIR) {
1341 /* ============ Memory allocation */
1344 /* I consider these wrappers nearly useless:
1345 * ok, they return you to nearest exception handler, but
1346 * how much memory do you leak in the process, making
1347 * memory starvation worse?
1350 ckrealloc(void * p, size_t nbytes)
1352 p = realloc(p, nbytes);
1354 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1359 ckmalloc(size_t nbytes)
1361 return ckrealloc(NULL, nbytes);
1365 ckzalloc(size_t nbytes)
1367 return memset(ckmalloc(nbytes), 0, nbytes);
1371 ckstrdup(const char *s)
1373 char *p = strdup(s);
1375 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1379 /* Using bbox equivalents. They exit if out of memory */
1380 # define ckrealloc xrealloc
1381 # define ckmalloc xmalloc
1382 # define ckzalloc xzalloc
1383 # define ckstrdup xstrdup
1387 * It appears that grabstackstr() will barf with such alignments
1388 * because stalloc() will return a string allocated in a new stackblock.
1390 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1392 /* Most machines require the value returned from malloc to be aligned
1393 * in some way. The following macro will get this right
1394 * on many machines. */
1395 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1396 /* Minimum size of a block */
1397 MINSIZE = SHELL_ALIGN(504),
1400 struct stack_block {
1401 struct stack_block *prev;
1402 char space[MINSIZE];
1406 struct stack_block *stackp;
1412 struct globals_memstack {
1413 struct stack_block *g_stackp; // = &stackbase;
1414 char *g_stacknxt; // = stackbase.space;
1415 char *sstrend; // = stackbase.space + MINSIZE;
1416 size_t g_stacknleft; // = MINSIZE;
1417 struct stack_block stackbase;
1419 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1420 #define G_memstack (*ash_ptr_to_globals_memstack)
1421 #define g_stackp (G_memstack.g_stackp )
1422 #define g_stacknxt (G_memstack.g_stacknxt )
1423 #define sstrend (G_memstack.sstrend )
1424 #define g_stacknleft (G_memstack.g_stacknleft)
1425 #define stackbase (G_memstack.stackbase )
1426 #define INIT_G_memstack() do { \
1427 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1429 g_stackp = &stackbase; \
1430 g_stacknxt = stackbase.space; \
1431 g_stacknleft = MINSIZE; \
1432 sstrend = stackbase.space + MINSIZE; \
1436 #define stackblock() ((void *)g_stacknxt)
1437 #define stackblocksize() g_stacknleft
1440 * Parse trees for commands are allocated in lifo order, so we use a stack
1441 * to make this more efficient, and also to avoid all sorts of exception
1442 * handling code to handle interrupts in the middle of a parse.
1444 * The size 504 was chosen because the Ultrix malloc handles that size
1448 stalloc(size_t nbytes)
1453 aligned = SHELL_ALIGN(nbytes);
1454 if (aligned > g_stacknleft) {
1457 struct stack_block *sp;
1459 blocksize = aligned;
1460 if (blocksize < MINSIZE)
1461 blocksize = MINSIZE;
1462 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1463 if (len < blocksize)
1464 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1467 sp->prev = g_stackp;
1468 g_stacknxt = sp->space;
1469 g_stacknleft = blocksize;
1470 sstrend = g_stacknxt + blocksize;
1475 g_stacknxt += aligned;
1476 g_stacknleft -= aligned;
1481 stzalloc(size_t nbytes)
1483 return memset(stalloc(nbytes), 0, nbytes);
1490 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1491 write(STDERR_FILENO, "stunalloc\n", 10);
1495 g_stacknleft += g_stacknxt - (char *)p;
1500 * Like strdup but works with the ash stack.
1503 sstrdup(const char *p)
1505 size_t len = strlen(p) + 1;
1506 return memcpy(stalloc(len), p, len);
1510 grabstackblock(size_t len)
1516 pushstackmark(struct stackmark *mark, size_t len)
1518 mark->stackp = g_stackp;
1519 mark->stacknxt = g_stacknxt;
1520 mark->stacknleft = g_stacknleft;
1521 grabstackblock(len);
1525 setstackmark(struct stackmark *mark)
1527 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1531 popstackmark(struct stackmark *mark)
1533 struct stack_block *sp;
1539 while (g_stackp != mark->stackp) {
1541 g_stackp = sp->prev;
1544 g_stacknxt = mark->stacknxt;
1545 g_stacknleft = mark->stacknleft;
1546 sstrend = mark->stacknxt + mark->stacknleft;
1551 * When the parser reads in a string, it wants to stick the string on the
1552 * stack and only adjust the stack pointer when it knows how big the
1553 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1554 * of space on top of the stack and stackblocklen returns the length of
1555 * this block. Growstackblock will grow this space by at least one byte,
1556 * possibly moving it (like realloc). Grabstackblock actually allocates the
1557 * part of the block that has been used.
1560 growstackblock(void)
1564 newlen = g_stacknleft * 2;
1565 if (newlen < g_stacknleft)
1566 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1570 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1571 struct stack_block *sp;
1572 struct stack_block *prevstackp;
1577 prevstackp = sp->prev;
1578 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1579 sp = ckrealloc(sp, grosslen);
1580 sp->prev = prevstackp;
1582 g_stacknxt = sp->space;
1583 g_stacknleft = newlen;
1584 sstrend = sp->space + newlen;
1587 char *oldspace = g_stacknxt;
1588 size_t oldlen = g_stacknleft;
1589 char *p = stalloc(newlen);
1591 /* free the space we just allocated */
1592 g_stacknxt = memcpy(p, oldspace, oldlen);
1593 g_stacknleft += newlen;
1598 * The following routines are somewhat easier to use than the above.
1599 * The user declares a variable of type STACKSTR, which may be declared
1600 * to be a register. The macro STARTSTACKSTR initializes things. Then
1601 * the user uses the macro STPUTC to add characters to the string. In
1602 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1603 * grown as necessary. When the user is done, she can just leave the
1604 * string there and refer to it using stackblock(). Or she can allocate
1605 * the space for it using grabstackstr(). If it is necessary to allow
1606 * someone else to use the stack temporarily and then continue to grow
1607 * the string, the user should use grabstack to allocate the space, and
1608 * then call ungrabstr(p) to return to the previous mode of operation.
1610 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1611 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1612 * is space for at least one character.
1617 size_t len = stackblocksize();
1619 return (char *)stackblock() + len;
1623 * Called from CHECKSTRSPACE.
1626 makestrspace(size_t newlen, char *p)
1628 size_t len = p - g_stacknxt;
1634 size = stackblocksize();
1636 if (nleft >= newlen)
1640 return (char *)stackblock() + len;
1644 stack_nputstr(const char *s, size_t n, char *p)
1646 p = makestrspace(n, p);
1647 p = (char *)memcpy(p, s, n) + n;
1652 stack_putstr(const char *s, char *p)
1654 return stack_nputstr(s, strlen(s), p);
1658 _STPUTC(int c, char *p)
1666 #define STARTSTACKSTR(p) ((p) = stackblock())
1667 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1668 #define CHECKSTRSPACE(n, p) do { \
1671 size_t m = sstrend - q; \
1673 (p) = makestrspace(l, q); \
1675 #define USTPUTC(c, p) (*(p)++ = (c))
1676 #define STACKSTRNUL(p) do { \
1677 if ((p) == sstrend) \
1678 (p) = growstackstr(); \
1681 #define STUNPUTC(p) (--(p))
1682 #define STTOPC(p) ((p)[-1])
1683 #define STADJUST(amount, p) ((p) += (amount))
1685 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1686 #define ungrabstackstr(s, p) stunalloc(s)
1687 #define stackstrend() ((void *)sstrend)
1690 /* ============ String helpers */
1693 * prefix -- see if pfx is a prefix of string.
1696 prefix(const char *string, const char *pfx)
1699 if (*pfx++ != *string++)
1702 return (char *) string;
1706 * Check for a valid number. This should be elsewhere.
1709 is_number(const char *p)
1714 } while (*++p != '\0');
1719 * Convert a string of digits to an integer, printing an error message on
1723 number(const char *s)
1726 ash_msg_and_raise_error(msg_illnum, s);
1731 * Produce a possibly single quoted string suitable as input to the shell.
1732 * The return string is allocated on the stack.
1735 single_quote(const char *s)
1745 len = strchrnul(s, '\'') - s;
1747 q = p = makestrspace(len + 3, p);
1750 q = (char *)memcpy(q, s, len) + len;
1759 do len++; while (*++s == '\'');
1761 q = p = makestrspace(len + 3, p);
1764 q = (char *)memcpy(q, s - len, len) + len;
1772 return stackblock();
1776 /* ============ nextopt */
1778 static char **argptr; /* argument list for builtin commands */
1779 static char *optionarg; /* set by nextopt (like getopt) */
1780 static char *optptr; /* used by nextopt */
1783 * XXX - should get rid of. Have all builtins use getopt(3).
1784 * The library getopt must have the BSD extension static variable
1785 * "optreset", otherwise it can't be used within the shell safely.
1787 * Standard option processing (a la getopt) for builtin routines.
1788 * The only argument that is passed to nextopt is the option string;
1789 * the other arguments are unnecessary. It returns the character,
1790 * or '\0' on end of input.
1793 nextopt(const char *optstring)
1800 if (p == NULL || *p == '\0') {
1801 /* We ate entire "-param", take next one */
1807 if (*++p == '\0') /* just "-" ? */
1810 if (LONE_DASH(p)) /* "--" ? */
1812 /* p => next "-param" */
1814 /* p => some option char in the middle of a "-param" */
1816 for (q = optstring; *q != c;) {
1818 ash_msg_and_raise_error("illegal option -%c", c);
1826 ash_msg_and_raise_error("no arg for -%c option", c);
1836 /* ============ Shell variables */
1839 * The parsefile structure pointed to by the global variable parsefile
1840 * contains information about the current file being read.
1843 int nparam; /* # of positional parameters (without $0) */
1844 #if ENABLE_ASH_GETOPTS
1845 int optind; /* next parameter to be processed by getopts */
1846 int optoff; /* used by getopts */
1848 unsigned char malloced; /* if parameter list dynamically allocated */
1849 char **p; /* parameter list */
1853 * Free the list of positional parameters.
1856 freeparam(volatile struct shparam *param)
1858 if (param->malloced) {
1860 ap = ap1 = param->p;
1867 #if ENABLE_ASH_GETOPTS
1868 static void FAST_FUNC getoptsreset(const char *value);
1872 struct var *next; /* next entry in hash list */
1873 int flags; /* flags are defined above */
1874 const char *var_text; /* name=value */
1875 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1876 /* the variable gets set/unset */
1880 struct localvar *next; /* next local variable in list */
1881 struct var *vp; /* the variable that was made local */
1882 int flags; /* saved flags */
1883 const char *text; /* saved text */
1887 #define VEXPORT 0x01 /* variable is exported */
1888 #define VREADONLY 0x02 /* variable cannot be modified */
1889 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1890 #define VTEXTFIXED 0x08 /* text is statically allocated */
1891 #define VSTACK 0x10 /* text is allocated on the stack */
1892 #define VUNSET 0x20 /* the variable is not set */
1893 #define VNOFUNC 0x40 /* don't call the callback function */
1894 #define VNOSET 0x80 /* do not set variable - just readonly test */
1895 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1896 #if ENABLE_ASH_RANDOM_SUPPORT
1897 # define VDYNAMIC 0x200 /* dynamic variable */
1903 /* Need to be before varinit_data[] */
1904 #if ENABLE_LOCALE_SUPPORT
1905 static void FAST_FUNC
1906 change_lc_all(const char *value)
1908 if (value && *value != '\0')
1909 setlocale(LC_ALL, value);
1911 static void FAST_FUNC
1912 change_lc_ctype(const char *value)
1914 if (value && *value != '\0')
1915 setlocale(LC_CTYPE, value);
1919 static void chkmail(void);
1920 static void changemail(const char *var_value) FAST_FUNC;
1922 # define chkmail() ((void)0)
1924 static void changepath(const char *) FAST_FUNC;
1925 #if ENABLE_ASH_RANDOM_SUPPORT
1926 static void change_random(const char *) FAST_FUNC;
1929 static const struct {
1931 const char *var_text;
1932 void (*var_func)(const char *) FAST_FUNC;
1933 } varinit_data[] = {
1935 * Note: VEXPORT would not work correctly here for NOFORK applets:
1936 * some environment strings may be constant.
1938 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1940 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1941 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1943 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1944 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1945 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1946 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1947 #if ENABLE_ASH_GETOPTS
1948 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1950 #if ENABLE_ASH_RANDOM_SUPPORT
1951 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1953 #if ENABLE_LOCALE_SUPPORT
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1955 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1957 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1958 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1964 struct globals_var {
1965 struct shparam shellparam; /* $@ current positional parameters */
1966 struct redirtab *redirlist;
1967 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1968 struct var *vartab[VTABSIZE];
1969 struct var varinit[ARRAY_SIZE(varinit_data)];
1971 extern struct globals_var *const ash_ptr_to_globals_var;
1972 #define G_var (*ash_ptr_to_globals_var)
1973 #define shellparam (G_var.shellparam )
1974 //#define redirlist (G_var.redirlist )
1975 #define preverrout_fd (G_var.preverrout_fd)
1976 #define vartab (G_var.vartab )
1977 #define varinit (G_var.varinit )
1978 #define INIT_G_var() do { \
1980 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1982 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1983 varinit[i].flags = varinit_data[i].flags; \
1984 varinit[i].var_text = varinit_data[i].var_text; \
1985 varinit[i].var_func = varinit_data[i].var_func; \
1989 #define vifs varinit[0]
1991 # define vmail (&vifs)[1]
1992 # define vmpath (&vmail)[1]
1993 # define vpath (&vmpath)[1]
1995 # define vpath (&vifs)[1]
1997 #define vps1 (&vpath)[1]
1998 #define vps2 (&vps1)[1]
1999 #define vps4 (&vps2)[1]
2000 #if ENABLE_ASH_GETOPTS
2001 # define voptind (&vps4)[1]
2002 # if ENABLE_ASH_RANDOM_SUPPORT
2003 # define vrandom (&voptind)[1]
2006 # if ENABLE_ASH_RANDOM_SUPPORT
2007 # define vrandom (&vps4)[1]
2012 * The following macros access the values of the above variables.
2013 * They have to skip over the name. They return the null string
2014 * for unset variables.
2016 #define ifsval() (vifs.var_text + 4)
2017 #define ifsset() ((vifs.flags & VUNSET) == 0)
2019 # define mailval() (vmail.var_text + 5)
2020 # define mpathval() (vmpath.var_text + 9)
2021 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2023 #define pathval() (vpath.var_text + 5)
2024 #define ps1val() (vps1.var_text + 4)
2025 #define ps2val() (vps2.var_text + 4)
2026 #define ps4val() (vps4.var_text + 4)
2027 #if ENABLE_ASH_GETOPTS
2028 # define optindval() (voptind.var_text + 7)
2031 #if ENABLE_ASH_GETOPTS
2032 static void FAST_FUNC
2033 getoptsreset(const char *value)
2035 shellparam.optind = number(value) ?: 1;
2036 shellparam.optoff = -1;
2041 * Compares two strings up to the first = or '\0'. The first
2042 * string must be terminated by '='; the second may be terminated by
2043 * either '=' or '\0'.
2046 varcmp(const char *p, const char *q)
2050 while ((c = *p) == (d = *q)) {
2051 if (c == '\0' || c == '=')
2065 * Find the appropriate entry in the hash table from the name.
2067 static struct var **
2068 hashvar(const char *p)
2072 hashval = ((unsigned char) *p) << 4;
2073 while (*p && *p != '=')
2074 hashval += (unsigned char) *p++;
2075 return &vartab[hashval % VTABSIZE];
2079 vpcmp(const void *a, const void *b)
2081 return varcmp(*(const char **)a, *(const char **)b);
2085 * This routine initializes the builtin variables.
2095 * PS1 depends on uid
2097 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2098 vps1.var_text = "PS1=\\w \\$ ";
2101 vps1.var_text = "PS1=# ";
2104 end = vp + ARRAY_SIZE(varinit);
2106 vpp = hashvar(vp->var_text);
2109 } while (++vp < end);
2112 static struct var **
2113 findvar(struct var **vpp, const char *name)
2115 for (; *vpp; vpp = &(*vpp)->next) {
2116 if (varcmp((*vpp)->var_text, name) == 0) {
2124 * Find the value of a variable. Returns NULL if not set.
2126 static const char* FAST_FUNC
2127 lookupvar(const char *name)
2131 v = *findvar(hashvar(name), name);
2133 #if ENABLE_ASH_RANDOM_SUPPORT
2135 * Dynamic variables are implemented roughly the same way they are
2136 * in bash. Namely, they're "special" so long as they aren't unset.
2137 * As soon as they're unset, they're no longer dynamic, and dynamic
2138 * lookup will no longer happen at that point. -- PFM.
2140 if (v->flags & VDYNAMIC)
2143 if (!(v->flags & VUNSET))
2144 return var_end(v->var_text);
2149 #if ENABLE_UNICODE_SUPPORT
2151 reinit_unicode_for_ash(void)
2153 /* Unicode support should be activated even if LANG is set
2154 * _during_ shell execution, not only if it was set when
2155 * shell was started. Therefore, re-check LANG every time:
2157 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2158 || ENABLE_UNICODE_USING_LOCALE
2160 const char *s = lookupvar("LC_ALL");
2161 if (!s) s = lookupvar("LC_CTYPE");
2162 if (!s) s = lookupvar("LANG");
2167 # define reinit_unicode_for_ash() ((void)0)
2171 * Search the environment of a builtin command.
2174 bltinlookup(const char *name)
2178 for (sp = cmdenviron; sp; sp = sp->next) {
2179 if (varcmp(sp->text, name) == 0)
2180 return var_end(sp->text);
2182 return lookupvar(name);
2186 * Same as setvar except that the variable and value are passed in
2187 * the first argument as name=value. Since the first argument will
2188 * be actually stored in the table, it should not be a string that
2190 * Called with interrupts off.
2193 setvareq(char *s, int flags)
2195 struct var *vp, **vpp;
2198 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2199 vp = *findvar(vpp, s);
2201 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2204 if (flags & VNOSAVE)
2208 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2214 if (vp->var_func && !(flags & VNOFUNC))
2215 vp->var_func(var_end(s));
2217 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2218 free((char*)vp->var_text);
2220 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2222 /* variable s is not found */
2225 vp = ckzalloc(sizeof(*vp));
2227 /*vp->func = NULL; - ckzalloc did it */
2230 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2237 * Set the value of a variable. The flags argument is ored with the
2238 * flags of the variable. If val is NULL, the variable is unset.
2241 setvar(const char *name, const char *val, int flags)
2249 q = endofname(name);
2250 p = strchrnul(q, '=');
2252 if (!namelen || p != q)
2253 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2258 vallen = strlen(val);
2262 nameeq = ckmalloc(namelen + vallen + 2);
2263 p = memcpy(nameeq, name, namelen) + namelen;
2266 p = memcpy(p, val, vallen) + vallen;
2269 setvareq(nameeq, flags | VNOSAVE);
2273 static void FAST_FUNC
2274 setvar0(const char *name, const char *val)
2276 setvar(name, val, 0);
2280 * Unset the specified variable.
2283 unsetvar(const char *s)
2289 vpp = findvar(hashvar(s), s);
2293 int flags = vp->flags;
2296 if (flags & VREADONLY)
2298 #if ENABLE_ASH_RANDOM_SUPPORT
2299 vp->flags &= ~VDYNAMIC;
2303 if ((flags & VSTRFIXED) == 0) {
2305 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2306 free((char*)vp->var_text);
2312 vp->flags &= ~VEXPORT;
2322 * Process a linked list of variable assignments.
2325 listsetvar(struct strlist *list_set_var, int flags)
2327 struct strlist *lp = list_set_var;
2333 setvareq(lp->text, flags);
2340 * Generate a list of variables satisfying the given conditions.
2343 listvars(int on, int off, char ***end)
2354 for (vp = *vpp; vp; vp = vp->next) {
2355 if ((vp->flags & mask) == on) {
2356 if (ep == stackstrend())
2357 ep = growstackstr();
2358 *ep++ = (char*)vp->var_text;
2361 } while (++vpp < vartab + VTABSIZE);
2362 if (ep == stackstrend())
2363 ep = growstackstr();
2367 return grabstackstr(ep);
2371 /* ============ Path search helper
2373 * The variable path (passed by reference) should be set to the start
2374 * of the path before the first call; path_advance will update
2375 * this value as it proceeds. Successive calls to path_advance will return
2376 * the possible path expansions in sequence. If an option (indicated by
2377 * a percent sign) appears in the path entry then the global variable
2378 * pathopt will be set to point to it; otherwise pathopt will be set to
2381 static const char *pathopt; /* set by path_advance */
2384 path_advance(const char **path, const char *name)
2394 for (p = start; *p && *p != ':' && *p != '%'; p++)
2396 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2397 while (stackblocksize() < len)
2401 memcpy(q, start, p - start);
2409 while (*p && *p != ':')
2416 return stalloc(len);
2420 /* ============ Prompt */
2422 static smallint doprompt; /* if set, prompt the user */
2423 static smallint needprompt; /* true if interactive and at start of line */
2425 #if ENABLE_FEATURE_EDITING
2426 static line_input_t *line_input_state;
2427 static const char *cmdedit_prompt;
2429 putprompt(const char *s)
2431 if (ENABLE_ASH_EXPAND_PRMT) {
2432 free((char*)cmdedit_prompt);
2433 cmdedit_prompt = ckstrdup(s);
2440 putprompt(const char *s)
2446 #if ENABLE_ASH_EXPAND_PRMT
2447 /* expandstr() needs parsing machinery, so it is far away ahead... */
2448 static const char *expandstr(const char *ps);
2450 #define expandstr(s) s
2454 setprompt_if(smallint do_set, int whichprompt)
2457 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2464 switch (whichprompt) {
2474 #if ENABLE_ASH_EXPAND_PRMT
2475 pushstackmark(&smark, stackblocksize());
2477 putprompt(expandstr(prompt));
2478 #if ENABLE_ASH_EXPAND_PRMT
2479 popstackmark(&smark);
2484 /* ============ The cd and pwd commands */
2486 #define CD_PHYSICAL 1
2496 while ((i = nextopt("LP")) != '\0') {
2498 flags ^= CD_PHYSICAL;
2507 * Update curdir (the name of the current directory) in response to a
2511 updatepwd(const char *dir)
2518 cdcomppath = sstrdup(dir);
2521 if (curdir == nullstr)
2523 new = stack_putstr(curdir, new);
2525 new = makestrspace(strlen(dir) + 2, new);
2526 lim = (char *)stackblock() + 1;
2530 if (new > lim && *lim == '/')
2535 if (dir[1] == '/' && dir[2] != '/') {
2541 p = strtok(cdcomppath, "/");
2545 if (p[1] == '.' && p[2] == '\0') {
2557 new = stack_putstr(p, new);
2560 p = strtok(NULL, "/");
2565 return stackblock();
2569 * Find out what the current directory is. If we already know the current
2570 * directory, this routine returns immediately.
2575 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2576 return dir ? dir : nullstr;
2580 setpwd(const char *val, int setold)
2584 oldcur = dir = curdir;
2587 setvar("OLDPWD", oldcur, VEXPORT);
2590 if (physdir != nullstr) {
2591 if (physdir != oldcur)
2595 if (oldcur == val || !val) {
2601 dir = ckstrdup(val);
2602 if (oldcur != dir && oldcur != nullstr) {
2607 setvar("PWD", dir, VEXPORT);
2610 static void hashcd(void);
2613 * Actually do the chdir. We also call hashcd to let other routines
2614 * know that the current directory has changed.
2617 docd(const char *dest, int flags)
2619 const char *dir = NULL;
2622 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2625 if (!(flags & CD_PHYSICAL)) {
2626 dir = updatepwd(dest);
2640 static int FAST_FUNC
2641 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2653 dest = bltinlookup("HOME");
2654 else if (LONE_DASH(dest)) {
2655 dest = bltinlookup("OLDPWD");
2677 path = bltinlookup("CDPATH");
2680 p = path_advance(&path, dest);
2681 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2685 if (!docd(p, flags))
2696 ash_msg_and_raise_error("can't cd to %s", dest);
2699 if (flags & CD_PRINT)
2700 out1fmt("%s\n", curdir);
2704 static int FAST_FUNC
2705 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2708 const char *dir = curdir;
2712 if (physdir == nullstr)
2716 out1fmt("%s\n", dir);
2721 /* ============ ... */
2724 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2726 /* Syntax classes */
2727 #define CWORD 0 /* character is nothing special */
2728 #define CNL 1 /* newline character */
2729 #define CBACK 2 /* a backslash character */
2730 #define CSQUOTE 3 /* single quote */
2731 #define CDQUOTE 4 /* double quote */
2732 #define CENDQUOTE 5 /* a terminating quote */
2733 #define CBQUOTE 6 /* backwards single quote */
2734 #define CVAR 7 /* a dollar sign */
2735 #define CENDVAR 8 /* a '}' character */
2736 #define CLP 9 /* a left paren in arithmetic */
2737 #define CRP 10 /* a right paren in arithmetic */
2738 #define CENDFILE 11 /* end of file */
2739 #define CCTL 12 /* like CWORD, except it must be escaped */
2740 #define CSPCL 13 /* these terminate a word */
2741 #define CIGN 14 /* character should be ignored */
2744 #if ENABLE_ASH_ALIAS
2748 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2750 #if ENABLE_FEATURE_SH_MATH
2751 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2753 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2755 static const uint16_t S_I_T[] ALIGN2 = {
2756 #if ENABLE_ASH_ALIAS
2757 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2759 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2760 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2761 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2762 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2763 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2764 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2765 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2766 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2767 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2768 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2769 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2770 #if !USE_SIT_FUNCTION
2771 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2772 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2773 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2777 /* Constants below must match table above */
2779 #if ENABLE_ASH_ALIAS
2780 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2782 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2783 CNL_CNL_CNL_CNL , /* 2 */
2784 CWORD_CCTL_CCTL_CWORD , /* 3 */
2785 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2786 CVAR_CVAR_CWORD_CVAR , /* 5 */
2787 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2788 CSPCL_CWORD_CWORD_CLP , /* 7 */
2789 CSPCL_CWORD_CWORD_CRP , /* 8 */
2790 CBACK_CBACK_CCTL_CBACK , /* 9 */
2791 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2792 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2793 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2794 CWORD_CWORD_CWORD_CWORD , /* 13 */
2795 CCTL_CCTL_CCTL_CCTL , /* 14 */
2798 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2799 * caller must ensure proper cast on it if c is *char_ptr!
2801 /* Values for syntax param */
2802 #define BASESYNTAX 0 /* not in quotes */
2803 #define DQSYNTAX 1 /* in double quotes */
2804 #define SQSYNTAX 2 /* in single quotes */
2805 #define ARISYNTAX 3 /* in arithmetic */
2806 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2808 #if USE_SIT_FUNCTION
2811 SIT(int c, int syntax)
2813 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2814 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2816 * This causes '/' to be prepended with CTLESC in dquoted string,
2817 * making "./file"* treated incorrectly because we feed
2818 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2819 * The "homegrown" glob implementation is okay with that,
2820 * but glibc one isn't. With '/' always treated as CWORD,
2823 # if ENABLE_ASH_ALIAS
2824 static const uint8_t syntax_index_table[] ALIGN1 = {
2825 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2826 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2827 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2831 static const uint8_t syntax_index_table[] ALIGN1 = {
2832 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2833 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2834 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2843 # if ENABLE_ASH_ALIAS
2849 /* Cast is purely for paranoia here,
2850 * just in case someone passed signed char to us */
2851 if ((unsigned char)c >= CTL_FIRST
2852 && (unsigned char)c <= CTL_LAST
2856 s = strchrnul(spec_symbls, c);
2859 indx = syntax_index_table[s - spec_symbls];
2861 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2864 #else /* !USE_SIT_FUNCTION */
2866 static const uint8_t syntax_index_table[] ALIGN1 = {
2867 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2868 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2878 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2879 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2901 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2903 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2905 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2907 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2908 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2909 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2910 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2911 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2913 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2914 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2915 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2916 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2928 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2929 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2930 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2931 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2932 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2933 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2961 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2962 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2966 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2994 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2995 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2996 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2997 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2999 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3000 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3001 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3002 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3003 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3004 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3005 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3006 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3125 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3126 # if ENABLE_ASH_ALIAS
3127 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3132 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3133 #else /* debug version, caught one signed char bug */
3134 # define SIT(c, syntax) \
3136 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3137 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3138 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3139 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3140 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3144 #endif /* !USE_SIT_FUNCTION */
3147 /* ============ Alias handling */
3149 #if ENABLE_ASH_ALIAS
3151 #define ALIASINUSE 1
3162 static struct alias **atab; // [ATABSIZE];
3163 #define INIT_G_alias() do { \
3164 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3168 static struct alias **
3169 __lookupalias(const char *name)
3171 unsigned int hashval;
3178 ch = (unsigned char)*p;
3182 ch = (unsigned char)*++p;
3184 app = &atab[hashval % ATABSIZE];
3186 for (; *app; app = &(*app)->next) {
3187 if (strcmp(name, (*app)->name) == 0) {
3195 static struct alias *
3196 lookupalias(const char *name, int check)
3198 struct alias *ap = *__lookupalias(name);
3200 if (check && ap && (ap->flag & ALIASINUSE))
3205 static struct alias *
3206 freealias(struct alias *ap)
3210 if (ap->flag & ALIASINUSE) {
3211 ap->flag |= ALIASDEAD;
3223 setalias(const char *name, const char *val)
3225 struct alias *ap, **app;
3227 app = __lookupalias(name);
3231 if (!(ap->flag & ALIASINUSE)) {
3234 ap->val = ckstrdup(val);
3235 ap->flag &= ~ALIASDEAD;
3238 ap = ckzalloc(sizeof(struct alias));
3239 ap->name = ckstrdup(name);
3240 ap->val = ckstrdup(val);
3241 /*ap->flag = 0; - ckzalloc did it */
3242 /*ap->next = NULL;*/
3249 unalias(const char *name)
3253 app = __lookupalias(name);
3257 *app = freealias(*app);
3268 struct alias *ap, **app;
3272 for (i = 0; i < ATABSIZE; i++) {
3274 for (ap = *app; ap; ap = *app) {
3275 *app = freealias(*app);
3285 printalias(const struct alias *ap)
3287 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3291 * TODO - sort output
3293 static int FAST_FUNC
3294 aliascmd(int argc UNUSED_PARAM, char **argv)
3303 for (i = 0; i < ATABSIZE; i++) {
3304 for (ap = atab[i]; ap; ap = ap->next) {
3310 while ((n = *++argv) != NULL) {
3311 v = strchr(n+1, '=');
3312 if (v == NULL) { /* n+1: funny ksh stuff */
3313 ap = *__lookupalias(n);
3315 fprintf(stderr, "%s: %s not found\n", "alias", n);
3328 static int FAST_FUNC
3329 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3333 while ((i = nextopt("a")) != '\0') {
3339 for (i = 0; *argptr; argptr++) {
3340 if (unalias(*argptr)) {
3341 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3349 #endif /* ASH_ALIAS */
3352 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3355 #define FORK_NOJOB 2
3357 /* mode flags for showjob(s) */
3358 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3359 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3360 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3361 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3364 * A job structure contains information about a job. A job is either a
3365 * single process or a set of processes contained in a pipeline. In the
3366 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3370 pid_t ps_pid; /* process id */
3371 int ps_status; /* last process status from wait() */
3372 char *ps_cmd; /* text of command being run */
3376 struct procstat ps0; /* status of process */
3377 struct procstat *ps; /* status or processes when more than one */
3379 int stopstatus; /* status of a stopped job */
3382 nprocs: 16, /* number of processes */
3384 #define JOBRUNNING 0 /* at least one proc running */
3385 #define JOBSTOPPED 1 /* all procs are stopped */
3386 #define JOBDONE 2 /* all procs are completed */
3388 sigint: 1, /* job was killed by SIGINT */
3389 jobctl: 1, /* job running under job control */
3391 waited: 1, /* true if this entry has been waited for */
3392 used: 1, /* true if this entry is in used */
3393 changed: 1; /* true if status has changed */
3394 struct job *prev_job; /* previous job */
3397 static struct job *makejob(/*union node *,*/ int);
3398 static int forkshell(struct job *, union node *, int);
3399 static int waitforjob(struct job *);
3402 enum { doing_jobctl = 0 };
3403 #define setjobctl(on) do {} while (0)
3405 static smallint doing_jobctl; //references:8
3406 static void setjobctl(int);
3413 ignoresig(int signo)
3415 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3416 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3417 /* No, need to do it */
3418 signal(signo, SIG_IGN);
3420 sigmode[signo - 1] = S_HARD_IGN;
3424 * Only one usage site - in setsignal()
3427 signal_handler(int signo)
3429 if (signo == SIGCHLD) {
3435 gotsig[signo - 1] = 1;
3436 pending_sig = signo;
3438 if (signo == SIGINT && !trap[SIGINT]) {
3439 if (!suppress_int) {
3441 raise_interrupt(); /* does not return */
3448 * Set the signal handler for the specified signal. The routine figures
3449 * out what it should be set to.
3452 setsignal(int signo)
3455 char cur_act, new_act;
3456 struct sigaction act;
3460 if (t != NULL) { /* trap for this sig is set */
3462 if (t[0] == '\0') /* trap is "": ignore this sig */
3466 if (rootshell && new_act == S_DFL) {
3469 if (iflag || minusc || sflag == 0)
3478 * "In all cases, bash ignores SIGQUIT. Non-builtin
3479 * commands run by bash have signal handlers
3480 * set to the values inherited by the shell
3481 * from its parent". */
3497 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3498 //whereas we have to restore it to what shell got on entry
3499 //from the parent. See comment above
3501 if (signo == SIGCHLD)
3504 t = &sigmode[signo - 1];
3507 /* current setting is not yet known */
3508 if (sigaction(signo, NULL, &act)) {
3509 /* pretend it worked; maybe we should give a warning,
3510 * but other shells don't. We don't alter sigmode,
3511 * so we retry every time.
3512 * btw, in Linux it never fails. --vda */
3515 if (act.sa_handler == SIG_IGN) {
3516 cur_act = S_HARD_IGN;
3518 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3520 cur_act = S_IGN; /* don't hard ignore these */
3524 if (cur_act == S_HARD_IGN || cur_act == new_act)
3527 act.sa_handler = SIG_DFL;
3530 act.sa_handler = signal_handler;
3533 act.sa_handler = SIG_IGN;
3537 /* flags and mask matter only if !DFL and !IGN, but we do it
3538 * for all cases for more deterministic behavior:
3541 sigfillset(&act.sa_mask);
3543 sigaction_set(signo, &act);
3548 /* mode flags for set_curjob */
3549 #define CUR_DELETE 2
3550 #define CUR_RUNNING 1
3551 #define CUR_STOPPED 0
3554 /* pgrp of shell on invocation */
3555 static int initialpgrp; //references:2
3556 static int ttyfd = -1; //5
3559 static struct job *jobtab; //5
3561 static unsigned njobs; //4
3563 static struct job *curjob; //lots
3564 /* number of presumed living untracked jobs */
3565 static int jobless; //4
3568 set_curjob(struct job *jp, unsigned mode)
3571 struct job **jpp, **curp;
3573 /* first remove from list */
3574 jpp = curp = &curjob;
3579 jpp = &jp1->prev_job;
3581 *jpp = jp1->prev_job;
3583 /* Then re-insert in correct position */
3591 /* job being deleted */
3594 /* newly created job or backgrounded job,
3595 * put after all stopped jobs.
3600 if (!jp1 || jp1->state != JOBSTOPPED)
3603 jpp = &jp1->prev_job;
3609 /* newly stopped job - becomes curjob */
3610 jp->prev_job = *jpp;
3618 jobno(const struct job *jp)
3620 return jp - jobtab + 1;
3625 * Convert a job name to a job structure.
3628 #define getjob(name, getctl) getjob(name)
3631 getjob(const char *name, int getctl)
3635 const char *err_msg = "%s: no such job";
3639 char *(*match)(const char *, const char *);
3654 if (c == '+' || c == '%') {
3656 err_msg = "No current job";
3662 err_msg = "No previous job";
3672 if (num > 0 && num <= njobs) {
3673 jp = jobtab + num - 1;
3688 if (match(jp->ps[0].ps_cmd, p)) {
3692 err_msg = "%s: ambiguous";
3702 err_msg = "job %s not created under job control";
3703 if (getctl && jp->jobctl == 0)
3708 ash_msg_and_raise_error(err_msg, name);
3712 * Mark a job structure as unused.
3715 freejob(struct job *jp)
3717 struct procstat *ps;
3721 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3722 if (ps->ps_cmd != nullstr)
3725 if (jp->ps != &jp->ps0)
3728 set_curjob(jp, CUR_DELETE);
3734 xtcsetpgrp(int fd, pid_t pgrp)
3736 if (tcsetpgrp(fd, pgrp))
3737 ash_msg_and_raise_error("can't set tty process group (%m)");
3741 * Turn job control on and off.
3743 * Note: This code assumes that the third arg to ioctl is a character
3744 * pointer, which is true on Berkeley systems but not System V. Since
3745 * System V doesn't have job control yet, this isn't a problem now.
3747 * Called with interrupts off.
3755 if (on == doing_jobctl || rootshell == 0)
3759 ofd = fd = open(_PATH_TTY, O_RDWR);
3761 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3762 * That sometimes helps to acquire controlling tty.
3763 * Obviously, a workaround for bugs when someone
3764 * failed to provide a controlling tty to bash! :) */
3770 /* fd is a tty at this point */
3771 fd = fcntl(fd, F_DUPFD, 10);
3772 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3775 goto out; /* F_DUPFD failed */
3776 close_on_exec_on(fd);
3777 while (1) { /* while we are in the background */
3778 pgrp = tcgetpgrp(fd);
3781 ash_msg("can't access tty; job control turned off");
3785 if (pgrp == getpgrp())
3796 xtcsetpgrp(fd, pgrp);
3798 /* turning job control off */
3801 /* was xtcsetpgrp, but this can make exiting ash
3802 * loop forever if pty is already deleted */
3803 tcsetpgrp(fd, pgrp);
3817 static int FAST_FUNC
3818 killcmd(int argc, char **argv)
3820 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3823 if (argv[i][0] == '%') {
3825 * "kill %N" - job kill
3826 * Converting to pgrp / pid kill
3832 jp = getjob(argv[i], 0);
3834 * In jobs started under job control, we signal
3835 * entire process group by kill -PGRP_ID.
3836 * This happens, f.e., in interactive shell.
3838 * Otherwise, we signal each child via
3839 * kill PID1 PID2 PID3.
3841 * sh -c 'sleep 1|sleep 1 & kill %1'
3842 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3843 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3845 n = jp->nprocs; /* can't be 0 (I hope) */
3848 dst = alloca(n * sizeof(int)*4);
3850 for (j = 0; j < n; j++) {
3851 struct procstat *ps = &jp->ps[j];
3852 /* Skip non-running and not-stopped members
3853 * (i.e. dead members) of the job
3855 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3858 * kill_main has matching code to expect
3859 * leading space. Needed to not confuse
3860 * negative pids with "kill -SIGNAL_NO" syntax
3862 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3866 } while (argv[++i]);
3868 return kill_main(argc, argv);
3872 showpipe(struct job *jp /*, FILE *out*/)
3874 struct procstat *ps;
3875 struct procstat *psend;
3877 psend = jp->ps + jp->nprocs;
3878 for (ps = jp->ps + 1; ps < psend; ps++)
3879 printf(" | %s", ps->ps_cmd);
3880 newline_and_flush(stdout);
3881 flush_stdout_stderr();
3886 restartjob(struct job *jp, int mode)
3888 struct procstat *ps;
3894 if (jp->state == JOBDONE)
3896 jp->state = JOBRUNNING;
3897 pgid = jp->ps[0].ps_pid;
3898 if (mode == FORK_FG)
3899 xtcsetpgrp(ttyfd, pgid);
3900 killpg(pgid, SIGCONT);
3904 if (WIFSTOPPED(ps->ps_status)) {
3910 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3915 static int FAST_FUNC
3916 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3922 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3926 jp = getjob(*argv, 1);
3927 if (mode == FORK_BG) {
3928 set_curjob(jp, CUR_RUNNING);
3929 printf("[%d] ", jobno(jp));
3931 out1str(jp->ps[0].ps_cmd);
3932 showpipe(jp /*, stdout*/);
3933 retval = restartjob(jp, mode);
3934 } while (*argv && *++argv);
3940 sprint_status48(char *s, int status, int sigonly)
3946 if (!WIFEXITED(status)) {
3947 if (JOBS && WIFSTOPPED(status))
3948 st = WSTOPSIG(status);
3950 st = WTERMSIG(status);
3952 if (st == SIGINT || st == SIGPIPE)
3954 if (JOBS && WIFSTOPPED(status))
3958 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3959 col = fmtstr(s, 32, strsignal(st));
3960 if (WCOREDUMP(status)) {
3961 strcpy(s + col, " (core dumped)");
3962 col += sizeof(" (core dumped)")-1;
3964 } else if (!sigonly) {
3965 st = WEXITSTATUS(status);
3966 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3973 wait_block_or_sig(int *status)
3980 /* Poll all children for changes in their state */
3982 /* if job control is active, accept stopped processes too */
3983 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3985 break; /* Error (e.g. EINTR, ECHILD) or pid */
3987 /* Children exist, but none are ready. Sleep until interesting signal */
3990 sigprocmask(SIG_SETMASK, &mask, &mask);
3991 while (!got_sigchld && !pending_sig)
3993 sigprocmask(SIG_SETMASK, &mask, NULL);
3994 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3995 while (!got_sigchld && !pending_sig)
3999 /* If it was SIGCHLD, poll children again */
4000 } while (got_sigchld);
4005 #define DOWAIT_NONBLOCK 0
4006 #define DOWAIT_BLOCK 1
4007 #define DOWAIT_BLOCK_OR_SIG 2
4010 dowait(int block, struct job *job)
4015 struct job *thisjob = NULL;
4017 TRACE(("dowait(0x%x) called\n", block));
4019 /* It's wrong to call waitpid() outside of INT_OFF region:
4020 * signal can arrive just after syscall return and handler can
4021 * longjmp away, losing stop/exit notification processing.
4022 * Thus, for "jobs" builtin, and for waiting for a fg job,
4023 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4025 * However, for "wait" builtin it is wrong to simply call waitpid()
4026 * in INT_OFF region: "wait" needs to wait for any running job
4027 * to change state, but should exit on any trap too.
4028 * In INT_OFF region, a signal just before syscall entry can set
4029 * pending_sig variables, but we can't check them, and we would
4030 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4032 * Because of this, we run inside INT_OFF, but use a special routine
4033 * which combines waitpid() and sigsuspend().
4034 * This is the reason why we need to have a handler for SIGCHLD:
4035 * SIG_DFL handler does not wake sigsuspend().
4038 if (block == DOWAIT_BLOCK_OR_SIG) {
4039 pid = wait_block_or_sig(&status);
4042 if (block == DOWAIT_NONBLOCK)
4043 wait_flags = WNOHANG;
4044 /* if job control is active, accept stopped processes too */
4046 wait_flags |= WUNTRACED;
4047 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4048 pid = waitpid(-1, &status, wait_flags);
4050 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4051 pid, status, errno, strerror(errno)));
4056 for (jp = curjob; jp; jp = jp->prev_job) {
4058 struct procstat *ps;
4059 struct procstat *psend;
4060 if (jp->state == JOBDONE)
4064 psend = ps + jp->nprocs;
4066 if (ps->ps_pid == pid) {
4067 TRACE(("Job %d: changing status of proc %d "
4068 "from 0x%x to 0x%x\n",
4069 jobno(jp), pid, ps->ps_status, status));
4070 ps->ps_status = status;
4073 if (ps->ps_status == -1)
4074 jobstate = JOBRUNNING;
4076 if (jobstate == JOBRUNNING)
4078 if (WIFSTOPPED(ps->ps_status)) {
4079 jp->stopstatus = ps->ps_status;
4080 jobstate = JOBSTOPPED;
4083 } while (++ps < psend);
4087 /* Found the job where one of its processes changed its state.
4088 * Is there at least one live and running process in this job? */
4089 if (jobstate != JOBRUNNING) {
4090 /* No. All live processes in the job are stopped
4091 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4093 thisjob->changed = 1;
4094 if (thisjob->state != jobstate) {
4095 TRACE(("Job %d: changing state from %d to %d\n",
4096 jobno(thisjob), thisjob->state, jobstate));
4097 thisjob->state = jobstate;
4099 if (jobstate == JOBSTOPPED)
4100 set_curjob(thisjob, CUR_STOPPED);
4106 /* The process wasn't found in job list */
4107 if (JOBS && !WIFSTOPPED(status))
4112 if (thisjob && thisjob == job) {
4116 len = sprint_status48(s, status, 1);
4128 showjob(struct job *jp, int mode)
4130 struct procstat *ps;
4131 struct procstat *psend;
4134 char s[16 + 16 + 48];
4135 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4139 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4140 /* just output process (group) id of pipeline */
4141 fprintf(out, "%d\n", ps->ps_pid);
4145 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4150 else if (curjob && jp == curjob->prev_job)
4153 if (mode & SHOW_PIDS)
4154 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4156 psend = ps + jp->nprocs;
4158 if (jp->state == JOBRUNNING) {
4159 strcpy(s + col, "Running");
4160 col += sizeof("Running") - 1;
4162 int status = psend[-1].ps_status;
4163 if (jp->state == JOBSTOPPED)
4164 status = jp->stopstatus;
4165 col += sprint_status48(s + col, status, 0);
4167 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4169 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4170 * or prints several "PID | <cmdN>" lines,
4171 * depending on SHOW_PIDS bit.
4172 * We do not print status of individual processes
4173 * between PID and <cmdN>. bash does it, but not very well:
4174 * first line shows overall job status, not process status,
4175 * making it impossible to know 1st process status.
4179 /* for each process */
4182 if (mode & SHOW_PIDS)
4183 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4185 fprintf(out, "%s%*c%s%s",
4187 33 - col >= 0 ? 33 - col : 0, ' ',
4188 ps == jp->ps ? "" : "| ",
4191 } while (++ps != psend);
4192 newline_and_flush(out);
4196 if (jp->state == JOBDONE) {
4197 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4203 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4204 * statuses have changed since the last call to showjobs.
4211 TRACE(("showjobs(0x%x) called\n", mode));
4213 /* Handle all finished jobs */
4214 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4217 for (jp = curjob; jp; jp = jp->prev_job) {
4218 if (!(mode & SHOW_CHANGED) || jp->changed) {
4224 static int FAST_FUNC
4225 jobscmd(int argc UNUSED_PARAM, char **argv)
4230 while ((m = nextopt("lp")) != '\0') {
4234 mode |= SHOW_ONLY_PGID;
4240 showjob(getjob(*argv, 0), mode);
4250 /* Called only on finished or stopped jobs (no members are running) */
4252 getstatus(struct job *job)
4256 struct procstat *ps;
4258 /* Fetch last member's status */
4259 ps = job->ps + job->nprocs - 1;
4260 status = ps->ps_status;
4262 /* "set -o pipefail" mode: use last _nonzero_ status */
4263 while (status == 0 && --ps >= job->ps)
4264 status = ps->ps_status;
4267 retval = WEXITSTATUS(status);
4268 if (!WIFEXITED(status)) {
4270 retval = WSTOPSIG(status);
4271 if (!WIFSTOPPED(status))
4274 /* XXX: limits number of signals */
4275 retval = WTERMSIG(status);
4277 if (retval == SIGINT)
4283 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4284 jobno(job), job->nprocs, status, retval));
4288 static int FAST_FUNC
4289 waitcmd(int argc UNUSED_PARAM, char **argv)
4300 /* wait for all jobs */
4304 if (!jp) /* no running procs */
4306 if (jp->state == JOBRUNNING)
4312 * "When bash is waiting for an asynchronous command via
4313 * the wait builtin, the reception of a signal for which a trap
4314 * has been set will cause the wait builtin to return immediately
4315 * with an exit status greater than 128, immediately after which
4316 * the trap is executed."
4318 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4319 /* if child sends us a signal *and immediately exits*,
4320 * dowait() returns pid > 0. Check this case,
4321 * not "if (dowait() < 0)"!
4330 if (**argv != '%') {
4331 pid_t pid = number(*argv);
4336 if (job->ps[job->nprocs - 1].ps_pid == pid)
4338 job = job->prev_job;
4341 job = getjob(*argv, 0);
4343 /* loop until process terminated or stopped */
4344 while (job->state == JOBRUNNING) {
4345 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4350 retval = getstatus(job);
4357 retval = 128 + pending_sig;
4366 struct job *jp, *jq;
4368 len = njobs * sizeof(*jp);
4370 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4372 offset = (char *)jp - (char *)jq;
4374 /* Relocate pointers */
4377 jq = (struct job *)((char *)jq + l);
4381 #define joff(p) ((struct job *)((char *)(p) + l))
4382 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4383 if (joff(jp)->ps == &jq->ps0)
4384 jmove(joff(jp)->ps);
4385 if (joff(jp)->prev_job)
4386 jmove(joff(jp)->prev_job);
4396 jp = (struct job *)((char *)jp + len);
4400 } while (--jq >= jp);
4405 * Return a new job structure.
4406 * Called with interrupts off.
4409 makejob(/*union node *node,*/ int nprocs)
4414 for (i = njobs, jp = jobtab; ; jp++) {
4421 if (jp->state != JOBDONE || !jp->waited)
4430 memset(jp, 0, sizeof(*jp));
4432 /* jp->jobctl is a bitfield.
4433 * "jp->jobctl |= jobctl" likely to give awful code */
4437 jp->prev_job = curjob;
4442 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4444 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4451 * Return a string identifying a command (to be printed by the
4454 static char *cmdnextc;
4457 cmdputs(const char *s)
4459 static const char vstype[VSTYPE + 1][3] = {
4460 "", "}", "-", "+", "?", "=",
4461 "%", "%%", "#", "##"
4462 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4465 const char *p, *str;
4469 unsigned char subtype = 0;
4473 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4475 while ((c = *p++) != '\0') {
4483 if ((subtype & VSTYPE) == VSLENGTH)
4489 str = "\"}" + !(quoted & 1);
4496 #if ENABLE_FEATURE_SH_MATH
4511 if ((subtype & VSTYPE) != VSNORMAL)
4513 str = vstype[subtype & VSTYPE];
4514 if (subtype & VSNUL)
4523 /* These can only happen inside quotes */
4536 while ((c = *str++) != '\0') {
4539 } /* while *p++ not NUL */
4542 USTPUTC('"', nextc);
4548 /* cmdtxt() and cmdlist() call each other */
4549 static void cmdtxt(union node *n);
4552 cmdlist(union node *np, int sep)
4554 for (; np; np = np->narg.next) {
4558 if (sep && np->narg.next)
4564 cmdtxt(union node *n)
4567 struct nodelist *lp;
4578 lp = n->npipe.cmdlist;
4596 cmdtxt(n->nbinary.ch1);
4612 cmdtxt(n->nif.test);
4614 if (n->nif.elsepart) {
4615 cmdtxt(n->nif.ifpart);
4617 n = n->nif.elsepart;
4635 cmdtxt(n->nbinary.ch1);
4645 cmdputs(n->nfor.var);
4647 cmdlist(n->nfor.args, 1);
4652 cmdputs(n->narg.text);
4656 cmdlist(n->ncmd.args, 1);
4657 cmdlist(n->ncmd.redirect, 0);
4670 cmdputs(n->ncase.expr->narg.text);
4672 for (np = n->ncase.cases; np; np = np->nclist.next) {
4673 cmdtxt(np->nclist.pattern);
4675 cmdtxt(np->nclist.body);
4689 #if ENABLE_ASH_BASH_COMPAT
4704 cmdputs(utoa(n->nfile.fd));
4706 if (n->type == NTOFD || n->type == NFROMFD) {
4707 cmdputs(utoa(n->ndup.dupfd));
4716 commandtext(union node *n)
4720 STARTSTACKSTR(cmdnextc);
4722 name = stackblock();
4723 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4724 return ckstrdup(name);
4729 * Fork off a subshell. If we are doing job control, give the subshell its
4730 * own process group. Jp is a job structure that the job is to be added to.
4731 * N is the command that will be evaluated by the child. Both jp and n may
4732 * be NULL. The mode parameter can be one of the following:
4733 * FORK_FG - Fork off a foreground process.
4734 * FORK_BG - Fork off a background process.
4735 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4736 * process group even if job control is on.
4738 * When job control is turned off, background processes have their standard
4739 * input redirected to /dev/null (except for the second and later processes
4742 * Called with interrupts off.
4745 * Clear traps on a fork.
4753 for (tp = trap; tp < &trap[NSIG]; tp++) {
4754 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4755 if (trap_ptr == trap)
4757 /* else: it "belongs" to trap_ptr vector, don't free */
4759 if ((tp - trap) != 0)
4760 setsignal(tp - trap);
4767 /* Lives far away from here, needed for forkchild */
4768 static void closescript(void);
4770 /* Called after fork(), in child */
4771 /* jp and n are NULL when called by openhere() for heredoc support */
4772 static NOINLINE void
4773 forkchild(struct job *jp, union node *n, int mode)
4777 TRACE(("Child shell %d\n", getpid()));
4781 /* man bash: "Non-builtin commands run by bash have signal handlers
4782 * set to the values inherited by the shell from its parent".
4783 * Do we do it correctly? */
4787 if (mode == FORK_NOJOB /* is it `xxx` ? */
4788 && n && n->type == NCMD /* is it single cmd? */
4789 /* && n->ncmd.args->type == NARG - always true? */
4790 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4791 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4792 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4794 TRACE(("Trap hack\n"));
4795 /* Awful hack for `trap` or $(trap).
4797 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4798 * contains an example where "trap" is executed in a subshell:
4800 * save_traps=$(trap)
4802 * eval "$save_traps"
4804 * Standard does not say that "trap" in subshell shall print
4805 * parent shell's traps. It only says that its output
4806 * must have suitable form, but then, in the above example
4807 * (which is not supposed to be normative), it implies that.
4809 * bash (and probably other shell) does implement it
4810 * (traps are reset to defaults, but "trap" still shows them),
4811 * but as a result, "trap" logic is hopelessly messed up:
4814 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4815 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4816 * # true | trap <--- trap is in subshell - no output (ditto)
4817 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4818 * trap -- 'echo Ho' SIGWINCH
4819 * # echo `(trap)` <--- in subshell in subshell - output
4820 * trap -- 'echo Ho' SIGWINCH
4821 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4822 * trap -- 'echo Ho' SIGWINCH
4824 * The rules when to forget and when to not forget traps
4825 * get really complex and nonsensical.
4827 * Our solution: ONLY bare $(trap) or `trap` is special.
4829 /* Save trap handler strings for trap builtin to print */
4830 trap_ptr = xmemdup(trap, sizeof(trap));
4831 /* Fall through into clearing traps */
4835 /* do job control only in root shell */
4837 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4840 if (jp->nprocs == 0)
4843 pgrp = jp->ps[0].ps_pid;
4844 /* this can fail because we are doing it in the parent also */
4846 if (mode == FORK_FG)
4847 xtcsetpgrp(ttyfd, pgrp);
4852 if (mode == FORK_BG) {
4853 /* man bash: "When job control is not in effect,
4854 * asynchronous commands ignore SIGINT and SIGQUIT" */
4857 if (jp->nprocs == 0) {
4859 if (open(bb_dev_null, O_RDONLY) != 0)
4860 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4864 if (iflag) { /* why if iflag only? */
4869 * "In all cases, bash ignores SIGQUIT. Non-builtin
4870 * commands run by bash have signal handlers
4871 * set to the values inherited by the shell
4873 * Take care of the second rule: */
4877 if (n && n->type == NCMD
4878 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4880 TRACE(("Job hack\n"));
4881 /* "jobs": we do not want to clear job list for it,
4882 * instead we remove only _its_ own_ job from job list.
4883 * This makes "jobs .... | cat" more useful.
4889 for (jp = curjob; jp; jp = jp->prev_job)
4894 /* Called after fork(), in parent */
4896 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4899 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4901 TRACE(("In parent shell: child = %d\n", pid));
4903 /* jp is NULL when called by openhere() for heredoc support */
4904 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4910 if (mode != FORK_NOJOB && jp->jobctl) {
4913 if (jp->nprocs == 0)
4916 pgrp = jp->ps[0].ps_pid;
4917 /* This can fail because we are doing it in the child also */
4921 if (mode == FORK_BG) {
4922 backgndpid = pid; /* set $! */
4923 set_curjob(jp, CUR_RUNNING);
4926 struct procstat *ps = &jp->ps[jp->nprocs++];
4929 ps->ps_cmd = nullstr;
4931 if (doing_jobctl && n)
4932 ps->ps_cmd = commandtext(n);
4937 /* jp and n are NULL when called by openhere() for heredoc support */
4939 forkshell(struct job *jp, union node *n, int mode)
4943 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4946 TRACE(("Fork failed, errno=%d", errno));
4949 ash_msg_and_raise_error("can't fork");
4952 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4953 forkchild(jp, n, mode);
4955 forkparent(jp, n, mode, pid);
4961 * Wait for job to finish.
4963 * Under job control we have the problem that while a child process
4964 * is running interrupts generated by the user are sent to the child
4965 * but not to the shell. This means that an infinite loop started by
4966 * an interactive user may be hard to kill. With job control turned off,
4967 * an interactive user may place an interactive program inside a loop.
4968 * If the interactive program catches interrupts, the user doesn't want
4969 * these interrupts to also abort the loop. The approach we take here
4970 * is to have the shell ignore interrupt signals while waiting for a
4971 * foreground process to terminate, and then send itself an interrupt
4972 * signal if the child process was terminated by an interrupt signal.
4973 * Unfortunately, some programs want to do a bit of cleanup and then
4974 * exit on interrupt; unless these processes terminate themselves by
4975 * sending a signal to themselves (instead of calling exit) they will
4976 * confuse this approach.
4978 * Called with interrupts off.
4981 waitforjob(struct job *jp)
4985 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4988 while (jp->state == JOBRUNNING) {
4989 /* In non-interactive shells, we _can_ get
4990 * a keyboard signal here and be EINTRed,
4991 * but we just loop back, waiting for command to complete.
4994 * "If bash is waiting for a command to complete and receives
4995 * a signal for which a trap has been set, the trap
4996 * will not be executed until the command completes."
4998 * Reality is that even if trap is not set, bash
4999 * will not act on the signal until command completes.
5000 * Try this. sleep5intoff.c:
5001 * #include <signal.h>
5002 * #include <unistd.h>
5005 * sigemptyset(&set);
5006 * sigaddset(&set, SIGINT);
5007 * sigaddset(&set, SIGQUIT);
5008 * sigprocmask(SIG_BLOCK, &set, NULL);
5012 * $ bash -c './sleep5intoff; echo hi'
5013 * ^C^C^C^C <--- pressing ^C once a second
5015 * $ bash -c './sleep5intoff; echo hi'
5016 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5019 dowait(DOWAIT_BLOCK, jp);
5026 xtcsetpgrp(ttyfd, rootpid);
5028 * This is truly gross.
5029 * If we're doing job control, then we did a TIOCSPGRP which
5030 * caused us (the shell) to no longer be in the controlling
5031 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5032 * intuit from the subprocess exit status whether a SIGINT
5033 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5035 if (jp->sigint) /* TODO: do the same with all signals */
5036 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5038 if (jp->state == JOBDONE)
5045 * return 1 if there are stopped jobs, otherwise 0
5057 if (jp && jp->state == JOBSTOPPED) {
5058 out2str("You have stopped jobs.\n");
5068 * Code for dealing with input/output redirection.
5073 #define EMPTY -2 /* marks an unused slot in redirtab */
5074 #define CLOSED -3 /* marks a slot of previously-closed fd */
5077 * Open a file in noclobber mode.
5078 * The code was copied from bash.
5081 noclobberopen(const char *fname)
5084 struct stat finfo, finfo2;
5087 * If the file exists and is a regular file, return an error
5090 r = stat(fname, &finfo);
5091 if (r == 0 && S_ISREG(finfo.st_mode)) {
5097 * If the file was not present (r != 0), make sure we open it
5098 * exclusively so that if it is created before we open it, our open
5099 * will fail. Make sure that we do not truncate an existing file.
5100 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5101 * file was not a regular file, we leave O_EXCL off.
5104 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5105 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5107 /* If the open failed, return the file descriptor right away. */
5112 * OK, the open succeeded, but the file may have been changed from a
5113 * non-regular file to a regular file between the stat and the open.
5114 * We are assuming that the O_EXCL open handles the case where FILENAME
5115 * did not exist and is symlinked to an existing file between the stat
5120 * If we can open it and fstat the file descriptor, and neither check
5121 * revealed that it was a regular file, and the file has not been
5122 * replaced, return the file descriptor.
5124 if (fstat(fd, &finfo2) == 0
5125 && !S_ISREG(finfo2.st_mode)
5126 && finfo.st_dev == finfo2.st_dev
5127 && finfo.st_ino == finfo2.st_ino
5132 /* The file has been replaced. badness. */
5139 * Handle here documents. Normally we fork off a process to write the
5140 * data to a pipe. If the document is short, we can stuff the data in
5141 * the pipe without forking.
5143 /* openhere needs this forward reference */
5144 static void expandhere(union node *arg, int fd);
5146 openhere(union node *redir)
5152 ash_msg_and_raise_error("pipe call failed");
5153 if (redir->type == NHERE) {
5154 len = strlen(redir->nhere.doc->narg.text);
5155 if (len <= PIPE_BUF) {
5156 full_write(pip[1], redir->nhere.doc->narg.text, len);
5160 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5163 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5164 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5165 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5166 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5167 signal(SIGPIPE, SIG_DFL);
5168 if (redir->type == NHERE)
5169 full_write(pip[1], redir->nhere.doc->narg.text, len);
5171 expandhere(redir->nhere.doc, pip[1]);
5172 _exit(EXIT_SUCCESS);
5180 openredirect(union node *redir)
5185 switch (redir->nfile.type) {
5186 /* Can't happen, our single caller does this itself */
5192 return openhere(redir);
5195 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5196 * allocated space. Do it only when we know it is safe.
5198 fname = redir->nfile.expfname;
5200 switch (redir->nfile.type) {
5206 f = open(fname, O_RDONLY);
5211 f = open(fname, O_RDWR|O_CREAT, 0666);
5216 #if ENABLE_ASH_BASH_COMPAT
5219 /* Take care of noclobber mode. */
5221 f = noclobberopen(fname);
5228 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5233 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5241 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5243 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5247 * Copy a file descriptor to be >= 10. Throws exception on error.
5255 newfd = fcntl(from, F_DUPFD, 10);
5256 err = newfd < 0 ? errno : 0;
5259 ash_msg_and_raise_error("%d: %m", from);
5261 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5267 dup2_or_raise(int from, int to)
5271 newfd = (from != to) ? dup2(from, to) : to;
5273 /* Happens when source fd is not open: try "echo >&99" */
5274 ash_msg_and_raise_error("%d: %m", from);
5279 /* Struct def and variable are moved down to the first usage site */
5284 struct redirtab *next;
5286 struct two_fd_t two_fd[];
5288 #define redirlist (G_var.redirlist)
5290 COPYFD_RESTORE = (int)~(INT_MAX),
5294 need_to_remember(struct redirtab *rp, int fd)
5298 if (!rp) /* remembering was not requested */
5301 for (i = 0; i < rp->pair_count; i++) {
5302 if (rp->two_fd[i].orig == fd) {
5303 /* already remembered */
5310 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5312 is_hidden_fd(struct redirtab *rp, int fd)
5315 struct parsefile *pf;
5319 /* Check open scripts' fds */
5322 /* We skip pf_fd == 0 case because of the following case:
5323 * $ ash # running ash interactively
5325 * and in script.sh: "exec 9>&0".
5326 * Even though top-level pf_fd _is_ 0,
5327 * it's still ok to use it: "read" builtin uses it,
5328 * why should we cripple "exec" builtin?
5330 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5338 /* Check saved fds of redirects */
5339 fd |= COPYFD_RESTORE;
5340 for (i = 0; i < rp->pair_count; i++) {
5341 if (rp->two_fd[i].copy == fd) {
5349 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5350 * old file descriptors are stashed away so that the redirection can be
5351 * undone by calling popredir.
5353 /* flags passed to redirect */
5354 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5355 #define REDIR_SAVEFD2 03 /* set preverrout */
5357 redirect(union node *redir, int flags)
5359 struct redirtab *sv;
5364 int copied_fd2 = -1;
5373 if (flags & REDIR_PUSH) {
5374 union node *tmp = redir;
5377 #if ENABLE_ASH_BASH_COMPAT
5378 if (tmp->nfile.type == NTO2)
5381 tmp = tmp->nfile.next;
5383 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5384 sv->next = redirlist;
5385 sv->pair_count = sv_pos;
5387 while (sv_pos > 0) {
5389 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5395 fd = redir->nfile.fd;
5396 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5397 right_fd = redir->ndup.dupfd;
5398 //bb_error_msg("doing %d > %d", fd, right_fd);
5399 /* redirect from/to same file descriptor? */
5402 /* "echo >&10" and 10 is a fd opened to a sh script? */
5403 if (is_hidden_fd(sv, right_fd)) {
5404 errno = EBADF; /* as if it is closed */
5405 ash_msg_and_raise_error("%d: %m", right_fd);
5409 newfd = openredirect(redir); /* always >= 0 */
5411 /* Descriptor wasn't open before redirect.
5412 * Mark it for close in the future */
5413 if (need_to_remember(sv, fd)) {
5414 goto remember_to_close;
5419 #if ENABLE_ASH_BASH_COMPAT
5422 if (need_to_remember(sv, fd)) {
5423 /* Copy old descriptor */
5424 /* Careful to not accidentally "save"
5425 * to the same fd as right side fd in N>&M */
5426 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5427 i = fcntl(fd, F_DUPFD, minfd);
5428 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5429 * are closed in popredir() in the child, preventing them from leaking
5430 * into child. (popredir() also cleans up the mess in case of failures)
5435 /* Strange error (e.g. "too many files" EMFILE?) */
5439 ash_msg_and_raise_error("%d: %m", fd);
5442 /* EBADF: it is not open - good, remember to close it */
5445 } else { /* fd is open, save its copy */
5446 /* "exec fd>&-" should not close fds
5447 * which point to script file(s).
5448 * Force them to be restored afterwards */
5449 if (is_hidden_fd(sv, fd))
5450 i |= COPYFD_RESTORE;
5454 sv->two_fd[sv_pos].orig = fd;
5455 sv->two_fd[sv_pos].copy = i;
5459 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5460 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5461 /* Don't want to trigger debugging */
5465 dup2_or_raise(redir->ndup.dupfd, fd);
5467 } else if (fd != newfd) { /* move newfd to fd */
5468 dup2_or_raise(newfd, fd);
5469 #if ENABLE_ASH_BASH_COMPAT
5470 if (!(redir->nfile.type == NTO2 && fd == 2))
5474 #if ENABLE_ASH_BASH_COMPAT
5475 if (redir->nfile.type == NTO2 && fd == 1) {
5476 /* We already redirected it to fd 1, now copy it to 2 */
5482 } while ((redir = redir->nfile.next) != NULL);
5485 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5486 preverrout_fd = copied_fd2;
5490 * Undo the effects of the last redirection.
5493 popredir(int drop, int restore)
5495 struct redirtab *rp;
5498 if (redirlist == NULL)
5502 for (i = 0; i < rp->pair_count; i++) {
5503 int fd = rp->two_fd[i].orig;
5504 int copy = rp->two_fd[i].copy;
5505 if (copy == CLOSED) {
5510 if (copy != EMPTY) {
5511 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5512 copy &= ~COPYFD_RESTORE;
5514 dup2_or_raise(copy, fd);
5516 close(copy & ~COPYFD_RESTORE);
5519 redirlist = rp->next;
5525 * Undo all redirections. Called on error or interrupt.
5529 redirectsafe(union node *redir, int flags)
5532 volatile int saveint;
5533 struct jmploc *volatile savehandler = exception_handler;
5534 struct jmploc jmploc;
5537 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5538 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5540 exception_handler = &jmploc;
5541 redirect(redir, flags);
5543 exception_handler = savehandler;
5544 if (err && exception_type != EXERROR)
5545 longjmp(exception_handler->loc, 1);
5546 RESTORE_INT(saveint);
5551 /* ============ Routines to expand arguments to commands
5553 * We have to deal with backquotes, shell variables, and file metacharacters.
5556 #if ENABLE_FEATURE_SH_MATH
5558 ash_arith(const char *s)
5560 arith_state_t math_state;
5563 math_state.lookupvar = lookupvar;
5564 math_state.setvar = setvar0;
5565 //math_state.endofname = endofname;
5568 result = arith(&math_state, s);
5569 if (math_state.errmsg)
5570 ash_msg_and_raise_error(math_state.errmsg);
5580 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5581 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5582 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5583 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5584 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5585 * POSIX says for this case:
5586 * Pathname expansion shall not be performed on the word by a
5587 * non-interactive shell; an interactive shell may perform it, but shall
5588 * do so only when the expansion would result in one word.
5589 * Currently, our code complies to the above rule by never globbing
5590 * redirection filenames.
5591 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5592 * (this means that on a typical Linux distro, bash almost always
5593 * performs globbing, and thus diverges from what we do).
5595 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5596 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5597 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5598 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5599 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5603 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5604 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5605 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5606 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5607 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5609 /* Add CTLESC when necessary. */
5610 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5611 /* Do not skip NUL characters. */
5612 #define QUOTES_KEEPNUL EXP_TILDE
5615 * Structure specifying which parts of the string should be searched
5616 * for IFS characters.
5619 struct ifsregion *next; /* next region in list */
5620 int begoff; /* offset of start of region */
5621 int endoff; /* offset of end of region */
5622 int nulonly; /* search for nul bytes only */
5626 struct strlist *list;
5627 struct strlist **lastp;
5630 /* output of current string */
5631 static char *expdest;
5632 /* list of back quote expressions */
5633 static struct nodelist *argbackq;
5634 /* first struct in list of ifs regions */
5635 static struct ifsregion ifsfirst;
5636 /* last struct in list */
5637 static struct ifsregion *ifslastp;
5638 /* holds expanded arg list */
5639 static struct arglist exparg;
5644 #if !ENABLE_FEATURE_SH_MATH
5645 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5646 typedef long arith_t;
5647 # define ARITH_FMT "%ld"
5654 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5655 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5656 STADJUST(len, expdest);
5661 * Break the argument string into pieces based upon IFS and add the
5662 * strings to the argument list. The regions of the string to be
5663 * searched for IFS characters have been stored by recordregion.
5666 ifsbreakup(char *string, struct arglist *arglist)
5668 struct ifsregion *ifsp;
5673 const char *ifs, *realifs;
5678 if (ifslastp != NULL) {
5681 realifs = ifsset() ? ifsval() : defifs;
5684 p = string + ifsp->begoff;
5685 nulonly = ifsp->nulonly;
5686 ifs = nulonly ? nullstr : realifs;
5688 while (p < string + ifsp->endoff) {
5690 if ((unsigned char)*p == CTLESC)
5692 if (!strchr(ifs, *p)) {
5697 ifsspc = (strchr(defifs, *p) != NULL);
5698 /* Ignore IFS whitespace at start */
5699 if (q == start && ifsspc) {
5705 sp = stzalloc(sizeof(*sp));
5707 *arglist->lastp = sp;
5708 arglist->lastp = &sp->next;
5712 if (p >= string + ifsp->endoff) {
5716 if ((unsigned char)*p == CTLESC)
5718 if (strchr(ifs, *p) == NULL) {
5722 if (strchr(defifs, *p) == NULL) {
5737 } while (ifsp != NULL);
5746 sp = stzalloc(sizeof(*sp));
5748 *arglist->lastp = sp;
5749 arglist->lastp = &sp->next;
5755 struct ifsregion *p = ifsfirst.next;
5762 struct ifsregion *ifsp;
5767 ifsfirst.next = NULL;
5774 esclen(const char *start, const char *p)
5778 while (p > start && (unsigned char)*--p == CTLESC) {
5785 * Remove any CTLESC characters from a string.
5788 rmescapes(char *str, int flag)
5790 static const char qchars[] ALIGN1 = {
5791 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5795 unsigned protect_against_glob;
5797 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5799 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5805 if (flag & RMESCAPE_ALLOC) {
5806 size_t len = p - str;
5807 size_t fulllen = len + strlen(p) + 1;
5809 if (flag & RMESCAPE_GROW) {
5810 int strloc = str - (char *)stackblock();
5811 r = makestrspace(fulllen, expdest);
5812 /* p and str may be invalidated by makestrspace */
5813 str = (char *)stackblock() + strloc;
5815 } else if (flag & RMESCAPE_HEAP) {
5816 r = ckmalloc(fulllen);
5818 r = stalloc(fulllen);
5822 q = (char *)memcpy(q, str, len) + len;
5827 globbing = flag & RMESCAPE_GLOB;
5828 protect_against_glob = globbing;
5830 if ((unsigned char)*p == CTLQUOTEMARK) {
5831 // Note: both inquotes and protect_against_glob only affect whether
5832 inquotes = ~inquotes;
5834 protect_against_glob = globbing;
5837 if ((unsigned char)*p == CTLESC) {
5841 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5843 if (protect_against_glob) {
5846 } else if (*p == '\\' && !inquotes) {
5847 /* naked back slash */
5848 protect_against_glob = 0;
5851 #if ENABLE_ASH_BASH_COMPAT
5852 else if (*p == '/' && slash) {
5853 /* stop handling globbing and mark location of slash */
5854 globbing = slash = 0;
5858 protect_against_glob = globbing;
5863 if (flag & RMESCAPE_GROW) {
5865 STADJUST(q - r + 1, expdest);
5869 #define pmatch(a, b) !fnmatch((a), (b), 0)
5872 * Prepare a pattern for a expmeta (internal glob(3)) call.
5874 * Returns an stalloced string.
5877 preglob(const char *pattern, int flag)
5879 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5883 * Put a string on the stack.
5886 memtodest(const char *p, size_t len, int syntax, int quotes)
5893 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5896 unsigned char c = *p++;
5898 if (quotes & QUOTES_ESC) {
5899 int n = SIT(c, syntax);
5901 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5908 } else if (!(quotes & QUOTES_KEEPNUL))
5917 strtodest(const char *p, int syntax, int quotes)
5919 size_t len = strlen(p);
5920 memtodest(p, len, syntax, quotes);
5925 * Record the fact that we have to scan this region of the
5926 * string for IFS characters.
5929 recordregion(int start, int end, int nulonly)
5931 struct ifsregion *ifsp;
5933 if (ifslastp == NULL) {
5937 ifsp = ckzalloc(sizeof(*ifsp));
5938 /*ifsp->next = NULL; - ckzalloc did it */
5939 ifslastp->next = ifsp;
5943 ifslastp->begoff = start;
5944 ifslastp->endoff = end;
5945 ifslastp->nulonly = nulonly;
5949 removerecordregions(int endoff)
5951 if (ifslastp == NULL)
5954 if (ifsfirst.endoff > endoff) {
5955 while (ifsfirst.next) {
5956 struct ifsregion *ifsp;
5958 ifsp = ifsfirst.next->next;
5959 free(ifsfirst.next);
5960 ifsfirst.next = ifsp;
5963 if (ifsfirst.begoff > endoff) {
5966 ifslastp = &ifsfirst;
5967 ifsfirst.endoff = endoff;
5972 ifslastp = &ifsfirst;
5973 while (ifslastp->next && ifslastp->next->begoff < endoff)
5974 ifslastp = ifslastp->next;
5975 while (ifslastp->next) {
5976 struct ifsregion *ifsp;
5978 ifsp = ifslastp->next->next;
5979 free(ifslastp->next);
5980 ifslastp->next = ifsp;
5983 if (ifslastp->endoff > endoff)
5984 ifslastp->endoff = endoff;
5988 exptilde(char *startp, char *p, int flags)
5994 int quotes = flags & QUOTES_ESC;
5998 while ((c = *++p) != '\0') {
6005 if (flags & EXP_VARTILDE)
6015 if (*name == '\0') {
6016 home = lookupvar("HOME");
6018 pw = getpwnam(name);
6023 if (!home || !*home)
6026 strtodest(home, SQSYNTAX, quotes);
6034 * Execute a command inside back quotes. If it's a builtin command, we
6035 * want to save its output in a block obtained from malloc. Otherwise
6036 * we fork off a subprocess and get the output of the command via a pipe.
6037 * Should be called with interrupts off.
6039 struct backcmd { /* result of evalbackcmd */
6040 int fd; /* file descriptor to read from */
6041 int nleft; /* number of chars in buffer */
6042 char *buf; /* buffer */
6043 struct job *jp; /* job structure for command */
6046 /* These forward decls are needed to use "eval" code for backticks handling: */
6047 #define EV_EXIT 01 /* exit after evaluating tree */
6048 static int evaltree(union node *, int);
6050 static void FAST_FUNC
6051 evalbackcmd(union node *n, struct backcmd *result)
6065 ash_msg_and_raise_error("pipe call failed");
6066 jp = makejob(/*n,*/ 1);
6067 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6073 dup2_or_raise(pip[1], 1);
6076 /* TODO: eflag clearing makes the following not abort:
6077 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6078 * which is what bash does (unless it is in POSIX mode).
6079 * dash deleted "eflag = 0" line in the commit
6080 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6081 * [EVAL] Don't clear eflag in evalbackcmd
6082 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6086 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6091 result->fd = pip[0];
6095 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6096 result->fd, result->buf, result->nleft, result->jp));
6100 * Expand stuff in backwards quotes.
6103 expbackq(union node *cmd, int flag)
6111 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6112 struct stackmark smark;
6115 startloc = expdest - (char *)stackblock();
6116 pushstackmark(&smark, startloc);
6117 evalbackcmd(cmd, &in);
6118 popstackmark(&smark);
6125 memtodest(p, i, syntax, flag & QUOTES_ESC);
6129 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6130 TRACE(("expbackq: read returns %d\n", i));
6139 back_exitstatus = waitforjob(in.jp);
6143 /* Eat all trailing newlines */
6145 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6149 if (!(flag & EXP_QUOTED))
6150 recordregion(startloc, dest - (char *)stackblock(), 0);
6151 TRACE(("evalbackq: size:%d:'%.*s'\n",
6152 (int)((dest - (char *)stackblock()) - startloc),
6153 (int)((dest - (char *)stackblock()) - startloc),
6154 stackblock() + startloc));
6157 #if ENABLE_FEATURE_SH_MATH
6159 * Expand arithmetic expression. Backup to start of expression,
6160 * evaluate, place result in (backed up) result, adjust string position.
6172 * This routine is slightly over-complicated for
6173 * efficiency. Next we scan backwards looking for the
6174 * start of arithmetic.
6176 start = stackblock();
6183 while ((unsigned char)*p != CTLARI) {
6187 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6192 esc = esclen(start, p);
6202 removerecordregions(begoff);
6206 if (flag & QUOTES_ESC)
6207 rmescapes(p + 1, 0);
6209 len = cvtnum(ash_arith(p + 1));
6211 if (!(flag & EXP_QUOTED))
6212 recordregion(begoff, begoff + len, 0);
6216 /* argstr needs it */
6217 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6220 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6221 * characters to allow for further processing. Otherwise treat
6222 * $@ like $* since no splitting will be performed.
6224 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6225 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6226 * for correct expansion of "B=$A" word.
6229 argstr(char *p, int flags, struct strlist *var_str_list)
6231 static const char spclchars[] ALIGN1 = {
6239 #if ENABLE_FEATURE_SH_MATH
6244 const char *reject = spclchars;
6245 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6250 if (!(flags & EXP_VARTILDE)) {
6252 } else if (flags & EXP_VARTILDE2) {
6257 if (flags & EXP_TILDE) {
6260 flags &= ~EXP_TILDE;
6264 p = exptilde(p, q, flags);
6267 startloc = expdest - (char *)stackblock();
6271 length += strcspn(p + length, reject);
6275 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6277 /* c == '=' || c == ':' || c == CTLENDARI */
6283 expdest = stack_nputstr(p, length, expdest);
6284 newloc = expdest - (char *)stackblock();
6285 if (breakall && !inquotes && newloc > startloc) {
6286 recordregion(startloc, newloc, 0);
6297 if (flags & EXP_VARTILDE2) {
6301 flags |= EXP_VARTILDE2;
6306 * sort of a hack - expand tildes in variable
6307 * assignments (after the first '=' and after ':'s).
6316 case CTLENDVAR: /* ??? */
6319 inquotes ^= EXP_QUOTED;
6320 /* "$@" syntax adherence hack */
6321 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6322 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6326 if (flags & QUOTES_ESC) {
6337 * Quoted parameter expansion pattern: remove quote
6338 * unless inside inner quotes or we have a literal
6341 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6342 EXP_QPAT && *p != '\\')
6347 TRACE(("argstr: evalvar('%s')\n", p));
6348 p = evalvar(p, flags | inquotes, var_str_list);
6349 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6352 expbackq(argbackq->n, flags | inquotes);
6353 argbackq = argbackq->next;
6355 #if ENABLE_FEATURE_SH_MATH
6358 expari(flags | inquotes);
6367 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6368 char *pattern, int quotes, int zero)
6377 const char *s = loc2;
6384 match = pmatch(pattern, s);
6389 if (quotes && (unsigned char)*loc == CTLESC)
6398 scanright(char *startp, char *rmesc, char *rmescend,
6399 char *pattern, int quotes, int match_at_start)
6401 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6402 int try2optimize = match_at_start;
6408 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6409 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6410 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6412 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6413 * and on each iteration they go back two/one char until they reach the beginning.
6414 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6416 /* TODO: document in what other circumstances we are called. */
6418 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6421 const char *s = loc2;
6422 if (match_at_start) {
6426 match = pmatch(pattern, s);
6427 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6431 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6433 /* Maybe we can optimize this:
6434 * if pattern ends with unescaped *, we can avoid checking
6435 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6436 * it wont match truncated "raw_value_of_" strings too.
6438 unsigned plen = strlen(pattern);
6439 /* Does it end with "*"? */
6440 if (plen != 0 && pattern[--plen] == '*') {
6441 /* "xxxx*" is not escaped */
6442 /* "xxx\*" is escaped */
6443 /* "xx\\*" is not escaped */
6444 /* "x\\\*" is escaped */
6446 while (plen != 0 && pattern[--plen] == '\\')
6449 break; /* ends with unescaped "*" */
6457 esc = esclen(startp, loc);
6468 static void varunset(const char *, const char *, const char *, int) NORETURN;
6470 varunset(const char *end, const char *var, const char *umsg, int varflags)
6476 msg = "parameter not set";
6478 if ((unsigned char)*end == CTLENDVAR) {
6479 if (varflags & VSNUL)
6485 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6489 subevalvar(char *p, char *varname, int strloc, int subtype,
6490 int startloc, int varflags, int flag, struct strlist *var_str_list)
6492 struct nodelist *saveargbackq = argbackq;
6493 int quotes = flag & QUOTES_ESC;
6496 char *rmesc, *rmescend;
6498 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6499 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6500 int amount, resetloc;
6501 IF_ASH_BASH_COMPAT(int workloc;)
6503 char *(*scan)(char*, char*, char*, char*, int, int);
6505 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6506 // p, varname, strloc, subtype, startloc, varflags, quotes);
6508 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6509 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6511 STPUTC('\0', expdest);
6512 argbackq = saveargbackq;
6513 startp = (char *)stackblock() + startloc;
6517 setvar0(varname, startp);
6518 amount = startp - expdest;
6519 STADJUST(amount, expdest);
6523 varunset(p, varname, startp, varflags);
6526 #if ENABLE_ASH_BASH_COMPAT
6528 //TODO: support more general format ${v:EXPR:EXPR},
6529 // where EXPR follows $(()) rules
6530 loc = str = stackblock() + strloc;
6531 /* Read POS in ${var:POS:LEN} */
6532 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6533 len = str - startp - 1;
6535 /* *loc != '\0', guaranteed by parser */
6539 /* Adjust the length by the number of escapes */
6540 for (ptr = startp; ptr < (str - 1); ptr++) {
6541 if ((unsigned char)*ptr == CTLESC) {
6549 if (*loc++ == ':') {
6553 /* Skip POS in ${var:POS:LEN} */
6555 while (*loc && *loc != ':') {
6557 * bash complains on: var=qwe; echo ${var:1a:123}
6559 ash_msg_and_raise_error(msg_illnum, str);
6563 if (*loc++ == ':') {
6568 /* ${VAR:$((-n)):l} starts n chars from the end */
6569 pos = orig_len + pos;
6571 if ((unsigned)pos >= orig_len) {
6572 /* apart from obvious ${VAR:999999:l},
6573 * covers ${VAR:$((-9999999)):l} - result is ""
6579 if (len > (orig_len - pos))
6580 len = orig_len - pos;
6582 for (str = startp; pos; str++, pos--) {
6583 if (quotes && (unsigned char)*str == CTLESC)
6586 for (loc = startp; len; len--) {
6587 if (quotes && (unsigned char)*str == CTLESC)
6592 amount = loc - expdest;
6593 STADJUST(amount, expdest);
6598 resetloc = expdest - (char *)stackblock();
6600 /* We'll comeback here if we grow the stack while handling
6601 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6602 * stack will need rebasing, and we'll need to remove our work
6605 IF_ASH_BASH_COMPAT(restart:)
6607 amount = expdest - ((char *)stackblock() + resetloc);
6608 STADJUST(-amount, expdest);
6609 startp = (char *)stackblock() + startloc;
6612 rmescend = (char *)stackblock() + strloc;
6614 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6615 if (rmesc != startp) {
6617 startp = (char *)stackblock() + startloc;
6621 str = (char *)stackblock() + strloc;
6623 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6624 * The result is a_\_z_c (not a\_\_z_c)!
6626 * The search pattern and replace string treat backslashes differently!
6627 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6628 * and string. It's only used on the first call.
6630 preglob(str, IF_ASH_BASH_COMPAT(
6631 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6632 RMESCAPE_SLASH :) 0);
6634 #if ENABLE_ASH_BASH_COMPAT
6635 workloc = expdest - (char *)stackblock();
6636 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6640 repl = strchr(str, CTLESC);
6646 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6648 /* If there's no pattern to match, return the expansion unmolested */
6657 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6658 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6660 /* No match, advance */
6661 char *restart_detect = stackblock();
6663 STPUTC(*idx, expdest);
6664 if (quotes && (unsigned char)*idx == CTLESC) {
6667 STPUTC(*idx, expdest);
6669 if (stackblock() != restart_detect)
6674 /* continue; - prone to quadratic behavior, smarter code: */
6677 if (str[0] == '*') {
6678 /* Pattern is "*foo". If "*foo" does not match "long_string",
6679 * it would never match "ong_string" etc, no point in trying.
6686 if (subtype == VSREPLACEALL) {
6688 if (quotes && (unsigned char)*idx == CTLESC)
6697 //bb_error_msg("repl:'%s'", repl);
6698 for (loc = (char*)repl; *loc; loc++) {
6699 char *restart_detect = stackblock();
6700 if (quotes && *loc == '\\') {
6701 STPUTC(CTLESC, expdest);
6704 STPUTC(*loc, expdest);
6705 if (stackblock() != restart_detect)
6710 if (subtype == VSREPLACE) {
6711 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6713 char *restart_detect = stackblock();
6714 STPUTC(*idx, expdest);
6715 if (stackblock() != restart_detect)
6724 /* We've put the replaced text into a buffer at workloc, now
6725 * move it to the right place and adjust the stack.
6727 STPUTC('\0', expdest);
6728 startp = (char *)stackblock() + startloc;
6729 memmove(startp, (char *)stackblock() + workloc, len + 1);
6730 //bb_error_msg("startp:'%s'", startp);
6731 amount = expdest - (startp + len);
6732 STADJUST(-amount, expdest);
6735 #endif /* ENABLE_ASH_BASH_COMPAT */
6737 subtype -= VSTRIMRIGHT;
6739 if (subtype < 0 || subtype > 7)
6742 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6743 zero = subtype >> 1;
6744 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6745 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6747 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6750 memmove(startp, loc, str - loc);
6751 loc = startp + (str - loc) - 1;
6754 amount = loc - expdest;
6755 STADJUST(amount, expdest);
6761 * Add the value of a specialized variable to the stack string.
6762 * name parameter (examples):
6763 * ash -c 'echo $1' name:'1='
6764 * ash -c 'echo $qwe' name:'qwe='
6765 * ash -c 'echo $$' name:'$='
6766 * ash -c 'echo ${$}' name:'$='
6767 * ash -c 'echo ${$##q}' name:'$=q'
6768 * ash -c 'echo ${#$}' name:'$='
6769 * note: examples with bad shell syntax:
6770 * ash -c 'echo ${#$1}' name:'$=1'
6771 * ash -c 'echo ${#1#}' name:'1=#'
6773 static NOINLINE ssize_t
6774 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6781 int quoted = *quotedp;
6782 int subtype = varflags & VSTYPE;
6783 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6784 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6787 sep = (flags & EXP_FULL) << CHAR_BIT;
6788 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6798 num = shellparam.nparam;
6806 goto check_1char_name;
6808 expdest = makestrspace(NOPTS, expdest);
6809 for (i = NOPTS - 1; i >= 0; i--) {
6811 USTPUTC(optletters(i), expdest);
6817 /* handles cases similar to ${#$1} */
6818 if (name[2] != '\0')
6819 raise_error_syntax("bad substitution");
6832 sep |= ifsset() ? ifsval()[0] : ' ';
6839 while ((p = *ap++) != NULL) {
6840 len += strtodest(p, syntax, quotes);
6844 memtodest(&sepc, 1, syntax, quotes);
6859 num = atoi(name); /* number(name) fails on ${N#str} etc */
6860 if (num < 0 || num > shellparam.nparam)
6862 p = num ? shellparam.p[num - 1] : arg0;
6865 /* NB: name has form "VAR=..." */
6867 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6868 * which should be considered before we check variables. */
6870 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6874 str = var_str_list->text;
6875 eq = strchr(str, '=');
6876 if (!eq) /* stop at first non-assignment */
6879 if (name_len == (unsigned)(eq - str)
6880 && strncmp(str, name, name_len) == 0
6883 /* goto value; - WRONG! */
6884 /* think "A=1 A=2 B=$A" */
6886 var_str_list = var_str_list->next;
6887 } while (var_str_list);
6891 p = lookupvar(name);
6896 len = strtodest(p, syntax, quotes);
6897 #if ENABLE_UNICODE_SUPPORT
6898 if (subtype == VSLENGTH && len > 0) {
6899 reinit_unicode_for_ash();
6900 if (unicode_status == UNICODE_ON) {
6901 STADJUST(-len, expdest);
6903 len = unicode_strlen(p);
6911 STADJUST(-len, expdest);
6916 * Expand a variable, and return a pointer to the next character in the
6920 evalvar(char *p, int flag, struct strlist *var_str_list)
6931 varflags = (unsigned char) *p++;
6932 subtype = varflags & VSTYPE;
6935 raise_error_syntax("bad substitution");
6937 quoted = flag & EXP_QUOTED;
6939 easy = (!quoted || (*var == '@' && shellparam.nparam));
6940 startloc = expdest - (char *)stackblock();
6941 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6944 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6945 if (varflags & VSNUL)
6948 if (subtype == VSPLUS) {
6949 varlen = -1 - varlen;
6953 if (subtype == VSMINUS) {
6958 flag | EXP_TILDE | EXP_WORD,
6966 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6970 subevalvar(p, var, 0, subtype, startloc, varflags,
6971 flag & ~QUOTES_ESC, var_str_list);
6974 * Remove any recorded regions beyond
6977 removerecordregions(startloc);
6981 if (varlen < 0 && uflag)
6982 varunset(p, var, 0, 0);
6984 if (subtype == VSLENGTH) {
6985 cvtnum(varlen > 0 ? varlen : 0);
6989 if (subtype == VSNORMAL) {
6993 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7002 case VSTRIMRIGHTMAX:
7003 #if ENABLE_ASH_BASH_COMPAT
7016 * Terminate the string and start recording the pattern
7019 STPUTC('\0', expdest);
7020 patloc = expdest - (char *)stackblock();
7021 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7022 startloc, varflags, flag, var_str_list)) {
7023 int amount = expdest - (
7024 (char *)stackblock() + patloc - 1
7026 STADJUST(-amount, expdest);
7028 /* Remove any recorded regions beyond start of variable */
7029 removerecordregions(startloc);
7034 if (subtype != VSNORMAL) { /* skip to end of alternative */
7037 unsigned char c = *p++;
7040 else if (c == CTLBACKQ) {
7042 argbackq = argbackq->next;
7043 } else if (c == CTLVAR) {
7044 if ((*p++ & VSTYPE) != VSNORMAL)
7046 } else if (c == CTLENDVAR) {
7056 * Add a file name to the list.
7059 addfname(const char *name)
7063 sp = stzalloc(sizeof(*sp));
7064 sp->text = sstrdup(name);
7066 exparg.lastp = &sp->next;
7069 /* If we want to use glob() from libc... */
7070 #if !ENABLE_ASH_INTERNAL_GLOB
7072 /* Add the result of glob() to the list */
7074 addglob(const glob_t *pglob)
7076 char **p = pglob->gl_pathv;
7083 expandmeta(struct strlist *str /*, int flag*/)
7085 /* TODO - EXP_REDIR */
7095 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7110 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7111 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7112 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7114 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7115 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7116 // Which means you need to unescape the string, right? Not so fast:
7117 // if there _is_ a file named "file\?" (with backslash), it is returned
7118 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7119 // You DONT KNOW by looking at the result whether you need to unescape it.
7121 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7122 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7123 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7124 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7125 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7126 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7127 i = glob(p, 0, NULL, &pglob);
7128 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7133 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7134 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7135 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7147 *exparg.lastp = str;
7148 rmescapes(str->text, 0);
7149 exparg.lastp = &str->next;
7151 default: /* GLOB_NOSPACE */
7154 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7161 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7164 * Do metacharacter (i.e. *, ?, [...]) expansion.
7167 expmeta(char *expdir, char *enddir, char *name)
7183 for (p = name; esc = 0, *p; p += esc + 1) {
7184 if (*p == '*' || *p == '?')
7186 else if (*p == '[') {
7193 if (*q == '/' || *q == '\0')
7203 if (p[esc] == '/') {
7206 start = p + esc + 1;
7210 if (metaflag == 0) { /* we've reached the end of the file name */
7211 if (enddir != expdir)
7219 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7230 } while (p < start);
7232 if (enddir == expdir) {
7234 } else if (enddir == expdir + 1 && *expdir == '/') {
7243 if (enddir != expdir)
7245 if (*endname == 0) {
7258 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7259 if (dp->d_name[0] == '.' && !matchdot)
7261 if (pmatch(start, dp->d_name)) {
7263 strcpy(enddir, dp->d_name);
7266 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7269 expmeta(expdir, p, endname);
7275 endname[-esc - 1] = esc ? '\\' : '/';
7278 static struct strlist *
7279 msort(struct strlist *list, int len)
7281 struct strlist *p, *q = NULL;
7282 struct strlist **lpp;
7290 for (n = half; --n >= 0;) {
7294 q->next = NULL; /* terminate first half of list */
7295 q = msort(list, half); /* sort first half of list */
7296 p = msort(p, len - half); /* sort second half */
7299 #if ENABLE_LOCALE_SUPPORT
7300 if (strcoll(p->text, q->text) < 0)
7302 if (strcmp(p->text, q->text) < 0)
7326 * Sort the results of file name expansion. It calculates the number of
7327 * strings to sort and then calls msort (short for merge sort) to do the
7330 static struct strlist *
7331 expsort(struct strlist *str)
7337 for (sp = str; sp; sp = sp->next)
7339 return msort(str, len);
7343 expandmeta(struct strlist *str /*, int flag*/)
7345 static const char metachars[] ALIGN1 = {
7348 /* TODO - EXP_REDIR */
7352 struct strlist **savelastp;
7358 if (!strpbrk(str->text, metachars))
7360 savelastp = exparg.lastp;
7363 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7365 int i = strlen(str->text);
7366 //BUGGY estimation of how long expanded name can be
7367 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7369 expmeta(expdir, expdir, p);
7374 if (exparg.lastp == savelastp) {
7379 *exparg.lastp = str;
7380 rmescapes(str->text, 0);
7381 exparg.lastp = &str->next;
7383 *exparg.lastp = NULL;
7384 *savelastp = sp = expsort(*savelastp);
7385 while (sp->next != NULL)
7387 exparg.lastp = &sp->next;
7392 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7395 * Perform variable substitution and command substitution on an argument,
7396 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7397 * perform splitting and file name expansion. When arglist is NULL, perform
7398 * here document expansion.
7401 expandarg(union node *arg, struct arglist *arglist, int flag)
7406 argbackq = arg->narg.backquote;
7407 STARTSTACKSTR(expdest);
7408 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7409 argstr(arg->narg.text, flag,
7410 /* var_str_list: */ arglist ? arglist->list : NULL);
7411 p = _STPUTC('\0', expdest);
7413 if (arglist == NULL) {
7414 /* here document expanded */
7417 p = grabstackstr(p);
7418 TRACE(("expandarg: p:'%s'\n", p));
7419 exparg.lastp = &exparg.list;
7423 if (flag & EXP_FULL) {
7424 ifsbreakup(p, &exparg);
7425 *exparg.lastp = NULL;
7426 exparg.lastp = &exparg.list;
7427 expandmeta(exparg.list /*, flag*/);
7429 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7431 TRACE(("expandarg: rmescapes:'%s'\n", p));
7433 sp = stzalloc(sizeof(*sp));
7436 exparg.lastp = &sp->next;
7438 *exparg.lastp = NULL;
7440 *arglist->lastp = exparg.list;
7441 arglist->lastp = exparg.lastp;
7449 * Expand shell variables and backquotes inside a here document.
7452 expandhere(union node *arg, int fd)
7454 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7455 full_write(fd, stackblock(), expdest - (char *)stackblock());
7459 * Returns true if the pattern matches the string.
7462 patmatch(char *pattern, const char *string)
7464 return pmatch(preglob(pattern, 0), string);
7468 * See if a pattern matches in a case statement.
7471 casematch(union node *pattern, char *val)
7473 struct stackmark smark;
7476 setstackmark(&smark);
7477 argbackq = pattern->narg.backquote;
7478 STARTSTACKSTR(expdest);
7479 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7480 /* var_str_list: */ NULL);
7481 STACKSTRNUL(expdest);
7483 result = patmatch(stackblock(), val);
7484 popstackmark(&smark);
7489 /* ============ find_command */
7493 int (*builtin)(int, char **) FAST_FUNC;
7494 /* unsigned flags; */
7496 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7497 /* "regular" builtins always take precedence over commands,
7498 * regardless of PATH=....%builtin... position */
7499 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7500 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7503 smallint cmdtype; /* CMDxxx */
7506 /* index >= 0 for commands without path (slashes) */
7507 /* (TODO: what exactly does the value mean? PATH position?) */
7508 /* index == -1 for commands with slashes */
7509 /* index == (-2 - applet_no) for NOFORK applets */
7510 const struct builtincmd *cmd;
7511 struct funcnode *func;
7514 /* values of cmdtype */
7515 #define CMDUNKNOWN -1 /* no entry in table for command */
7516 #define CMDNORMAL 0 /* command is an executable program */
7517 #define CMDFUNCTION 1 /* command is a shell function */
7518 #define CMDBUILTIN 2 /* command is a shell builtin */
7520 /* action to find_command() */
7521 #define DO_ERR 0x01 /* prints errors */
7522 #define DO_ABS 0x02 /* checks absolute paths */
7523 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7524 #define DO_ALTPATH 0x08 /* using alternate path */
7525 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7527 static void find_command(char *, struct cmdentry *, int, const char *);
7530 /* ============ Hashing commands */
7533 * When commands are first encountered, they are entered in a hash table.
7534 * This ensures that a full path search will not have to be done for them
7535 * on each invocation.
7537 * We should investigate converting to a linear search, even though that
7538 * would make the command name "hash" a misnomer.
7542 struct tblentry *next; /* next entry in hash chain */
7543 union param param; /* definition of builtin function */
7544 smallint cmdtype; /* CMDxxx */
7545 char rehash; /* if set, cd done since entry created */
7546 char cmdname[1]; /* name of command */
7549 static struct tblentry **cmdtable;
7550 #define INIT_G_cmdtable() do { \
7551 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7554 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7558 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7560 #if ENABLE_FEATURE_SH_STANDALONE
7561 if (applet_no >= 0) {
7562 if (APPLET_IS_NOEXEC(applet_no)) {
7566 run_applet_no_and_exit(applet_no, argv);
7568 /* re-exec ourselves with the new arguments */
7569 execve(bb_busybox_exec_path, argv, envp);
7570 /* If they called chroot or otherwise made the binary no longer
7571 * executable, fall through */
7578 execve(cmd, argv, envp);
7579 } while (errno == EINTR);
7581 execve(cmd, argv, envp);
7583 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7584 /* Run "cmd" as a shell script:
7585 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7586 * "If the execve() function fails with ENOEXEC, the shell
7587 * shall execute a command equivalent to having a shell invoked
7588 * with the command name as its first operand,
7589 * with any remaining arguments passed to the new shell"
7591 * That is, do not use $SHELL, user's shell, or /bin/sh;
7592 * just call ourselves.
7594 * Note that bash reads ~80 chars of the file, and if it sees
7595 * a zero byte before it sees newline, it doesn't try to
7596 * interpret it, but fails with "cannot execute binary file"
7597 * message and exit code 126. For one, this prevents attempts
7598 * to interpret foreign ELF binaries as shell scripts.
7601 cmd = (char*) bb_busybox_exec_path;
7602 /* NB: this is only possible because all callers of shellexec()
7603 * ensure that the argv[-1] slot exists!
7606 argv[0] = (char*) "ash";
7612 * Exec a program. Never returns. If you change this routine, you may
7613 * have to change the find_command routine as well.
7614 * argv[-1] must exist and be writable! See tryexec() for why.
7616 static void shellexec(char **, const char *, int) NORETURN;
7618 shellexec(char **argv, const char *path, int idx)
7624 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7626 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7627 if (strchr(argv[0], '/') != NULL
7628 #if ENABLE_FEATURE_SH_STANDALONE
7629 || (applet_no = find_applet_by_name(argv[0])) >= 0
7632 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7633 if (applet_no >= 0) {
7634 /* We tried execing ourself, but it didn't work.
7635 * Maybe /proc/self/exe doesn't exist?
7644 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7645 if (--idx < 0 && pathopt == NULL) {
7646 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7647 if (errno != ENOENT && errno != ENOTDIR)
7654 /* Map to POSIX errors */
7666 exitstatus = exerrno;
7667 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7668 argv[0], e, suppress_int));
7669 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7674 printentry(struct tblentry *cmdp)
7680 idx = cmdp->param.index;
7683 name = path_advance(&path, cmdp->cmdname);
7685 } while (--idx >= 0);
7686 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7690 * Clear out command entries. The argument specifies the first entry in
7691 * PATH which has changed.
7694 clearcmdentry(int firstchange)
7696 struct tblentry **tblp;
7697 struct tblentry **pp;
7698 struct tblentry *cmdp;
7701 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7703 while ((cmdp = *pp) != NULL) {
7704 if ((cmdp->cmdtype == CMDNORMAL &&
7705 cmdp->param.index >= firstchange)
7706 || (cmdp->cmdtype == CMDBUILTIN &&
7707 builtinloc >= firstchange)
7720 * Locate a command in the command hash table. If "add" is nonzero,
7721 * add the command to the table if it is not already present. The
7722 * variable "lastcmdentry" is set to point to the address of the link
7723 * pointing to the entry, so that delete_cmd_entry can delete the
7726 * Interrupts must be off if called with add != 0.
7728 static struct tblentry **lastcmdentry;
7730 static struct tblentry *
7731 cmdlookup(const char *name, int add)
7733 unsigned int hashval;
7735 struct tblentry *cmdp;
7736 struct tblentry **pp;
7739 hashval = (unsigned char)*p << 4;
7741 hashval += (unsigned char)*p++;
7743 pp = &cmdtable[hashval % CMDTABLESIZE];
7744 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7745 if (strcmp(cmdp->cmdname, name) == 0)
7749 if (add && cmdp == NULL) {
7750 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7752 /* + 1 - already done because
7753 * tblentry::cmdname is char[1] */);
7754 /*cmdp->next = NULL; - ckzalloc did it */
7755 cmdp->cmdtype = CMDUNKNOWN;
7756 strcpy(cmdp->cmdname, name);
7763 * Delete the command entry returned on the last lookup.
7766 delete_cmd_entry(void)
7768 struct tblentry *cmdp;
7771 cmdp = *lastcmdentry;
7772 *lastcmdentry = cmdp->next;
7773 if (cmdp->cmdtype == CMDFUNCTION)
7774 freefunc(cmdp->param.func);
7780 * Add a new command entry, replacing any existing command entry for
7781 * the same name - except special builtins.
7784 addcmdentry(char *name, struct cmdentry *entry)
7786 struct tblentry *cmdp;
7788 cmdp = cmdlookup(name, 1);
7789 if (cmdp->cmdtype == CMDFUNCTION) {
7790 freefunc(cmdp->param.func);
7792 cmdp->cmdtype = entry->cmdtype;
7793 cmdp->param = entry->u;
7797 static int FAST_FUNC
7798 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7800 struct tblentry **pp;
7801 struct tblentry *cmdp;
7803 struct cmdentry entry;
7806 if (nextopt("r") != '\0') {
7811 if (*argptr == NULL) {
7812 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7813 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7814 if (cmdp->cmdtype == CMDNORMAL)
7822 while ((name = *argptr) != NULL) {
7823 cmdp = cmdlookup(name, 0);
7825 && (cmdp->cmdtype == CMDNORMAL
7826 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7830 find_command(name, &entry, DO_ERR, pathval());
7831 if (entry.cmdtype == CMDUNKNOWN)
7839 * Called when a cd is done. Marks all commands so the next time they
7840 * are executed they will be rehashed.
7845 struct tblentry **pp;
7846 struct tblentry *cmdp;
7848 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7849 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7850 if (cmdp->cmdtype == CMDNORMAL
7851 || (cmdp->cmdtype == CMDBUILTIN
7852 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7862 * Fix command hash table when PATH changed.
7863 * Called before PATH is changed. The argument is the new value of PATH;
7864 * pathval() still returns the old value at this point.
7865 * Called with interrupts off.
7867 static void FAST_FUNC
7868 changepath(const char *new)
7876 firstchange = 9999; /* assume no change */
7882 if ((*old == '\0' && *new == ':')
7883 || (*old == ':' && *new == '\0')
7887 old = new; /* ignore subsequent differences */
7891 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7898 if (builtinloc < 0 && idx_bltin >= 0)
7899 builtinloc = idx_bltin; /* zap builtins */
7900 if (builtinloc >= 0 && idx_bltin < 0)
7902 clearcmdentry(firstchange);
7903 builtinloc = idx_bltin;
7928 #if ENABLE_ASH_BASH_COMPAT
7939 typedef smallint token_id_t;
7941 /* Nth bit indicates if token marks the end of a list */
7944 /* 0 */ | (1u << TEOF)
7945 /* 1 */ | (0u << TNL)
7946 /* 2 */ | (0u << TREDIR)
7947 /* 3 */ | (0u << TWORD)
7948 /* 4 */ | (0u << TSEMI)
7949 /* 5 */ | (0u << TBACKGND)
7950 /* 6 */ | (0u << TAND)
7951 /* 7 */ | (0u << TOR)
7952 /* 8 */ | (0u << TPIPE)
7953 /* 9 */ | (0u << TLP)
7954 /* 10 */ | (1u << TRP)
7955 /* 11 */ | (1u << TENDCASE)
7956 /* 12 */ | (1u << TENDBQUOTE)
7957 /* 13 */ | (0u << TNOT)
7958 /* 14 */ | (0u << TCASE)
7959 /* 15 */ | (1u << TDO)
7960 /* 16 */ | (1u << TDONE)
7961 /* 17 */ | (1u << TELIF)
7962 /* 18 */ | (1u << TELSE)
7963 /* 19 */ | (1u << TESAC)
7964 /* 20 */ | (1u << TFI)
7965 /* 21 */ | (0u << TFOR)
7966 #if ENABLE_ASH_BASH_COMPAT
7967 /* 22 */ | (0u << TFUNCTION)
7969 /* 23 */ | (0u << TIF)
7970 /* 24 */ | (0u << TIN)
7971 /* 25 */ | (1u << TTHEN)
7972 /* 26 */ | (0u << TUNTIL)
7973 /* 27 */ | (0u << TWHILE)
7974 /* 28 */ | (0u << TBEGIN)
7975 /* 29 */ | (1u << TEND)
7976 , /* thus far 29 bits used */
7979 static const char *const tokname_array[] = {
7993 #define KWDOFFSET 13
7994 /* the following are keywords */
8004 #if ENABLE_ASH_BASH_COMPAT
8016 /* Wrapper around strcmp for qsort/bsearch/... */
8018 pstrcmp(const void *a, const void *b)
8020 return strcmp((char*)a, *(char**)b);
8023 static const char *const *
8024 findkwd(const char *s)
8026 return bsearch(s, tokname_array + KWDOFFSET,
8027 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8028 sizeof(tokname_array[0]), pstrcmp);
8032 * Locate and print what a word is...
8035 describe_command(char *command, const char *path, int describe_command_verbose)
8037 struct cmdentry entry;
8038 struct tblentry *cmdp;
8039 #if ENABLE_ASH_ALIAS
8040 const struct alias *ap;
8043 path = path ? path : pathval();
8045 if (describe_command_verbose) {
8049 /* First look at the keywords */
8050 if (findkwd(command)) {
8051 out1str(describe_command_verbose ? " is a shell keyword" : command);
8055 #if ENABLE_ASH_ALIAS
8056 /* Then look at the aliases */
8057 ap = lookupalias(command, 0);
8059 if (!describe_command_verbose) {
8064 out1fmt(" is an alias for %s", ap->val);
8068 /* Then check if it is a tracked alias */
8069 cmdp = cmdlookup(command, 0);
8071 entry.cmdtype = cmdp->cmdtype;
8072 entry.u = cmdp->param;
8074 /* Finally use brute force */
8075 find_command(command, &entry, DO_ABS, path);
8078 switch (entry.cmdtype) {
8080 int j = entry.u.index;
8086 p = path_advance(&path, command);
8090 if (describe_command_verbose) {
8092 (cmdp ? " a tracked alias for" : nullstr), p
8101 if (describe_command_verbose) {
8102 out1str(" is a shell function");
8109 if (describe_command_verbose) {
8110 out1fmt(" is a %sshell builtin",
8111 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8112 "special " : nullstr
8120 if (describe_command_verbose) {
8121 out1str(": not found\n");
8130 static int FAST_FUNC
8131 typecmd(int argc UNUSED_PARAM, char **argv)
8137 /* type -p ... ? (we don't bother checking for 'p') */
8138 if (argv[1] && argv[1][0] == '-') {
8143 err |= describe_command(argv[i++], NULL, verbose);
8148 #if ENABLE_ASH_CMDCMD
8149 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8151 parse_command_args(char **argv, const char **path)
8164 if (c == '-' && !*cp) {
8172 *path = bb_default_path;
8175 /* run 'typecmd' for other options */
8184 static int FAST_FUNC
8185 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8193 const char *path = NULL;
8195 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8196 * never reaches this function.
8199 while ((c = nextopt("pvV")) != '\0')
8201 verify |= VERIFY_VERBOSE;
8203 /*verify |= VERIFY_BRIEF*/;
8209 path = bb_default_path;
8211 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8213 if (/*verify && */ cmd)
8214 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8221 /*static int funcblocksize; // size of structures in function */
8222 /*static int funcstringsize; // size of strings in node */
8223 static void *funcblock; /* block to allocate function from */
8224 static char *funcstring_end; /* end of block to allocate strings from */
8226 /* flags in argument to evaltree */
8227 #define EV_EXIT 01 /* exit after evaluating tree */
8228 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8230 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8231 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8232 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8233 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8234 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8235 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8236 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8237 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8238 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8239 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8240 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8241 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8242 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8243 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8244 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8245 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8246 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8247 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8248 #if ENABLE_ASH_BASH_COMPAT
8249 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8251 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8252 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8253 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8254 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8255 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8256 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8257 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8258 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8259 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8262 static int calcsize(int funcblocksize, union node *n);
8265 sizenodelist(int funcblocksize, struct nodelist *lp)
8268 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8269 funcblocksize = calcsize(funcblocksize, lp->n);
8272 return funcblocksize;
8276 calcsize(int funcblocksize, union node *n)
8279 return funcblocksize;
8280 funcblocksize += nodesize[n->type];
8283 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8284 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8285 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8288 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8293 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8294 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8301 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8302 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8305 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8306 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8307 funcblocksize = calcsize(funcblocksize, n->nif.test);
8310 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8311 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8312 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8315 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8316 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8319 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8320 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8321 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8325 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8326 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8327 funcblocksize = calcsize(funcblocksize, n->narg.next);
8330 #if ENABLE_ASH_BASH_COMPAT
8337 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8338 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8342 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8343 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8347 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8348 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8351 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8354 return funcblocksize;
8358 nodeckstrdup(char *s)
8360 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8361 return strcpy(funcstring_end, s);
8364 static union node *copynode(union node *);
8366 static struct nodelist *
8367 copynodelist(struct nodelist *lp)
8369 struct nodelist *start;
8370 struct nodelist **lpp;
8375 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8376 (*lpp)->n = copynode(lp->n);
8378 lpp = &(*lpp)->next;
8385 copynode(union node *n)
8392 funcblock = (char *) funcblock + nodesize[n->type];
8396 new->ncmd.redirect = copynode(n->ncmd.redirect);
8397 new->ncmd.args = copynode(n->ncmd.args);
8398 new->ncmd.assign = copynode(n->ncmd.assign);
8401 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8402 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8407 new->nredir.redirect = copynode(n->nredir.redirect);
8408 new->nredir.n = copynode(n->nredir.n);
8415 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8416 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8419 new->nif.elsepart = copynode(n->nif.elsepart);
8420 new->nif.ifpart = copynode(n->nif.ifpart);
8421 new->nif.test = copynode(n->nif.test);
8424 new->nfor.var = nodeckstrdup(n->nfor.var);
8425 new->nfor.body = copynode(n->nfor.body);
8426 new->nfor.args = copynode(n->nfor.args);
8429 new->ncase.cases = copynode(n->ncase.cases);
8430 new->ncase.expr = copynode(n->ncase.expr);
8433 new->nclist.body = copynode(n->nclist.body);
8434 new->nclist.pattern = copynode(n->nclist.pattern);
8435 new->nclist.next = copynode(n->nclist.next);
8439 new->narg.backquote = copynodelist(n->narg.backquote);
8440 new->narg.text = nodeckstrdup(n->narg.text);
8441 new->narg.next = copynode(n->narg.next);
8444 #if ENABLE_ASH_BASH_COMPAT
8451 new->nfile.fname = copynode(n->nfile.fname);
8452 new->nfile.fd = n->nfile.fd;
8453 new->nfile.next = copynode(n->nfile.next);
8457 new->ndup.vname = copynode(n->ndup.vname);
8458 new->ndup.dupfd = n->ndup.dupfd;
8459 new->ndup.fd = n->ndup.fd;
8460 new->ndup.next = copynode(n->ndup.next);
8464 new->nhere.doc = copynode(n->nhere.doc);
8465 new->nhere.fd = n->nhere.fd;
8466 new->nhere.next = copynode(n->nhere.next);
8469 new->nnot.com = copynode(n->nnot.com);
8472 new->type = n->type;
8477 * Make a copy of a parse tree.
8479 static struct funcnode *
8480 copyfunc(union node *n)
8485 /*funcstringsize = 0;*/
8486 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8487 f = ckzalloc(blocksize /* + funcstringsize */);
8488 funcblock = (char *) f + offsetof(struct funcnode, n);
8489 funcstring_end = (char *) f + blocksize;
8491 /* f->count = 0; - ckzalloc did it */
8496 * Define a shell function.
8499 defun(union node *func)
8501 struct cmdentry entry;
8504 entry.cmdtype = CMDFUNCTION;
8505 entry.u.func = copyfunc(func);
8506 addcmdentry(func->narg.text, &entry);
8510 /* Reasons for skipping commands (see comment on breakcmd routine) */
8511 #define SKIPBREAK (1 << 0)
8512 #define SKIPCONT (1 << 1)
8513 #define SKIPFUNC (1 << 2)
8514 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8515 static int skipcount; /* number of levels to skip */
8516 static int funcnest; /* depth of function calls */
8517 static int loopnest; /* current loop nesting level */
8519 /* Forward decl way out to parsing code - dotrap needs it */
8520 static int evalstring(char *s, int flags);
8522 /* Called to execute a trap.
8523 * Single callsite - at the end of evaltree().
8524 * If we return non-zero, evaltree raises EXEXIT exception.
8526 * Perhaps we should avoid entering new trap handlers
8527 * while we are executing a trap handler. [is it a TODO?]
8534 uint8_t last_status;
8539 last_status = exitstatus;
8543 TRACE(("dotrap entered\n"));
8544 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8556 /* non-trapped SIGINT is handled separately by raise_interrupt,
8557 * don't upset it by resetting gotsig[SIGINT-1] */
8558 if (sig == SIGINT && !p)
8561 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8567 exitstatus = last_status;
8568 TRACE(("dotrap returns\n"));
8571 /* forward declarations - evaluation is fairly recursive business... */
8572 static int evalloop(union node *, int);
8573 static int evalfor(union node *, int);
8574 static int evalcase(union node *, int);
8575 static int evalsubshell(union node *, int);
8576 static void expredir(union node *);
8577 static int evalpipe(union node *, int);
8578 static int evalcommand(union node *, int);
8579 static int evalbltin(const struct builtincmd *, int, char **, int);
8580 static void prehash(union node *);
8583 * Evaluate a parse tree. The value is left in the global variable
8587 evaltree(union node *n, int flags)
8590 int (*evalfn)(union node *, int);
8594 TRACE(("evaltree(NULL) called\n"));
8597 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8604 out1fmt("Node type = %d\n", n->type);
8609 status = !evaltree(n->nnot.com, EV_TESTED);
8612 expredir(n->nredir.redirect);
8613 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8615 status = evaltree(n->nredir.n, flags & EV_TESTED);
8617 if (n->nredir.redirect)
8618 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8621 evalfn = evalcommand;
8623 if (eflag && !(flags & EV_TESTED))
8635 evalfn = evalsubshell;
8648 #error NAND + 1 != NOR
8650 #if NOR + 1 != NSEMI
8651 #error NOR + 1 != NSEMI
8653 unsigned is_or = n->type - NAND;
8656 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8658 if ((!status) == is_or || evalskip)
8664 status = evalfn(n, flags);
8668 status = evaltree(n->nif.test, EV_TESTED);
8675 if (n->nif.elsepart) {
8676 n = n->nif.elsepart;
8683 /* Not necessary. To test it:
8684 * "false; f() { qwerty; }; echo $?" should print 0.
8688 exitstatus = status;
8692 /* Order of checks below is important:
8693 * signal handlers trigger before exit caused by "set -e".
8697 if (checkexit & status)
8698 raise_exception(EXEXIT);
8699 if (flags & EV_EXIT)
8700 raise_exception(EXEXIT);
8702 TRACE(("leaving evaltree (no interrupts)\n"));
8706 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8709 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8714 int skip = evalskip;
8721 if (--skipcount <= 0) {
8732 evalloop(union node *n, int flags)
8743 i = evaltree(n->nbinary.ch1, EV_TESTED);
8745 if (skip == SKIPFUNC)
8749 if (n->type != NWHILE)
8753 status = evaltree(n->nbinary.ch2, flags);
8755 } while (!(skip & ~SKIPCONT));
8762 evalfor(union node *n, int flags)
8764 struct arglist arglist;
8767 struct stackmark smark;
8770 setstackmark(&smark);
8771 arglist.list = NULL;
8772 arglist.lastp = &arglist.list;
8773 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8774 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8776 *arglist.lastp = NULL;
8780 for (sp = arglist.list; sp; sp = sp->next) {
8781 setvar0(n->nfor.var, sp->text);
8782 status = evaltree(n->nfor.body, flags);
8783 if (skiploop() & ~SKIPCONT)
8787 popstackmark(&smark);
8793 evalcase(union node *n, int flags)
8797 struct arglist arglist;
8798 struct stackmark smark;
8801 setstackmark(&smark);
8802 arglist.list = NULL;
8803 arglist.lastp = &arglist.list;
8804 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8805 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8806 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8807 if (casematch(patp, arglist.list->text)) {
8808 /* Ensure body is non-empty as otherwise
8809 * EV_EXIT may prevent us from setting the
8812 if (evalskip == 0 && cp->nclist.body) {
8813 status = evaltree(cp->nclist.body, flags);
8820 popstackmark(&smark);
8826 * Kick off a subshell to evaluate a tree.
8829 evalsubshell(union node *n, int flags)
8832 int backgnd = (n->type == NBACKGND);
8835 expredir(n->nredir.redirect);
8836 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8839 jp = makejob(/*n,*/ 1);
8840 if (forkshell(jp, n, backgnd) == 0) {
8845 flags &= ~EV_TESTED;
8847 redirect(n->nredir.redirect, 0);
8848 evaltreenr(n->nredir.n, flags);
8854 status = waitforjob(jp);
8860 * Compute the names of the files in a redirection list.
8862 static void fixredir(union node *, const char *, int);
8864 expredir(union node *n)
8868 for (redir = n; redir; redir = redir->nfile.next) {
8872 fn.lastp = &fn.list;
8873 switch (redir->type) {
8877 #if ENABLE_ASH_BASH_COMPAT
8882 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8883 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8884 #if ENABLE_ASH_BASH_COMPAT
8888 // By the design of stack allocator, the loop of this kind:
8889 // while true; do while true; do break; done </dev/null; done
8890 // will look like a memory leak: ash plans to free expfname's
8891 // of "/dev/null" as soon as it finishes running the loop
8892 // (in this case, never).
8893 // This "fix" is wrong:
8894 if (redir->nfile.expfname)
8895 stunalloc(redir->nfile.expfname);
8896 // It results in corrupted state of stacked allocations.
8898 redir->nfile.expfname = fn.list->text;
8901 case NTOFD: /* >& */
8902 if (redir->ndup.vname) {
8903 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8904 if (fn.list == NULL)
8905 ash_msg_and_raise_error("redir error");
8906 #if ENABLE_ASH_BASH_COMPAT
8907 //FIXME: we used expandarg with different args!
8908 if (!isdigit_str9(fn.list->text)) {
8909 /* >&file, not >&fd */
8910 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8911 ash_msg_and_raise_error("redir error");
8913 goto store_expfname;
8916 fixredir(redir, fn.list->text, 1);
8924 * Evaluate a pipeline. All the processes in the pipeline are children
8925 * of the process creating the pipeline. (This differs from some versions
8926 * of the shell, which make the last process in a pipeline the parent
8930 evalpipe(union node *n, int flags)
8933 struct nodelist *lp;
8939 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8941 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8945 jp = makejob(/*n,*/ pipelen);
8947 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8951 if (pipe(pip) < 0) {
8953 ash_msg_and_raise_error("pipe call failed");
8956 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8970 evaltreenr(lp->n, flags);
8977 /* Don't want to trigger debugging */
8981 if (n->npipe.pipe_backgnd == 0) {
8982 status = waitforjob(jp);
8983 TRACE(("evalpipe: job done exit status %d\n", status));
8991 * Controls whether the shell is interactive or not.
8994 setinteractive(int on)
8996 static smallint is_interactive;
8998 if (++on == is_interactive)
9000 is_interactive = on;
9004 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9005 if (is_interactive > 1) {
9006 /* Looks like they want an interactive shell */
9007 static smallint did_banner;
9010 /* note: ash and hush share this string */
9011 out1fmt("\n\n%s %s\n"
9012 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9015 "built-in shell (ash)"
9029 setinteractive(iflag);
9031 #if ENABLE_FEATURE_EDITING_VI
9033 line_input_state->flags |= VI_MODE;
9035 line_input_state->flags &= ~VI_MODE;
9037 viflag = 0; /* forcibly keep the option off */
9041 static struct localvar *localvars;
9044 * Called after a function returns.
9045 * Interrupts must be off.
9050 struct localvar *lvp;
9053 while ((lvp = localvars) != NULL) {
9054 localvars = lvp->next;
9056 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9057 if (vp == NULL) { /* $- saved */
9058 memcpy(optlist, lvp->text, sizeof(optlist));
9059 free((char*)lvp->text);
9061 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9062 unsetvar(vp->var_text);
9065 vp->var_func(var_end(lvp->text));
9066 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9067 free((char*)vp->var_text);
9068 vp->flags = lvp->flags;
9069 vp->var_text = lvp->text;
9076 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9078 volatile struct shparam saveparam;
9079 struct localvar *volatile savelocalvars;
9080 struct jmploc *volatile savehandler;
9081 struct jmploc jmploc;
9084 saveparam = shellparam;
9085 savelocalvars = localvars;
9086 savehandler = exception_handler;
9087 e = setjmp(jmploc.loc);
9092 exception_handler = &jmploc;
9094 shellparam.malloced = 0;
9098 shellparam.nparam = argc - 1;
9099 shellparam.p = argv + 1;
9100 #if ENABLE_ASH_GETOPTS
9101 shellparam.optind = 1;
9102 shellparam.optoff = -1;
9104 evaltree(func->n.narg.next, flags & EV_TESTED);
9110 localvars = savelocalvars;
9111 freeparam(&shellparam);
9112 shellparam = saveparam;
9113 exception_handler = savehandler;
9115 evalskip &= ~SKIPFUNC;
9120 * Make a variable a local variable. When a variable is made local, it's
9121 * value and flags are saved in a localvar structure. The saved values
9122 * will be restored when the shell function returns. We handle the name
9123 * "-" as a special case: it makes changes to "set +-options" local
9124 * (options will be restored on return from the function).
9129 struct localvar *lvp;
9132 char *eq = strchr(name, '=');
9135 /* Cater for duplicate "local". Examples:
9136 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9137 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9141 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9145 * it's a duplicate "local VAR" declaration, do nothing
9152 lvp = ckzalloc(sizeof(*lvp));
9153 if (LONE_DASH(name)) {
9155 p = ckmalloc(sizeof(optlist));
9156 lvp->text = memcpy(p, optlist, sizeof(optlist));
9159 vpp = hashvar(name);
9160 vp = *findvar(vpp, name);
9162 /* variable did not exist yet */
9164 setvareq(name, VSTRFIXED);
9166 setvar(name, NULL, VSTRFIXED);
9167 vp = *vpp; /* the new variable */
9168 lvp->flags = VUNSET;
9170 lvp->text = vp->var_text;
9171 lvp->flags = vp->flags;
9172 /* make sure neither "struct var" nor string gets freed
9173 * during (un)setting:
9175 vp->flags |= VSTRFIXED|VTEXTFIXED;
9179 /* "local VAR" unsets VAR: */
9180 setvar0(name, NULL);
9184 lvp->next = localvars;
9191 * The "local" command.
9193 static int FAST_FUNC
9194 localcmd(int argc UNUSED_PARAM, char **argv)
9199 ash_msg_and_raise_error("not in a function");
9202 while ((name = *argv++) != NULL) {
9208 static int FAST_FUNC
9209 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9214 static int FAST_FUNC
9215 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9220 static int FAST_FUNC
9221 execcmd(int argc UNUSED_PARAM, char **argv)
9224 iflag = 0; /* exit on error */
9227 /* We should set up signals for "exec CMD"
9228 * the same way as for "CMD" without "exec".
9229 * But optschanged->setinteractive->setsignal
9230 * still thought we are a root shell. Therefore, for example,
9231 * SIGQUIT is still set to IGN. Fix it:
9235 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9236 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9237 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9239 shellexec(argv + 1, pathval(), 0);
9246 * The return command.
9248 static int FAST_FUNC
9249 returncmd(int argc UNUSED_PARAM, char **argv)
9252 * If called outside a function, do what ksh does;
9253 * skip the rest of the file.
9255 evalskip = SKIPFUNC;
9256 return argv[1] ? number(argv[1]) : exitstatus;
9259 /* Forward declarations for builtintab[] */
9260 static int breakcmd(int, char **) FAST_FUNC;
9261 static int dotcmd(int, char **) FAST_FUNC;
9262 static int evalcmd(int, char **, int) FAST_FUNC;
9263 static int exitcmd(int, char **) FAST_FUNC;
9264 static int exportcmd(int, char **) FAST_FUNC;
9265 #if ENABLE_ASH_GETOPTS
9266 static int getoptscmd(int, char **) FAST_FUNC;
9269 static int helpcmd(int, char **) FAST_FUNC;
9272 static int historycmd(int, char **) FAST_FUNC;
9274 #if ENABLE_FEATURE_SH_MATH
9275 static int letcmd(int, char **) FAST_FUNC;
9277 static int readcmd(int, char **) FAST_FUNC;
9278 static int setcmd(int, char **) FAST_FUNC;
9279 static int shiftcmd(int, char **) FAST_FUNC;
9280 static int timescmd(int, char **) FAST_FUNC;
9281 static int trapcmd(int, char **) FAST_FUNC;
9282 static int umaskcmd(int, char **) FAST_FUNC;
9283 static int unsetcmd(int, char **) FAST_FUNC;
9284 static int ulimitcmd(int, char **) FAST_FUNC;
9286 #define BUILTIN_NOSPEC "0"
9287 #define BUILTIN_SPECIAL "1"
9288 #define BUILTIN_REGULAR "2"
9289 #define BUILTIN_SPEC_REG "3"
9290 #define BUILTIN_ASSIGN "4"
9291 #define BUILTIN_SPEC_ASSG "5"
9292 #define BUILTIN_REG_ASSG "6"
9293 #define BUILTIN_SPEC_REG_ASSG "7"
9295 /* Stubs for calling non-FAST_FUNC's */
9296 #if ENABLE_ASH_BUILTIN_ECHO
9297 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9299 #if ENABLE_ASH_BUILTIN_PRINTF
9300 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9302 #if ENABLE_ASH_BUILTIN_TEST
9303 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9306 /* Keep these in proper order since it is searched via bsearch() */
9307 static const struct builtincmd builtintab[] = {
9308 { BUILTIN_SPEC_REG "." , dotcmd },
9309 { BUILTIN_SPEC_REG ":" , truecmd },
9310 #if ENABLE_ASH_BUILTIN_TEST
9311 { BUILTIN_REGULAR "[" , testcmd },
9312 # if ENABLE_ASH_BASH_COMPAT
9313 { BUILTIN_REGULAR "[[" , testcmd },
9316 #if ENABLE_ASH_ALIAS
9317 { BUILTIN_REG_ASSG "alias" , aliascmd },
9320 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9322 { BUILTIN_SPEC_REG "break" , breakcmd },
9323 { BUILTIN_REGULAR "cd" , cdcmd },
9324 { BUILTIN_NOSPEC "chdir" , cdcmd },
9325 #if ENABLE_ASH_CMDCMD
9326 { BUILTIN_REGULAR "command" , commandcmd },
9328 { BUILTIN_SPEC_REG "continue", breakcmd },
9329 #if ENABLE_ASH_BUILTIN_ECHO
9330 { BUILTIN_REGULAR "echo" , echocmd },
9332 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9333 { BUILTIN_SPEC_REG "exec" , execcmd },
9334 { BUILTIN_SPEC_REG "exit" , exitcmd },
9335 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9336 { BUILTIN_REGULAR "false" , falsecmd },
9338 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9340 #if ENABLE_ASH_GETOPTS
9341 { BUILTIN_REGULAR "getopts" , getoptscmd },
9343 { BUILTIN_NOSPEC "hash" , hashcmd },
9345 { BUILTIN_NOSPEC "help" , helpcmd },
9348 { BUILTIN_NOSPEC "history" , historycmd },
9351 { BUILTIN_REGULAR "jobs" , jobscmd },
9352 { BUILTIN_REGULAR "kill" , killcmd },
9354 #if ENABLE_FEATURE_SH_MATH
9355 { BUILTIN_NOSPEC "let" , letcmd },
9357 { BUILTIN_ASSIGN "local" , localcmd },
9358 #if ENABLE_ASH_BUILTIN_PRINTF
9359 { BUILTIN_REGULAR "printf" , printfcmd },
9361 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9362 { BUILTIN_REGULAR "read" , readcmd },
9363 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9364 { BUILTIN_SPEC_REG "return" , returncmd },
9365 { BUILTIN_SPEC_REG "set" , setcmd },
9366 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9367 #if ENABLE_ASH_BASH_COMPAT
9368 { BUILTIN_SPEC_REG "source" , dotcmd },
9370 #if ENABLE_ASH_BUILTIN_TEST
9371 { BUILTIN_REGULAR "test" , testcmd },
9373 { BUILTIN_SPEC_REG "times" , timescmd },
9374 { BUILTIN_SPEC_REG "trap" , trapcmd },
9375 { BUILTIN_REGULAR "true" , truecmd },
9376 { BUILTIN_NOSPEC "type" , typecmd },
9377 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9378 { BUILTIN_REGULAR "umask" , umaskcmd },
9379 #if ENABLE_ASH_ALIAS
9380 { BUILTIN_REGULAR "unalias" , unaliascmd },
9382 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9383 { BUILTIN_REGULAR "wait" , waitcmd },
9386 /* Should match the above table! */
9387 #define COMMANDCMD (builtintab + \
9389 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9390 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9391 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9392 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9393 /* break cd cddir */ 3)
9394 #define EVALCMD (COMMANDCMD + \
9395 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9396 /* continue */ 1 + \
9397 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9399 #define EXECCMD (EVALCMD + \
9403 * Search the table of builtin commands.
9406 pstrcmp1(const void *a, const void *b)
9408 return strcmp((char*)a, *(char**)b + 1);
9410 static struct builtincmd *
9411 find_builtin(const char *name)
9413 struct builtincmd *bp;
9416 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9423 * Execute a simple command.
9426 isassignment(const char *p)
9428 const char *q = endofname(p);
9433 static int FAST_FUNC
9434 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9436 /* Preserve exitstatus of a previous possible redirection
9437 * as POSIX mandates */
9438 return back_exitstatus;
9441 evalcommand(union node *cmd, int flags)
9443 static const struct builtincmd null_bltin = {
9444 "\0\0", bltincmd /* why three NULs? */
9446 struct stackmark smark;
9448 struct arglist arglist;
9449 struct arglist varlist;
9452 const struct strlist *sp;
9453 struct cmdentry cmdentry;
9460 struct builtincmd *bcmd;
9461 smallint cmd_is_exec;
9462 smallint pseudovarflag = 0;
9464 /* First expand the arguments. */
9465 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9466 setstackmark(&smark);
9467 back_exitstatus = 0;
9469 cmdentry.cmdtype = CMDBUILTIN;
9470 cmdentry.u.cmd = &null_bltin;
9471 varlist.lastp = &varlist.list;
9472 *varlist.lastp = NULL;
9473 arglist.lastp = &arglist.list;
9474 *arglist.lastp = NULL;
9477 if (cmd->ncmd.args) {
9478 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9479 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9482 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9483 struct strlist **spp;
9485 spp = arglist.lastp;
9486 if (pseudovarflag && isassignment(argp->narg.text))
9487 expandarg(argp, &arglist, EXP_VARTILDE);
9489 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9491 for (sp = *spp; sp; sp = sp->next)
9495 /* Reserve one extra spot at the front for shellexec. */
9496 nargv = stalloc(sizeof(char *) * (argc + 2));
9498 for (sp = arglist.list; sp; sp = sp->next) {
9499 TRACE(("evalcommand arg: %s\n", sp->text));
9500 *nargv++ = sp->text;
9505 if (iflag && funcnest == 0 && argc > 0)
9506 lastarg = nargv[-1];
9509 expredir(cmd->ncmd.redirect);
9510 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9512 path = vpath.var_text;
9513 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9514 struct strlist **spp;
9517 spp = varlist.lastp;
9518 expandarg(argp, &varlist, EXP_VARTILDE);
9521 * Modify the command lookup path, if a PATH= assignment
9525 if (varcmp(p, path) == 0)
9529 /* Print the command if xflag is set. */
9532 const char *p = " %s" + 1;
9534 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9536 for (n = 0; n < 2; n++) {
9538 fdprintf(preverrout_fd, p, sp->text);
9544 safe_write(preverrout_fd, "\n", 1);
9550 /* Now locate the command. */
9552 int cmd_flag = DO_ERR;
9553 #if ENABLE_ASH_CMDCMD
9554 const char *oldpath = path + 5;
9558 find_command(argv[0], &cmdentry, cmd_flag, path);
9559 if (cmdentry.cmdtype == CMDUNKNOWN) {
9560 flush_stdout_stderr();
9565 /* implement bltin and command here */
9566 if (cmdentry.cmdtype != CMDBUILTIN)
9569 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9570 if (cmdentry.u.cmd == EXECCMD)
9572 #if ENABLE_ASH_CMDCMD
9573 if (cmdentry.u.cmd == COMMANDCMD) {
9575 nargv = parse_command_args(argv, &path);
9578 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9579 * nargv => "PROG". path is updated if -p.
9581 argc -= nargv - argv;
9583 cmd_flag |= DO_NOFUNC;
9591 /* We have a redirection error. */
9593 raise_exception(EXERROR);
9595 exitstatus = status;
9599 /* Execute the command. */
9600 switch (cmdentry.cmdtype) {
9603 #if ENABLE_FEATURE_SH_NOFORK
9604 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9605 * around run_nofork_applet() call.
9606 * (2) Should this check also be done in forkshell()?
9607 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9609 /* find_command() encodes applet_no as (-2 - applet_no) */
9610 int applet_no = (- cmdentry.u.index - 2);
9611 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9612 listsetvar(varlist.list, VEXPORT|VSTACK);
9613 /* run <applet>_main() */
9614 status = run_nofork_applet(applet_no, argv);
9618 /* Can we avoid forking off? For example, very last command
9619 * in a script or a subshell does not need forking,
9620 * we can just exec it.
9622 if (!(flags & EV_EXIT) || may_have_traps) {
9623 /* No, forking off a child is necessary */
9625 jp = makejob(/*cmd,*/ 1);
9626 if (forkshell(jp, cmd, FORK_FG) != 0) {
9628 status = waitforjob(jp);
9630 TRACE(("forked child exited with %d\n", status));
9635 /* fall through to exec'ing external program */
9637 listsetvar(varlist.list, VEXPORT|VSTACK);
9638 shellexec(argv, path, cmdentry.u.index);
9642 cmdenviron = varlist.list;
9644 struct strlist *list = cmdenviron;
9646 if (spclbltin > 0 || argc == 0) {
9648 if (cmd_is_exec && argc > 1)
9651 listsetvar(list, i);
9653 /* Tight loop with builtins only:
9654 * "while kill -0 $child; do true; done"
9655 * will never exit even if $child died, unless we do this
9656 * to reap the zombie and make kill detect that it's gone: */
9657 dowait(DOWAIT_NONBLOCK, NULL);
9659 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9660 if (exception_type == EXERROR && spclbltin <= 0) {
9665 longjmp(exception_handler->loc, 1);
9670 listsetvar(varlist.list, 0);
9671 /* See above for the rationale */
9672 dowait(DOWAIT_NONBLOCK, NULL);
9673 if (evalfun(cmdentry.u.func, argc, argv, flags))
9676 status = exitstatus;
9681 if (cmd->ncmd.redirect)
9682 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9684 /* dsl: I think this is intended to be used to support
9685 * '_' in 'vi' command mode during line editing...
9686 * However I implemented that within libedit itself.
9688 setvar0("_", lastarg);
9690 popstackmark(&smark);
9696 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9698 char *volatile savecmdname;
9699 struct jmploc *volatile savehandler;
9700 struct jmploc jmploc;
9704 savecmdname = commandname;
9705 savehandler = exception_handler;
9706 i = setjmp(jmploc.loc);
9709 exception_handler = &jmploc;
9710 commandname = argv[0];
9712 optptr = NULL; /* initialize nextopt */
9714 status = evalcmd(argc, argv, flags);
9716 status = (*cmd->builtin)(argc, argv);
9717 flush_stdout_stderr();
9718 status |= ferror(stdout);
9719 exitstatus = status;
9722 commandname = savecmdname;
9723 exception_handler = savehandler;
9729 goodname(const char *p)
9731 return endofname(p)[0] == '\0';
9736 * Search for a command. This is called before we fork so that the
9737 * location of the command will be available in the parent as well as
9738 * the child. The check for "goodname" is an overly conservative
9739 * check that the name will not be subject to expansion.
9742 prehash(union node *n)
9744 struct cmdentry entry;
9746 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9747 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9751 /* ============ Builtin commands
9753 * Builtin commands whose functions are closely tied to evaluation
9754 * are implemented here.
9758 * Handle break and continue commands. Break, continue, and return are
9759 * all handled by setting the evalskip flag. The evaluation routines
9760 * above all check this flag, and if it is set they start skipping
9761 * commands rather than executing them. The variable skipcount is
9762 * the number of loops to break/continue, or the number of function
9763 * levels to return. (The latter is always 1.) It should probably
9764 * be an error to break out of more loops than exist, but it isn't
9765 * in the standard shell so we don't make it one here.
9767 static int FAST_FUNC
9768 breakcmd(int argc UNUSED_PARAM, char **argv)
9770 int n = argv[1] ? number(argv[1]) : 1;
9773 ash_msg_and_raise_error(msg_illnum, argv[1]);
9777 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9785 * This implements the input routines used by the parser.
9789 INPUT_PUSH_FILE = 1,
9790 INPUT_NOFILE_OK = 2,
9793 static smallint checkkwd;
9794 /* values of checkkwd variable */
9795 #define CHKALIAS 0x1
9800 * Push a string back onto the input at this current parsefile level.
9801 * We handle aliases this way.
9803 #if !ENABLE_ASH_ALIAS
9804 #define pushstring(s, ap) pushstring(s)
9807 pushstring(char *s, struct alias *ap)
9814 if (g_parsefile->strpush) {
9815 sp = ckzalloc(sizeof(*sp));
9816 sp->prev = g_parsefile->strpush;
9818 sp = &(g_parsefile->basestrpush);
9820 g_parsefile->strpush = sp;
9821 sp->prev_string = g_parsefile->next_to_pgetc;
9822 sp->prev_left_in_line = g_parsefile->left_in_line;
9823 sp->unget = g_parsefile->unget;
9824 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9825 #if ENABLE_ASH_ALIAS
9828 ap->flag |= ALIASINUSE;
9832 g_parsefile->next_to_pgetc = s;
9833 g_parsefile->left_in_line = len;
9834 g_parsefile->unget = 0;
9841 struct strpush *sp = g_parsefile->strpush;
9844 #if ENABLE_ASH_ALIAS
9846 if (g_parsefile->next_to_pgetc[-1] == ' '
9847 || g_parsefile->next_to_pgetc[-1] == '\t'
9849 checkkwd |= CHKALIAS;
9851 if (sp->string != sp->ap->val) {
9854 sp->ap->flag &= ~ALIASINUSE;
9855 if (sp->ap->flag & ALIASDEAD) {
9856 unalias(sp->ap->name);
9860 g_parsefile->next_to_pgetc = sp->prev_string;
9861 g_parsefile->left_in_line = sp->prev_left_in_line;
9862 g_parsefile->unget = sp->unget;
9863 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9864 g_parsefile->strpush = sp->prev;
9865 if (sp != &(g_parsefile->basestrpush))
9874 char *buf = g_parsefile->buf;
9876 g_parsefile->next_to_pgetc = buf;
9877 #if ENABLE_FEATURE_EDITING
9879 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9880 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9883 # if ENABLE_ASH_IDLE_TIMEOUT
9885 const char *tmout_var = lookupvar("TMOUT");
9887 timeout = atoi(tmout_var) * 1000;
9893 # if ENABLE_FEATURE_TAB_COMPLETION
9894 line_input_state->path_lookup = pathval();
9896 reinit_unicode_for_ash();
9897 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9899 /* ^C pressed, "convert" to SIGINT */
9900 write(STDOUT_FILENO, "^C", 2);
9907 exitstatus = 128 + SIGINT;
9913 /* Ctrl+D pressed */
9916 # if ENABLE_ASH_IDLE_TIMEOUT
9917 else if (errno == EAGAIN && timeout > 0) {
9918 puts("\007timed out waiting for input: auto-logout");
9925 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9928 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9930 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9931 int flags = fcntl(0, F_GETFL);
9932 if (flags >= 0 && (flags & O_NONBLOCK)) {
9933 flags &= ~O_NONBLOCK;
9934 if (fcntl(0, F_SETFL, flags) >= 0) {
9935 out2str("sh: turning off NDELAY mode\n");
9946 * Refill the input buffer and return the next input character:
9948 * 1) If a string was pushed back on the input, pop it;
9949 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9950 * or we are reading from a string so we can't refill the buffer,
9952 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9953 * 4) Process input up to the next newline, deleting nul characters.
9955 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9956 #define pgetc_debug(...) ((void)0)
9957 static int pgetc(void);
9964 if (g_parsefile->strpush) {
9965 #if ENABLE_ASH_ALIAS
9966 if (g_parsefile->left_in_line == -1
9967 && g_parsefile->strpush->ap
9968 && g_parsefile->next_to_pgetc[-1] != ' '
9969 && g_parsefile->next_to_pgetc[-1] != '\t'
9971 pgetc_debug("preadbuffer PEOA");
9978 /* on both branches above g_parsefile->left_in_line < 0.
9979 * "pgetc" needs refilling.
9982 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9983 * pungetc() may increment it a few times.
9984 * Assuming it won't increment it to less than -90.
9986 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9987 pgetc_debug("preadbuffer PEOF1");
9988 /* even in failure keep left_in_line and next_to_pgetc
9989 * in lock step, for correct multi-layer pungetc.
9990 * left_in_line was decremented before preadbuffer(),
9991 * must inc next_to_pgetc: */
9992 g_parsefile->next_to_pgetc++;
9996 more = g_parsefile->left_in_buffer;
9998 flush_stdout_stderr();
10002 /* don't try reading again */
10003 g_parsefile->left_in_line = -99;
10004 pgetc_debug("preadbuffer PEOF2");
10005 g_parsefile->next_to_pgetc++;
10010 /* Find out where's the end of line.
10011 * Set g_parsefile->left_in_line
10012 * and g_parsefile->left_in_buffer acordingly.
10013 * NUL chars are deleted.
10015 q = g_parsefile->next_to_pgetc;
10023 memmove(q, q + 1, more);
10027 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10033 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10034 if (g_parsefile->left_in_line < 0)
10039 g_parsefile->left_in_buffer = more;
10044 out2str(g_parsefile->next_to_pgetc);
10048 pgetc_debug("preadbuffer at %d:%p'%s'",
10049 g_parsefile->left_in_line,
10050 g_parsefile->next_to_pgetc,
10051 g_parsefile->next_to_pgetc);
10052 return (unsigned char)*g_parsefile->next_to_pgetc++;
10058 g_parsefile->linno++;
10059 setprompt_if(doprompt, 2);
10064 g_parsefile->linno++;
10065 needprompt = doprompt;
10073 pgetc_debug("pgetc at %d:%p'%s'",
10074 g_parsefile->left_in_line,
10075 g_parsefile->next_to_pgetc,
10076 g_parsefile->next_to_pgetc);
10077 if (g_parsefile->unget)
10078 return g_parsefile->lastc[--g_parsefile->unget];
10080 if (--g_parsefile->left_in_line >= 0)
10081 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10085 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10086 g_parsefile->lastc[0] = c;
10091 #if ENABLE_ASH_ALIAS
10093 pgetc_without_PEOA(void)
10097 pgetc_debug("pgetc at %d:%p'%s'",
10098 g_parsefile->left_in_line,
10099 g_parsefile->next_to_pgetc,
10100 g_parsefile->next_to_pgetc);
10102 } while (c == PEOA);
10106 # define pgetc_without_PEOA() pgetc()
10110 * Read a line from the script.
10113 pfgets(char *line, int len)
10119 while (--nleft > 0) {
10120 c = pgetc_without_PEOA();
10135 * Undo a call to pgetc. Only two characters may be pushed back.
10136 * PEOF may be pushed back.
10141 g_parsefile->unget++;
10144 /* This one eats backslash+newline */
10150 while ((c = pgetc()) == '\\') {
10151 if (pgetc() != '\n') {
10163 * To handle the "." command, a stack of input files is used. Pushfile
10164 * adds a new entry to the stack and popfile restores the previous level.
10169 struct parsefile *pf;
10171 pf = ckzalloc(sizeof(*pf));
10172 pf->prev = g_parsefile;
10174 /*pf->strpush = NULL; - ckzalloc did it */
10175 /*pf->basestrpush.prev = NULL;*/
10183 struct parsefile *pf = g_parsefile;
10189 if (pf->pf_fd >= 0)
10192 while (pf->strpush)
10194 g_parsefile = pf->prev;
10200 * Return to top level.
10205 while (g_parsefile != &basepf)
10210 * Close the file(s) that the shell is reading commands from. Called
10211 * after a fork is done.
10217 if (g_parsefile->pf_fd > 0) {
10218 close(g_parsefile->pf_fd);
10219 g_parsefile->pf_fd = 0;
10224 * Like setinputfile, but takes an open file descriptor. Call this with
10228 setinputfd(int fd, int push)
10232 g_parsefile->buf = NULL;
10234 g_parsefile->pf_fd = fd;
10235 if (g_parsefile->buf == NULL)
10236 g_parsefile->buf = ckmalloc(IBUFSIZ);
10237 g_parsefile->left_in_buffer = 0;
10238 g_parsefile->left_in_line = 0;
10239 g_parsefile->linno = 1;
10243 * Set the input to take input from a file. If push is set, push the
10244 * old input onto the stack first.
10247 setinputfile(const char *fname, int flags)
10252 fd = open(fname, O_RDONLY);
10254 if (flags & INPUT_NOFILE_OK)
10257 ash_msg_and_raise_error("can't open '%s'", fname);
10262 close_on_exec_on(fd);
10263 setinputfd(fd, flags & INPUT_PUSH_FILE);
10270 * Like setinputfile, but takes input from a string.
10273 setinputstring(char *string)
10277 g_parsefile->next_to_pgetc = string;
10278 g_parsefile->left_in_line = strlen(string);
10279 g_parsefile->buf = NULL;
10280 g_parsefile->linno = 1;
10286 * Routines to check for mail.
10289 #if ENABLE_ASH_MAIL
10291 /* Hash of mtimes of mailboxes */
10292 static unsigned mailtime_hash;
10293 /* Set if MAIL or MAILPATH is changed. */
10294 static smallint mail_var_path_changed;
10297 * Print appropriate message(s) if mail has arrived.
10298 * If mail_var_path_changed is set,
10299 * then the value of MAIL has mail_var_path_changed,
10300 * so we just update the values.
10309 struct stackmark smark;
10312 setstackmark(&smark);
10313 mpath = mpathset() ? mpathval() : mailval();
10316 p = path_advance(&mpath, nullstr);
10321 for (q = p; *q; q++)
10327 q[-1] = '\0'; /* delete trailing '/' */
10328 if (stat(p, &statb) < 0) {
10331 /* Very simplistic "hash": just a sum of all mtimes */
10332 new_hash += (unsigned)statb.st_mtime;
10334 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10335 if (mailtime_hash != 0)
10336 out2str("you have mail\n");
10337 mailtime_hash = new_hash;
10339 mail_var_path_changed = 0;
10340 popstackmark(&smark);
10343 static void FAST_FUNC
10344 changemail(const char *val UNUSED_PARAM)
10346 mail_var_path_changed = 1;
10349 #endif /* ASH_MAIL */
10352 /* ============ ??? */
10355 * Set the shell parameters.
10358 setparam(char **argv)
10364 for (nparam = 0; argv[nparam]; nparam++)
10366 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10368 *ap++ = ckstrdup(*argv++);
10371 freeparam(&shellparam);
10372 shellparam.malloced = 1;
10373 shellparam.nparam = nparam;
10374 shellparam.p = newparam;
10375 #if ENABLE_ASH_GETOPTS
10376 shellparam.optind = 1;
10377 shellparam.optoff = -1;
10382 * Process shell options. The global variable argptr contains a pointer
10383 * to the argument list; we advance it past the options.
10385 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10386 * For a non-interactive shell, an error condition encountered
10387 * by a special built-in ... shall cause the shell to write a diagnostic message
10388 * to standard error and exit as shown in the following table:
10389 * Error Special Built-In
10391 * Utility syntax error (option or operand error) Shall exit
10393 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10394 * we see that bash does not do that (set "finishes" with error code 1 instead,
10395 * and shell continues), and people rely on this behavior!
10397 * set -o barfoo 2>/dev/null
10400 * Oh well. Let's mimic that.
10403 plus_minus_o(char *name, int val)
10408 for (i = 0; i < NOPTS; i++) {
10409 if (strcmp(name, optnames(i)) == 0) {
10414 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10417 for (i = 0; i < NOPTS; i++) {
10419 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10421 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10427 setoption(int flag, int val)
10431 for (i = 0; i < NOPTS; i++) {
10432 if (optletters(i) == flag) {
10437 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10441 options(int cmdline)
10449 while ((p = *argptr) != NULL) {
10451 if (c != '-' && c != '+')
10454 val = 0; /* val = 0 if c == '+' */
10457 if (p[0] == '\0' || LONE_DASH(p)) {
10459 /* "-" means turn off -x and -v */
10462 /* "--" means reset params */
10463 else if (*argptr == NULL)
10466 break; /* "-" or "--" terminates options */
10469 /* first char was + or - */
10470 while ((c = *p++) != '\0') {
10471 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10472 if (c == 'c' && cmdline) {
10473 minusc = p; /* command is after shell args */
10474 } else if (c == 'o') {
10475 if (plus_minus_o(*argptr, val)) {
10476 /* it already printed err message */
10477 return 1; /* error */
10481 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10483 /* bash does not accept +-login, we also won't */
10484 } else if (cmdline && val && (c == '-')) { /* long options */
10485 if (strcmp(p, "login") == 0)
10497 * The shift builtin command.
10499 static int FAST_FUNC
10500 shiftcmd(int argc UNUSED_PARAM, char **argv)
10507 n = number(argv[1]);
10508 if (n > shellparam.nparam)
10509 n = 0; /* bash compat, was = shellparam.nparam; */
10511 shellparam.nparam -= n;
10512 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10513 if (shellparam.malloced)
10516 ap2 = shellparam.p;
10517 while ((*ap2++ = *ap1++) != NULL)
10519 #if ENABLE_ASH_GETOPTS
10520 shellparam.optind = 1;
10521 shellparam.optoff = -1;
10528 * POSIX requires that 'set' (but not export or readonly) output the
10529 * variables in lexicographic order - by the locale's collating order (sigh).
10530 * Maybe we could keep them in an ordered balanced binary tree
10531 * instead of hashed lists.
10532 * For now just roll 'em through qsort for printing...
10535 showvars(const char *sep_prefix, int on, int off)
10538 char **ep, **epend;
10540 ep = listvars(on, off, &epend);
10541 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10543 sep = *sep_prefix ? " " : sep_prefix;
10545 for (; ep < epend; ep++) {
10549 p = strchrnul(*ep, '=');
10552 q = single_quote(++p);
10553 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10559 * The set command builtin.
10561 static int FAST_FUNC
10562 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10567 return showvars(nullstr, 0, VUNSET);
10570 retval = options(/*cmdline:*/ 0);
10571 if (retval == 0) { /* if no parse error... */
10573 if (*argptr != NULL) {
10581 #if ENABLE_ASH_RANDOM_SUPPORT
10582 static void FAST_FUNC
10583 change_random(const char *value)
10587 if (value == NULL) {
10588 /* "get", generate */
10589 t = next_random(&random_gen);
10590 /* set without recursion */
10591 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10592 vrandom.flags &= ~VNOFUNC;
10595 t = strtoul(value, NULL, 10);
10596 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10601 #if ENABLE_ASH_GETOPTS
10603 getopts(char *optstr, char *optvar, char **optfirst)
10610 int ind = shellparam.optind;
10611 int off = shellparam.optoff;
10615 shellparam.optind = -1;
10616 optnext = optfirst + ind - 1;
10618 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10621 p = optnext[-1] + off;
10622 if (p == NULL || *p == '\0') {
10623 /* Current word is done, advance */
10625 if (p == NULL || *p != '-' || *++p == '\0') {
10632 if (LONE_DASH(p)) /* check for "--" */
10637 for (q = optstr; *q != c;) {
10639 if (optstr[0] == ':') {
10641 /*sbuf[1] = '\0'; - already is */
10642 setvar0("OPTARG", sbuf);
10644 fprintf(stderr, "Illegal option -%c\n", c);
10645 unsetvar("OPTARG");
10655 if (*p == '\0' && (p = *optnext) == NULL) {
10656 if (optstr[0] == ':') {
10658 /*sbuf[1] = '\0'; - already is */
10659 setvar0("OPTARG", sbuf);
10662 fprintf(stderr, "No arg for -%c option\n", c);
10663 unsetvar("OPTARG");
10671 setvar0("OPTARG", p);
10674 setvar0("OPTARG", nullstr);
10676 ind = optnext - optfirst + 1;
10677 setvar("OPTIND", itoa(ind), VNOFUNC);
10679 /*sbuf[1] = '\0'; - already is */
10680 setvar0(optvar, sbuf);
10682 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10683 shellparam.optind = ind;
10689 * The getopts builtin. Shellparam.optnext points to the next argument
10690 * to be processed. Shellparam.optptr points to the next character to
10691 * be processed in the current argument. If shellparam.optnext is NULL,
10692 * then it's the first time getopts has been called.
10694 static int FAST_FUNC
10695 getoptscmd(int argc, char **argv)
10700 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10702 optbase = shellparam.p;
10703 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10704 shellparam.optind = 1;
10705 shellparam.optoff = -1;
10708 optbase = &argv[3];
10709 if ((unsigned)shellparam.optind > argc - 2) {
10710 shellparam.optind = 1;
10711 shellparam.optoff = -1;
10715 return getopts(argv[1], argv[2], optbase);
10717 #endif /* ASH_GETOPTS */
10720 /* ============ Shell parser */
10723 struct heredoc *next; /* next here document in list */
10724 union node *here; /* redirection node */
10725 char *eofmark; /* string indicating end of input */
10726 smallint striptabs; /* if set, strip leading tabs */
10729 static smallint tokpushback; /* last token pushed back */
10730 static smallint quoteflag; /* set if (part of) last token was quoted */
10731 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10732 static struct heredoc *heredoclist; /* list of here documents to read */
10733 static char *wordtext; /* text of last word returned by readtoken */
10734 static struct nodelist *backquotelist;
10735 static union node *redirnode;
10736 static struct heredoc *heredoc;
10738 static const char *
10739 tokname(char *buf, int tok)
10742 return tokname_array[tok];
10743 sprintf(buf, "\"%s\"", tokname_array[tok]);
10747 /* raise_error_unexpected_syntax:
10748 * Called when an unexpected token is read during the parse. The argument
10749 * is the token that is expected, or -1 if more than one type of token can
10750 * occur at this point.
10752 static void raise_error_unexpected_syntax(int) NORETURN;
10754 raise_error_unexpected_syntax(int token)
10760 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10762 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10763 raise_error_syntax(msg);
10767 #define EOFMARKLEN 79
10769 /* parsing is heavily cross-recursive, need these forward decls */
10770 static union node *andor(void);
10771 static union node *pipeline(void);
10772 static union node *parse_command(void);
10773 static void parseheredoc(void);
10774 static int peektoken(void);
10775 static int readtoken(void);
10777 static union node *
10780 union node *n1, *n2, *n3;
10785 switch (peektoken()) {
10793 if (!n1 && (nlflag & 1))
10799 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10800 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10806 if (tok == TBACKGND) {
10807 if (n2->type == NPIPE) {
10808 n2->npipe.pipe_backgnd = 1;
10810 if (n2->type != NREDIR) {
10811 n3 = stzalloc(sizeof(struct nredir));
10813 /*n3->nredir.redirect = NULL; - stzalloc did it */
10816 n2->type = NBACKGND;
10822 n3 = stzalloc(sizeof(struct nbinary));
10824 n3->nbinary.ch1 = n1;
10825 n3->nbinary.ch2 = n2;
10838 raise_error_unexpected_syntax(-1);
10845 static union node *
10848 union node *n1, *n2, *n3;
10856 } else if (t == TOR) {
10862 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10864 n3 = stzalloc(sizeof(struct nbinary));
10866 n3->nbinary.ch1 = n1;
10867 n3->nbinary.ch2 = n2;
10872 static union node *
10875 union node *n1, *n2, *pipenode;
10876 struct nodelist *lp, *prev;
10880 TRACE(("pipeline: entered\n"));
10881 if (readtoken() == TNOT) {
10883 checkkwd = CHKKWD | CHKALIAS;
10886 n1 = parse_command();
10887 if (readtoken() == TPIPE) {
10888 pipenode = stzalloc(sizeof(struct npipe));
10889 pipenode->type = NPIPE;
10890 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10891 lp = stzalloc(sizeof(struct nodelist));
10892 pipenode->npipe.cmdlist = lp;
10896 lp = stzalloc(sizeof(struct nodelist));
10897 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10898 lp->n = parse_command();
10900 } while (readtoken() == TPIPE);
10906 n2 = stzalloc(sizeof(struct nnot));
10914 static union node *
10919 n = stzalloc(sizeof(struct narg));
10921 /*n->narg.next = NULL; - stzalloc did it */
10922 n->narg.text = wordtext;
10923 n->narg.backquote = backquotelist;
10928 fixredir(union node *n, const char *text, int err)
10932 TRACE(("Fix redir %s %d\n", text, err));
10934 n->ndup.vname = NULL;
10936 fd = bb_strtou(text, NULL, 10);
10937 if (!errno && fd >= 0)
10938 n->ndup.dupfd = fd;
10939 else if (LONE_DASH(text))
10940 n->ndup.dupfd = -1;
10943 raise_error_syntax("bad fd number");
10944 n->ndup.vname = makename();
10949 * Returns true if the text contains nothing to expand (no dollar signs
10953 noexpand(const char *text)
10957 while ((c = *text++) != '\0') {
10958 if (c == CTLQUOTEMARK)
10962 else if (SIT(c, BASESYNTAX) == CCTL)
10971 union node *n = redirnode;
10973 if (readtoken() != TWORD)
10974 raise_error_unexpected_syntax(-1);
10975 if (n->type == NHERE) {
10976 struct heredoc *here = heredoc;
10980 if (quoteflag == 0)
10982 TRACE(("Here document %d\n", n->type));
10983 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10984 raise_error_syntax("illegal eof marker for << redirection");
10985 rmescapes(wordtext, 0);
10986 here->eofmark = wordtext;
10988 if (heredoclist == NULL)
10989 heredoclist = here;
10991 for (p = heredoclist; p->next; p = p->next)
10995 } else if (n->type == NTOFD || n->type == NFROMFD) {
10996 fixredir(n, wordtext, 0);
10998 n->nfile.fname = makename();
11002 static union node *
11005 union node *args, **app;
11006 union node *n = NULL;
11007 union node *vars, **vpp;
11008 union node **rpp, *redir;
11010 #if ENABLE_ASH_BASH_COMPAT
11011 smallint double_brackets_flag = 0;
11012 smallint function_flag = 0;
11022 savecheckkwd = CHKALIAS;
11025 checkkwd = savecheckkwd;
11028 #if ENABLE_ASH_BASH_COMPAT
11030 if (peektoken() != TWORD)
11031 raise_error_unexpected_syntax(TWORD);
11034 case TAND: /* "&&" */
11035 case TOR: /* "||" */
11036 if (!double_brackets_flag) {
11040 wordtext = (char *) (t == TAND ? "-a" : "-o");
11043 n = stzalloc(sizeof(struct narg));
11045 /*n->narg.next = NULL; - stzalloc did it */
11046 n->narg.text = wordtext;
11047 #if ENABLE_ASH_BASH_COMPAT
11048 if (strcmp("[[", wordtext) == 0)
11049 double_brackets_flag = 1;
11050 else if (strcmp("]]", wordtext) == 0)
11051 double_brackets_flag = 0;
11053 n->narg.backquote = backquotelist;
11054 if (savecheckkwd && isassignment(wordtext)) {
11056 vpp = &n->narg.next;
11059 app = &n->narg.next;
11062 #if ENABLE_ASH_BASH_COMPAT
11063 if (function_flag) {
11064 checkkwd = CHKNL | CHKKWD;
11065 switch (peektoken()) {
11077 if (strcmp("[[", wordtext) == 0)
11081 raise_error_unexpected_syntax(-1);
11087 *rpp = n = redirnode;
11088 rpp = &n->nfile.next;
11089 parsefname(); /* read name of redirection file */
11092 IF_ASH_BASH_COMPAT(do_func:)
11093 if (args && app == &args->narg.next
11096 struct builtincmd *bcmd;
11099 /* We have a function */
11100 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11101 raise_error_unexpected_syntax(TRP);
11102 name = n->narg.text;
11103 if (!goodname(name)
11104 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11106 raise_error_syntax("bad function name");
11109 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11110 n->narg.next = parse_command();
11113 IF_ASH_BASH_COMPAT(function_flag = 0;)
11124 n = stzalloc(sizeof(struct ncmd));
11126 n->ncmd.args = args;
11127 n->ncmd.assign = vars;
11128 n->ncmd.redirect = redir;
11132 static union node *
11133 parse_command(void)
11135 union node *n1, *n2;
11136 union node *ap, **app;
11137 union node *cp, **cpp;
11138 union node *redir, **rpp;
11145 switch (readtoken()) {
11147 raise_error_unexpected_syntax(-1);
11150 n1 = stzalloc(sizeof(struct nif));
11152 n1->nif.test = list(0);
11153 if (readtoken() != TTHEN)
11154 raise_error_unexpected_syntax(TTHEN);
11155 n1->nif.ifpart = list(0);
11157 while (readtoken() == TELIF) {
11158 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11159 n2 = n2->nif.elsepart;
11161 n2->nif.test = list(0);
11162 if (readtoken() != TTHEN)
11163 raise_error_unexpected_syntax(TTHEN);
11164 n2->nif.ifpart = list(0);
11166 if (lasttoken == TELSE)
11167 n2->nif.elsepart = list(0);
11169 n2->nif.elsepart = NULL;
11177 n1 = stzalloc(sizeof(struct nbinary));
11178 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11179 n1->nbinary.ch1 = list(0);
11182 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11183 got == TWORD ? wordtext : ""));
11184 raise_error_unexpected_syntax(TDO);
11186 n1->nbinary.ch2 = list(0);
11191 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11192 raise_error_syntax("bad for loop variable");
11193 n1 = stzalloc(sizeof(struct nfor));
11195 n1->nfor.var = wordtext;
11196 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11197 if (readtoken() == TIN) {
11199 while (readtoken() == TWORD) {
11200 n2 = stzalloc(sizeof(struct narg));
11202 /*n2->narg.next = NULL; - stzalloc did it */
11203 n2->narg.text = wordtext;
11204 n2->narg.backquote = backquotelist;
11206 app = &n2->narg.next;
11209 n1->nfor.args = ap;
11210 if (lasttoken != TNL && lasttoken != TSEMI)
11211 raise_error_unexpected_syntax(-1);
11213 n2 = stzalloc(sizeof(struct narg));
11215 /*n2->narg.next = NULL; - stzalloc did it */
11216 n2->narg.text = (char *)dolatstr;
11217 /*n2->narg.backquote = NULL;*/
11218 n1->nfor.args = n2;
11220 * Newline or semicolon here is optional (but note
11221 * that the original Bourne shell only allowed NL).
11223 if (lasttoken != TSEMI)
11226 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11227 if (readtoken() != TDO)
11228 raise_error_unexpected_syntax(TDO);
11229 n1->nfor.body = list(0);
11233 n1 = stzalloc(sizeof(struct ncase));
11235 if (readtoken() != TWORD)
11236 raise_error_unexpected_syntax(TWORD);
11237 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11239 /*n2->narg.next = NULL; - stzalloc did it */
11240 n2->narg.text = wordtext;
11241 n2->narg.backquote = backquotelist;
11242 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11243 if (readtoken() != TIN)
11244 raise_error_unexpected_syntax(TIN);
11245 cpp = &n1->ncase.cases;
11247 checkkwd = CHKNL | CHKKWD;
11249 while (t != TESAC) {
11250 if (lasttoken == TLP)
11252 *cpp = cp = stzalloc(sizeof(struct nclist));
11254 app = &cp->nclist.pattern;
11256 *app = ap = stzalloc(sizeof(struct narg));
11258 /*ap->narg.next = NULL; - stzalloc did it */
11259 ap->narg.text = wordtext;
11260 ap->narg.backquote = backquotelist;
11261 if (readtoken() != TPIPE)
11263 app = &ap->narg.next;
11266 //ap->narg.next = NULL;
11267 if (lasttoken != TRP)
11268 raise_error_unexpected_syntax(TRP);
11269 cp->nclist.body = list(2);
11271 cpp = &cp->nclist.next;
11273 checkkwd = CHKNL | CHKKWD;
11277 raise_error_unexpected_syntax(TENDCASE);
11284 n1 = stzalloc(sizeof(struct nredir));
11285 n1->type = NSUBSHELL;
11286 n1->nredir.n = list(0);
11287 /*n1->nredir.redirect = NULL; - stzalloc did it */
11294 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11298 return simplecmd();
11301 if (readtoken() != t)
11302 raise_error_unexpected_syntax(t);
11305 /* Now check for redirection which may follow command */
11306 checkkwd = CHKKWD | CHKALIAS;
11308 while (readtoken() == TREDIR) {
11309 *rpp = n2 = redirnode;
11310 rpp = &n2->nfile.next;
11316 if (n1->type != NSUBSHELL) {
11317 n2 = stzalloc(sizeof(struct nredir));
11322 n1->nredir.redirect = redir;
11327 #if ENABLE_ASH_BASH_COMPAT
11329 decode_dollar_squote(void)
11331 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11337 p = strchr(C_escapes, c);
11342 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11346 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11348 } else if (c == 'x') { /* \xHH */
11352 } while (isxdigit(c) && --cnt);
11354 if (cnt == 3) { /* \x but next char is "bad" */
11358 } else { /* simple seq like \\ or \t */
11363 c = bb_process_escape_sequence((void*)&p);
11364 } else { /* unrecognized "\z": print both chars unless ' or " */
11365 if (c != '\'' && c != '"') {
11367 c |= 0x100; /* "please encode \, then me" */
11375 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11376 * is not NULL, read a here document. In the latter case, eofmark is the
11377 * word which marks the end of the document and striptabs is true if
11378 * leading tabs should be stripped from the document. The argument c
11379 * is the first character of the input token or document.
11381 * Because C does not have internal subroutines, I have simulated them
11382 * using goto's to implement the subroutine linkage. The following macros
11383 * will run code that appears at the end of readtoken1.
11385 #define CHECKEND() {goto checkend; checkend_return:;}
11386 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11387 #define PARSESUB() {goto parsesub; parsesub_return:;}
11388 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11389 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11390 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11392 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11394 /* NB: syntax parameter fits into smallint */
11395 /* c parameter is an unsigned char or PEOF or PEOA */
11398 char line[EOFMARKLEN + 1];
11399 struct nodelist *bqlist;
11403 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11404 #if ENABLE_ASH_EXPAND_PRMT
11405 smallint pssyntax; /* we are expanding a prompt string */
11407 int varnest; /* levels of variables expansion */
11408 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11409 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11410 int dqvarnest; /* levels of variables expansion within double quotes */
11412 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11414 startlinno = g_parsefile->linno;
11417 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11418 #if ENABLE_ASH_EXPAND_PRMT
11419 pssyntax = (syntax == PSSYNTAX);
11423 dblquote = (syntax == DQSYNTAX);
11425 IF_FEATURE_SH_MATH(arinest = 0;)
11426 IF_FEATURE_SH_MATH(parenlevel = 0;)
11429 STARTSTACKSTR(out);
11431 /* For each line, until end of word */
11432 CHECKEND(); /* set c to PEOF if at end of here document */
11433 for (;;) { /* until end of line or end of word */
11434 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11435 switch (SIT(c, syntax)) {
11436 case CNL: /* '\n' */
11437 if (syntax == BASESYNTAX)
11438 goto endword; /* exit outer loop */
11442 goto loop; /* continue outer loop */
11447 #if ENABLE_ASH_BASH_COMPAT
11448 if (c == '\\' && bash_dollar_squote) {
11449 c = decode_dollar_squote();
11451 /* skip $'\000', $'\x00' (like bash) */
11455 /* Unknown escape. Encode as '\z' */
11456 c = (unsigned char)c;
11457 if (eofmark == NULL || dblquote)
11458 USTPUTC(CTLESC, out);
11459 USTPUTC('\\', out);
11463 if (eofmark == NULL || dblquote)
11464 USTPUTC(CTLESC, out);
11467 case CBACK: /* backslash */
11468 c = pgetc_without_PEOA();
11470 USTPUTC(CTLESC, out);
11471 USTPUTC('\\', out);
11473 } else if (c == '\n') {
11476 #if ENABLE_ASH_EXPAND_PRMT
11477 if (c == '$' && pssyntax) {
11478 USTPUTC(CTLESC, out);
11479 USTPUTC('\\', out);
11482 /* Backslash is retained if we are in "str" and next char isn't special */
11487 && (c != '"' || eofmark != NULL)
11489 USTPUTC('\\', out);
11491 USTPUTC(CTLESC, out);
11499 if (eofmark == NULL) {
11500 USTPUTC(CTLQUOTEMARK, out);
11508 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11509 if (eofmark != NULL && varnest == 0) {
11512 if (dqvarnest == 0) {
11513 syntax = BASESYNTAX;
11520 case CVAR: /* '$' */
11521 PARSESUB(); /* parse substitution */
11523 case CENDVAR: /* '}' */
11526 if (dqvarnest > 0) {
11533 #if ENABLE_FEATURE_SH_MATH
11534 case CLP: /* '(' in arithmetic */
11538 case CRP: /* ')' in arithmetic */
11539 if (parenlevel > 0) {
11542 if (pgetc_eatbnl() == ')') {
11544 if (--arinest == 0) {
11545 syntax = prevsyntax;
11549 * unbalanced parens
11550 * (don't 2nd guess - no error)
11558 case CBQUOTE: /* '`' */
11562 goto endword; /* exit outer loop */
11566 if (varnest == 0) {
11567 #if ENABLE_ASH_BASH_COMPAT
11569 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11570 if (pgetc() == '>')
11571 c = 0x100 + '>'; /* flag &> */
11575 goto endword; /* exit outer loop */
11577 IF_ASH_ALIAS(if (c != PEOA))
11584 #if ENABLE_FEATURE_SH_MATH
11585 if (syntax == ARISYNTAX)
11586 raise_error_syntax("missing '))'");
11588 if (syntax != BASESYNTAX && eofmark == NULL)
11589 raise_error_syntax("unterminated quoted string");
11590 if (varnest != 0) {
11591 startlinno = g_parsefile->linno;
11593 raise_error_syntax("missing '}'");
11595 USTPUTC('\0', out);
11596 len = out - (char *)stackblock();
11597 out = stackblock();
11598 if (eofmark == NULL) {
11599 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11602 if (isdigit_str9(out)) {
11603 PARSEREDIR(); /* passed as params: out, c */
11604 lasttoken = TREDIR;
11607 /* else: non-number X seen, interpret it
11608 * as "NNNX>file" = "NNNX >file" */
11612 quoteflag = quotef;
11613 backquotelist = bqlist;
11614 grabstackblock(len);
11618 /* end of readtoken routine */
11621 * Check to see whether we are at the end of the here document. When this
11622 * is called, c is set to the first character of the next input line. If
11623 * we are at the end of the here document, this routine sets the c to PEOF.
11627 #if ENABLE_ASH_ALIAS
11629 c = pgetc_without_PEOA();
11632 while (c == '\t') {
11633 c = pgetc_without_PEOA();
11636 if (c == *eofmark) {
11637 if (pfgets(line, sizeof(line)) != NULL) {
11642 for (q = eofmark + 1;; p++, q++) {
11646 if (!*q || cc != *q)
11653 pushstring(line, NULL);
11658 goto checkend_return;
11662 * Parse a redirection operator. The variable "out" points to a string
11663 * specifying the fd to be redirected. The variable "c" contains the
11664 * first character of the redirection operator.
11667 /* out is already checked to be a valid number or "" */
11668 int fd = (*out == '\0' ? -1 : atoi(out));
11671 np = stzalloc(sizeof(struct nfile));
11676 np->type = NAPPEND;
11678 np->type = NCLOBBER;
11681 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11687 #if ENABLE_ASH_BASH_COMPAT
11688 else if (c == 0x100 + '>') { /* this flags &> redirection */
11690 pgetc(); /* this is '>', no need to check */
11694 else { /* c == '<' */
11695 /*np->nfile.fd = 0; - stzalloc did it */
11699 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11700 np = stzalloc(sizeof(struct nhere));
11701 /*np->nfile.fd = 0; - stzalloc did it */
11704 heredoc = stzalloc(sizeof(struct heredoc));
11705 heredoc->here = np;
11708 heredoc->striptabs = 1;
11710 /*heredoc->striptabs = 0; - stzalloc did it */
11716 np->type = NFROMFD;
11720 np->type = NFROMTO;
11732 goto parseredir_return;
11736 * Parse a substitution. At this point, we have read the dollar sign
11737 * and nothing else.
11740 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11741 * (assuming ascii char codes, as the original implementation did) */
11742 #define is_special(c) \
11743 (((unsigned)(c) - 33 < 32) \
11744 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11746 unsigned char subtype;
11749 c = pgetc_eatbnl();
11750 if (c > 255 /* PEOA or PEOF */
11751 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11753 #if ENABLE_ASH_BASH_COMPAT
11754 if (syntax != DQSYNTAX && c == '\'')
11755 bash_dollar_squote = 1;
11760 } else if (c == '(') {
11761 /* $(command) or $((arith)) */
11762 if (pgetc_eatbnl() == '(') {
11763 #if ENABLE_FEATURE_SH_MATH
11766 raise_error_syntax("you disabled math support for $((arith)) syntax");
11773 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11774 USTPUTC(CTLVAR, out);
11775 typeloc = out - (char *)stackblock();
11777 subtype = VSNORMAL;
11779 c = pgetc_eatbnl();
11784 /* $[{[#]]NAME[}] */
11787 c = pgetc_eatbnl();
11788 } while (is_in_name(c));
11789 } else if (isdigit(c)) {
11790 /* $[{[#]]NUM[}] */
11793 c = pgetc_eatbnl();
11794 } while (isdigit(c));
11795 } else if (is_special(c)) {
11796 /* $[{[#]]<specialchar>[}] */
11799 c = pgetc_eatbnl();
11800 if (!subtype && cc == '#') {
11801 subtype = VSLENGTH;
11802 if (c == '_' || isalnum(c))
11805 c = pgetc_eatbnl();
11806 if (cc == '}' || c != '}') {
11817 if (c != '}' && subtype == VSLENGTH) {
11818 /* ${#VAR didn't end with } */
11822 if (subtype == 0) {
11823 static const char types[] ALIGN1 = "}-+?=";
11824 /* ${VAR...} but not $VAR or ${#VAR} */
11825 /* c == first char after VAR */
11828 c = pgetc_eatbnl();
11829 #if ENABLE_ASH_BASH_COMPAT
11830 /* This check is only needed to not misinterpret
11831 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11834 if (!strchr(types, c)) {
11835 subtype = VSSUBSTR;
11837 break; /* "goto badsub" is bigger (!) */
11843 const char *p = strchr(types, c);
11846 subtype |= p - types + VSNORMAL;
11852 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11853 c = pgetc_eatbnl();
11859 #if ENABLE_ASH_BASH_COMPAT
11861 /* ${v/[/]pattern/repl} */
11862 //TODO: encode pattern and repl separately.
11863 // Currently ${v/$var_with_slash/repl} is horribly broken
11864 subtype = VSREPLACE;
11865 c = pgetc_eatbnl();
11868 subtype++; /* VSREPLACEALL */
11876 ((unsigned char *)stackblock())[typeloc] = subtype;
11877 if (subtype != VSNORMAL) {
11884 goto parsesub_return;
11888 * Called to parse command substitutions. Newstyle is set if the command
11889 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11890 * list of commands (passed by reference), and savelen is the number of
11891 * characters on the top of the stack which must be preserved.
11894 struct nodelist **nlpp;
11898 smallint saveprompt = 0;
11901 savelen = out - (char *)stackblock();
11904 * FIXME: this can allocate very large block on stack and SEGV.
11906 * echo "..<100kbytes>..`true` $(true) `true` ..."
11907 * allocates 100kb for every command subst. With about
11908 * a hundred command substitutions stack overflows.
11909 * With larger prepended string, SEGV happens sooner.
11911 str = alloca(savelen);
11912 memcpy(str, stackblock(), savelen);
11916 /* We must read until the closing backquote, giving special
11917 * treatment to some slashes, and then push the string and
11918 * reread it as input, interpreting it normally.
11924 STARTSTACKSTR(pout);
11928 setprompt_if(needprompt, 2);
11939 * If eating a newline, avoid putting
11940 * the newline into the new character
11941 * stream (via the STPUTC after the
11946 if (pc != '\\' && pc != '`' && pc != '$'
11947 && (!dblquote || pc != '"')
11949 STPUTC('\\', pout);
11951 if (pc <= 255 /* not PEOA or PEOF */) {
11957 IF_ASH_ALIAS(case PEOA:)
11958 startlinno = g_parsefile->linno;
11959 raise_error_syntax("EOF in backquote substitution");
11971 STPUTC('\0', pout);
11972 psavelen = pout - (char *)stackblock();
11973 if (psavelen > 0) {
11974 pstr = grabstackstr(pout);
11975 setinputstring(pstr);
11980 nlpp = &(*nlpp)->next;
11981 *nlpp = stzalloc(sizeof(**nlpp));
11982 /* (*nlpp)->next = NULL; - stzalloc did it */
11985 saveprompt = doprompt;
11992 doprompt = saveprompt;
11993 else if (readtoken() != TRP)
11994 raise_error_unexpected_syntax(TRP);
11999 * Start reading from old file again, ignoring any pushed back
12000 * tokens left from the backquote parsing
12005 while (stackblocksize() <= savelen)
12007 STARTSTACKSTR(out);
12009 memcpy(out, str, savelen);
12010 STADJUST(savelen, out);
12012 USTPUTC(CTLBACKQ, out);
12014 goto parsebackq_oldreturn;
12015 goto parsebackq_newreturn;
12018 #if ENABLE_FEATURE_SH_MATH
12020 * Parse an arithmetic expansion (indicate start of one and set state)
12023 if (++arinest == 1) {
12024 prevsyntax = syntax;
12025 syntax = ARISYNTAX;
12027 USTPUTC(CTLARI, out);
12028 goto parsearith_return;
12031 } /* end of readtoken */
12034 * Read the next input token.
12035 * If the token is a word, we set backquotelist to the list of cmds in
12036 * backquotes. We set quoteflag to true if any part of the word was
12038 * If the token is TREDIR, then we set redirnode to a structure containing
12040 * In all cases, the variable startlinno is set to the number of the line
12041 * on which the token starts.
12043 * [Change comment: here documents and internal procedures]
12044 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12045 * word parsing code into a separate routine. In this case, readtoken
12046 * doesn't need to have any internal procedures, but parseword does.
12047 * We could also make parseoperator in essence the main routine, and
12048 * have parseword (readtoken1?) handle both words and redirection.]
12050 #define NEW_xxreadtoken
12051 #ifdef NEW_xxreadtoken
12052 /* singles must be first! */
12053 static const char xxreadtoken_chars[7] ALIGN1 = {
12054 '\n', '(', ')', /* singles */
12055 '&', '|', ';', /* doubles */
12059 #define xxreadtoken_singles 3
12060 #define xxreadtoken_doubles 3
12062 static const char xxreadtoken_tokens[] ALIGN1 = {
12063 TNL, TLP, TRP, /* only single occurrence allowed */
12064 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12065 TEOF, /* corresponds to trailing nul */
12066 TAND, TOR, TENDCASE /* if double occurrence */
12078 setprompt_if(needprompt, 2);
12079 startlinno = g_parsefile->linno;
12080 for (;;) { /* until token or start of word found */
12082 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12086 while ((c = pgetc()) != '\n' && c != PEOF)
12089 } else if (c == '\\') {
12090 if (pgetc() != '\n') {
12092 break; /* return readtoken1(...) */
12098 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12104 p = strchr(xxreadtoken_chars, c);
12106 break; /* return readtoken1(...) */
12108 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12110 if (cc == c) { /* double occurrence? */
12111 p += xxreadtoken_doubles + 1;
12114 #if ENABLE_ASH_BASH_COMPAT
12115 if (c == '&' && cc == '>') /* &> */
12116 break; /* return readtoken1(...) */
12121 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12126 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12128 #else /* old xxreadtoken */
12129 #define RETURN(token) return lasttoken = token
12139 setprompt_if(needprompt, 2);
12140 startlinno = g_parsefile->linno;
12141 for (;;) { /* until token or start of word found */
12144 case ' ': case '\t':
12145 IF_ASH_ALIAS(case PEOA:)
12148 while ((c = pgetc()) != '\n' && c != PEOF)
12153 if (pgetc() == '\n') {
12165 if (pgetc() == '&')
12170 if (pgetc() == '|')
12175 if (pgetc() == ';')
12188 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12191 #endif /* old xxreadtoken */
12197 int kwd = checkkwd;
12199 smallint alreadyseen = tokpushback;
12202 #if ENABLE_ASH_ALIAS
12218 if (t != TWORD || quoteflag) {
12223 * check for keywords
12225 if (kwd & CHKKWD) {
12226 const char *const *pp;
12228 pp = findkwd(wordtext);
12230 lasttoken = t = pp - tokname_array;
12231 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12236 if (checkkwd & CHKALIAS) {
12237 #if ENABLE_ASH_ALIAS
12239 ap = lookupalias(wordtext, 1);
12242 pushstring(ap->val, ap);
12252 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12254 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12270 * Read and parse a command. Returns NODE_EOF on end of file.
12271 * (NULL is a valid parse tree indicating a blank line.)
12273 static union node *
12274 parsecmd(int interact)
12279 doprompt = interact;
12280 setprompt_if(doprompt, doprompt);
12286 * Input any here documents.
12291 struct heredoc *here;
12294 here = heredoclist;
12295 heredoclist = NULL;
12298 setprompt_if(needprompt, 2);
12299 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12300 here->eofmark, here->striptabs);
12301 n = stzalloc(sizeof(struct narg));
12302 n->narg.type = NARG;
12303 /*n->narg.next = NULL; - stzalloc did it */
12304 n->narg.text = wordtext;
12305 n->narg.backquote = backquotelist;
12306 here->here->nhere.doc = n;
12313 * called by editline -- any expansions to the prompt should be added here.
12315 #if ENABLE_ASH_EXPAND_PRMT
12316 static const char *
12317 expandstr(const char *ps)
12322 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12323 * and token processing _can_ alter it (delete NULs etc). */
12324 setinputstring((char *)ps);
12326 saveprompt = doprompt;
12328 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12329 doprompt = saveprompt;
12333 n.narg.type = NARG;
12334 n.narg.next = NULL;
12335 n.narg.text = wordtext;
12336 n.narg.backquote = backquotelist;
12338 expandarg(&n, NULL, EXP_QUOTED);
12339 return stackblock();
12344 * Execute a command or commands contained in a string.
12347 evalstring(char *s, int flags)
12349 struct jmploc *volatile savehandler;
12350 struct jmploc jmploc;
12354 struct stackmark smark;
12359 setstackmark(&smark);
12362 /* On exception inside execution loop, we must popfile().
12363 * Try interactively:
12365 * command eval "a=b" # throws "is read only" error
12366 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12367 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12369 savehandler = exception_handler;
12370 ex = setjmp(jmploc.loc);
12373 exception_handler = &jmploc;
12375 while ((n = parsecmd(0)) != NODE_EOF) {
12378 i = evaltree(n, flags);
12381 popstackmark(&smark);
12386 popstackmark(&smark);
12390 exception_handler = savehandler;
12392 longjmp(exception_handler->loc, ex);
12398 * The eval command.
12400 static int FAST_FUNC
12401 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12410 STARTSTACKSTR(concat);
12412 concat = stack_putstr(p, concat);
12416 STPUTC(' ', concat);
12418 STPUTC('\0', concat);
12419 p = grabstackstr(concat);
12421 return evalstring(p, flags & EV_TESTED);
12427 * Read and execute commands.
12428 * "Top" is nonzero for the top level command loop;
12429 * it turns on prompting if the shell is interactive.
12435 struct stackmark smark;
12440 TRACE(("cmdloop(%d) called\n", top));
12444 setstackmark(&smark);
12447 showjobs(SHOW_CHANGED|SHOW_STDERR);
12450 if (iflag && top) {
12454 n = parsecmd(inter);
12456 if (DEBUG > 2 && debug && (n != NODE_EOF))
12459 if (n == NODE_EOF) {
12460 if (!top || numeof >= 50)
12462 if (!stoppedjobs()) {
12465 out2str("\nUse \"exit\" to leave shell.\n");
12468 } else if (nflag == 0) {
12471 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12474 i = evaltree(n, 0);
12478 popstackmark(&smark);
12482 evalskip &= ~SKIPFUNC;
12490 * Take commands from a file. To be compatible we should do a path
12491 * search for the file, which is necessary to find sub-commands.
12494 find_dot_file(char *name)
12497 const char *path = pathval();
12500 /* don't try this for absolute or relative paths */
12501 if (strchr(name, '/'))
12504 /* IIRC standards do not say whether . is to be searched.
12505 * And it is even smaller this way, making it unconditional for now:
12507 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12512 while ((fullname = path_advance(&path, name)) != NULL) {
12514 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12516 * Don't bother freeing here, since it will
12517 * be freed by the caller.
12521 if (fullname != name)
12522 stunalloc(fullname);
12525 /* not found in the PATH */
12526 ash_msg_and_raise_error("%s: not found", name);
12530 static int FAST_FUNC
12531 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12533 /* "false; . empty_file; echo $?" should print 0, not 1: */
12537 struct strlist *sp;
12538 volatile struct shparam saveparam;
12540 for (sp = cmdenviron; sp; sp = sp->next)
12541 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12543 nextopt(nullstr); /* handle possible "--" */
12547 /* bash says: "bash: .: filename argument required" */
12548 return 2; /* bash compat */
12551 /* This aborts if file isn't found, which is POSIXly correct.
12552 * bash returns exitcode 1 instead.
12554 fullname = find_dot_file(argv[0]);
12556 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12558 saveparam = shellparam;
12559 shellparam.malloced = 0;
12563 shellparam.nparam = argc;
12564 shellparam.p = argv;
12567 /* This aborts if file can't be opened, which is POSIXly correct.
12568 * bash returns exitcode 1 instead.
12570 setinputfile(fullname, INPUT_PUSH_FILE);
12571 commandname = fullname;
12572 status = cmdloop(0);
12576 freeparam(&shellparam);
12577 shellparam = saveparam;
12583 static int FAST_FUNC
12584 exitcmd(int argc UNUSED_PARAM, char **argv)
12589 exitstatus = number(argv[1]);
12590 raise_exception(EXEXIT);
12595 * Read a file containing shell functions.
12598 readcmdfile(char *name)
12600 setinputfile(name, INPUT_PUSH_FILE);
12606 /* ============ find_command inplementation */
12609 * Resolve a command name. If you change this routine, you may have to
12610 * change the shellexec routine as well.
12613 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12615 struct tblentry *cmdp;
12622 struct builtincmd *bcmd;
12624 /* If name contains a slash, don't use PATH or hash table */
12625 if (strchr(name, '/') != NULL) {
12626 entry->u.index = -1;
12627 if (act & DO_ABS) {
12628 while (stat(name, &statb) < 0) {
12630 if (errno == EINTR)
12633 entry->cmdtype = CMDUNKNOWN;
12637 entry->cmdtype = CMDNORMAL;
12641 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12643 updatetbl = (path == pathval());
12646 if (strstr(path, "%builtin") != NULL)
12647 act |= DO_ALTBLTIN;
12650 /* If name is in the table, check answer will be ok */
12651 cmdp = cmdlookup(name, 0);
12652 if (cmdp != NULL) {
12655 switch (cmdp->cmdtype) {
12673 } else if (cmdp->rehash == 0)
12674 /* if not invalidated by cd, we're done */
12678 /* If %builtin not in path, check for builtin next */
12679 bcmd = find_builtin(name);
12681 if (IS_BUILTIN_REGULAR(bcmd))
12682 goto builtin_success;
12683 if (act & DO_ALTPATH) {
12684 if (!(act & DO_ALTBLTIN))
12685 goto builtin_success;
12686 } else if (builtinloc <= 0) {
12687 goto builtin_success;
12691 #if ENABLE_FEATURE_SH_STANDALONE
12693 int applet_no = find_applet_by_name(name);
12694 if (applet_no >= 0) {
12695 entry->cmdtype = CMDNORMAL;
12696 entry->u.index = -2 - applet_no;
12702 /* We have to search path. */
12703 prev = -1; /* where to start */
12704 if (cmdp && cmdp->rehash) { /* doing a rehash */
12705 if (cmdp->cmdtype == CMDBUILTIN)
12708 prev = cmdp->param.index;
12714 while ((fullname = path_advance(&path, name)) != NULL) {
12715 stunalloc(fullname);
12716 /* NB: code below will still use fullname
12717 * despite it being "unallocated" */
12720 if (prefix(pathopt, "builtin")) {
12722 goto builtin_success;
12725 if ((act & DO_NOFUNC)
12726 || !prefix(pathopt, "func")
12727 ) { /* ignore unimplemented options */
12731 /* if rehash, don't redo absolute path names */
12732 if (fullname[0] == '/' && idx <= prev) {
12735 TRACE(("searchexec \"%s\": no change\n", name));
12738 while (stat(fullname, &statb) < 0) {
12740 if (errno == EINTR)
12743 if (errno != ENOENT && errno != ENOTDIR)
12747 e = EACCES; /* if we fail, this will be the error */
12748 if (!S_ISREG(statb.st_mode))
12750 if (pathopt) { /* this is a %func directory */
12751 stalloc(strlen(fullname) + 1);
12752 /* NB: stalloc will return space pointed by fullname
12753 * (because we don't have any intervening allocations
12754 * between stunalloc above and this stalloc) */
12755 readcmdfile(fullname);
12756 cmdp = cmdlookup(name, 0);
12757 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12758 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12759 stunalloc(fullname);
12762 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12764 entry->cmdtype = CMDNORMAL;
12765 entry->u.index = idx;
12769 cmdp = cmdlookup(name, 1);
12770 cmdp->cmdtype = CMDNORMAL;
12771 cmdp->param.index = idx;
12776 /* We failed. If there was an entry for this command, delete it */
12777 if (cmdp && updatetbl)
12778 delete_cmd_entry();
12780 ash_msg("%s: %s", name, errmsg(e, "not found"));
12781 entry->cmdtype = CMDUNKNOWN;
12786 entry->cmdtype = CMDBUILTIN;
12787 entry->u.cmd = bcmd;
12791 cmdp = cmdlookup(name, 1);
12792 cmdp->cmdtype = CMDBUILTIN;
12793 cmdp->param.cmd = bcmd;
12797 entry->cmdtype = cmdp->cmdtype;
12798 entry->u = cmdp->param;
12803 * The trap builtin.
12805 static int FAST_FUNC
12806 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12810 int signo, exitcode;
12815 for (signo = 0; signo < NSIG; signo++) {
12816 char *tr = trap_ptr[signo];
12818 /* note: bash adds "SIG", but only if invoked
12819 * as "bash". If called as "sh", or if set -o posix,
12820 * then it prints short signal names.
12821 * We are printing short names: */
12822 out1fmt("trap -- %s %s\n",
12824 get_signame(signo));
12825 /* trap_ptr != trap only if we are in special-cased `trap` code.
12826 * In this case, we will exit very soon, no need to free(). */
12827 /* if (trap_ptr != trap && tp[0]) */
12832 if (trap_ptr != trap) {
12845 signo = get_signum(*ap);
12847 /* Mimic bash message exactly */
12848 ash_msg("%s: invalid signal specification", *ap);
12854 if (LONE_DASH(action))
12857 if (action[0]) /* not NULL and not "" and not "-" */
12858 may_have_traps = 1;
12859 action = ckstrdup(action);
12863 trap[signo] = action;
12874 /* ============ Builtins */
12876 #if ENABLE_ASH_HELP
12877 static int FAST_FUNC
12878 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12884 "Built-in commands:\n"
12885 "------------------\n");
12886 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12887 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12888 builtintab[i].name + 1);
12894 # if ENABLE_FEATURE_SH_STANDALONE
12896 const char *a = applet_names;
12898 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12903 while (*a++ != '\0')
12908 newline_and_flush(stdout);
12909 return EXIT_SUCCESS;
12914 static int FAST_FUNC
12915 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12917 show_history(line_input_state);
12918 return EXIT_SUCCESS;
12923 * The export and readonly commands.
12925 static int FAST_FUNC
12926 exportcmd(int argc UNUSED_PARAM, char **argv)
12936 /* "readonly" in bash accepts, but ignores -n.
12937 * We do the same: it saves a conditional in nextopt's param.
12940 while ((opt = nextopt("np")) != '\0') {
12942 flag_off = VEXPORT;
12945 if (argv[0][0] == 'r') {
12947 flag_off = 0; /* readonly ignores -n */
12949 flag_off = ~flag_off;
12951 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12957 p = strchr(name, '=');
12961 vp = *findvar(hashvar(name), name);
12963 vp->flags = ((vp->flags | flag) & flag_off);
12967 setvar(name, p, (flag & flag_off));
12968 } while ((name = *++aptr) != NULL);
12973 /* No arguments. Show the list of exported or readonly vars.
12976 showvars(argv[0], flag, 0);
12981 * Delete a function if it exists.
12984 unsetfunc(const char *name)
12986 struct tblentry *cmdp;
12988 cmdp = cmdlookup(name, 0);
12989 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12990 delete_cmd_entry();
12994 * The unset builtin command. We unset the function before we unset the
12995 * variable to allow a function to be unset when there is a readonly variable
12996 * with the same name.
12998 static int FAST_FUNC
12999 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13006 while ((i = nextopt("vf")) != 0) {
13010 for (ap = argptr; *ap; ap++) {
13023 static const unsigned char timescmd_str[] ALIGN1 = {
13024 ' ', offsetof(struct tms, tms_utime),
13025 '\n', offsetof(struct tms, tms_stime),
13026 ' ', offsetof(struct tms, tms_cutime),
13027 '\n', offsetof(struct tms, tms_cstime),
13030 static int FAST_FUNC
13031 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13033 unsigned long clk_tck, s, t;
13034 const unsigned char *p;
13037 clk_tck = bb_clk_tck();
13042 t = *(clock_t *)(((char *) &buf) + p[1]);
13045 out1fmt("%lum%lu.%03lus%c",
13047 (t * 1000) / clk_tck,
13055 #if ENABLE_FEATURE_SH_MATH
13057 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13058 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13060 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13062 static int FAST_FUNC
13063 letcmd(int argc UNUSED_PARAM, char **argv)
13069 ash_msg_and_raise_error("expression expected");
13071 i = ash_arith(*argv);
13079 * The read builtin. Options:
13080 * -r Do not interpret '\' specially
13081 * -s Turn off echo (tty only)
13082 * -n NCHARS Read NCHARS max
13083 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13084 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13085 * -u FD Read from given FD instead of fd 0
13086 * This uses unbuffered input, which may be avoidable in some cases.
13087 * TODO: bash also has:
13088 * -a ARRAY Read into array[0],[1],etc
13089 * -d DELIM End on DELIM char, not newline
13090 * -e Use line editing (tty only)
13092 static int FAST_FUNC
13093 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13095 char *opt_n = NULL;
13096 char *opt_p = NULL;
13097 char *opt_t = NULL;
13098 char *opt_u = NULL;
13099 int read_flags = 0;
13103 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13112 read_flags |= BUILTIN_READ_SILENT;
13118 read_flags |= BUILTIN_READ_RAW;
13128 /* "read -s" needs to save/restore termios, can't allow ^C
13129 * to jump out of it.
13132 r = shell_builtin_read(setvar0,
13134 bltinlookup("IFS"), /* can be NULL */
13143 if ((uintptr_t)r > 1)
13144 ash_msg_and_raise_error(r);
13146 return (uintptr_t)r;
13149 static int FAST_FUNC
13150 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13152 static const char permuser[3] ALIGN1 = "ogu";
13155 int symbolic_mode = 0;
13157 while (nextopt("S") != '\0') {
13166 if (*argptr == NULL) {
13167 if (symbolic_mode) {
13168 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13175 *p++ = permuser[i];
13177 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13178 if (!(mask & 0400)) *p++ = 'r';
13179 if (!(mask & 0200)) *p++ = 'w';
13180 if (!(mask & 0100)) *p++ = 'x';
13188 out1fmt("%04o\n", mask);
13191 char *modestr = *argptr;
13192 /* numeric umasks are taken as-is */
13193 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13194 if (!isdigit(modestr[0]))
13196 mask = bb_parse_mode(modestr, mask);
13197 if ((unsigned)mask > 0777) {
13198 ash_msg_and_raise_error("illegal mode: %s", modestr);
13200 if (!isdigit(modestr[0]))
13207 static int FAST_FUNC
13208 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13210 return shell_builtin_ulimit(argv);
13213 /* ============ main() and helpers */
13216 * Called to exit the shell.
13225 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13226 save_history(line_input_state);
13228 status = exitstatus;
13229 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13230 if (setjmp(loc.loc)) {
13231 if (exception_type == EXEXIT)
13232 status = exitstatus;
13235 exception_handler = &loc;
13241 /*free(p); - we'll exit soon */
13244 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13245 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13248 flush_stdout_stderr();
13256 /* we will never free this */
13257 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13259 sigmode[SIGCHLD - 1] = S_DFL;
13260 setsignal(SIGCHLD);
13262 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13263 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13265 signal(SIGHUP, SIG_DFL);
13270 struct stat st1, st2;
13273 for (envp = environ; envp && *envp; envp++) {
13274 p = endofname(*envp);
13275 if (p != *envp && *p == '=') {
13276 setvareq(*envp, VEXPORT|VTEXTFIXED);
13280 setvareq((char*)defoptindvar, VTEXTFIXED);
13282 setvar0("PPID", utoa(getppid()));
13283 #if ENABLE_ASH_BASH_COMPAT
13284 p = lookupvar("SHLVL");
13285 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13286 if (!lookupvar("HOSTNAME")) {
13287 struct utsname uts;
13289 setvar0("HOSTNAME", uts.nodename);
13292 p = lookupvar("PWD");
13294 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13295 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13305 //usage:#define ash_trivial_usage
13306 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13307 //usage:#define ash_full_usage "\n\n"
13308 //usage: "Unix shell interpreter"
13311 * Process the shell command line arguments.
13314 procargs(char **argv)
13317 const char *xminusc;
13322 /* if (xargv[0]) - mmm, this is always true! */
13324 for (i = 0; i < NOPTS; i++)
13327 if (options(/*cmdline:*/ 1)) {
13328 /* it already printed err message */
13329 raise_exception(EXERROR);
13333 if (*xargv == NULL) {
13335 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13338 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13342 for (i = 0; i < NOPTS; i++)
13343 if (optlist[i] == 2)
13348 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13353 } else if (!sflag) {
13354 setinputfile(*xargv, 0);
13357 commandname = arg0;
13360 shellparam.p = xargv;
13361 #if ENABLE_ASH_GETOPTS
13362 shellparam.optind = 1;
13363 shellparam.optoff = -1;
13365 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13367 shellparam.nparam++;
13374 * Read /etc/profile, ~/.profile, $ENV.
13377 read_profile(const char *name)
13379 name = expandstr(name);
13380 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13387 * This routine is called when an error or an interrupt occurs in an
13388 * interactive shell and control is returned to the main command loop.
13389 * (In dash, this function is auto-generated by build machinery).
13398 /* from expand.c: */
13401 /* from input.c: */
13402 g_parsefile->left_in_buffer = 0;
13403 g_parsefile->left_in_line = 0; /* clear input buffer */
13406 /* from redir.c: */
13408 popredir(/*drop:*/ 0, /*restore:*/ 0);
13412 static short profile_buf[16384];
13413 extern int etext();
13417 * Main routine. We initialize things, parse the arguments, execute
13418 * profiles if we're a login shell, and then call cmdloop to execute
13419 * commands. The setjmp call sets up the location to jump to when an
13420 * exception occurs. When an exception occurs the variable "state"
13421 * is used to figure out how far we had gotten.
13423 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13424 int ash_main(int argc UNUSED_PARAM, char **argv)
13426 volatile smallint state;
13427 struct jmploc jmploc;
13428 struct stackmark smark;
13430 /* Initialize global data */
13434 #if ENABLE_ASH_ALIAS
13440 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13443 #if ENABLE_FEATURE_EDITING
13444 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13447 if (setjmp(jmploc.loc)) {
13453 e = exception_type;
13455 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13459 newline_and_flush(stderr);
13462 popstackmark(&smark);
13463 FORCE_INT_ON; /* enable interrupts */
13472 exception_handler = &jmploc;
13473 rootpid = getpid();
13476 setstackmark(&smark);
13479 TRACE(("Shell args: "));
13480 trace_puts_args(argv);
13483 if (argv[0] && argv[0][0] == '-')
13489 read_profile("/etc/profile");
13492 hp = lookupvar("HOME");
13494 read_profile("$HOME/.profile");
13500 getuid() == geteuid() && getgid() == getegid() &&
13504 const char *shinit = lookupvar("ENV");
13505 if (shinit != NULL && *shinit != '\0')
13506 read_profile(shinit);
13508 popstackmark(&smark);
13512 /* evalstring pushes parsefile stack.
13513 * Ensure we don't falsely claim that 0 (stdin)
13514 * is one of stacked source fds.
13515 * Testcase: ash -c 'exec 1>&0' must not complain. */
13516 // if (!sflag) g_parsefile->pf_fd = -1;
13517 // ^^ not necessary since now we special-case fd 0
13518 // in is_hidden_fd() to not be considered "hidden fd"
13519 evalstring(minusc, 0);
13522 if (sflag || minusc == NULL) {
13523 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13525 const char *hp = lookupvar("HISTFILE");
13527 hp = lookupvar("HOME");
13529 hp = concat_path_file(hp, ".ash_history");
13530 setvar0("HISTFILE", hp);
13532 hp = lookupvar("HISTFILE");
13536 line_input_state->hist_file = hp;
13537 # if ENABLE_FEATURE_SH_HISTFILESIZE
13538 hp = lookupvar("HISTFILESIZE");
13539 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13543 state4: /* XXX ??? - why isn't this before the "if" statement */
13551 extern void _mcleanup(void);
13555 TRACE(("End of main reached\n"));
13562 * Copyright (c) 1989, 1991, 1993, 1994
13563 * The Regents of the University of California. All rights reserved.
13565 * This code is derived from software contributed to Berkeley by
13566 * Kenneth Almquist.
13568 * Redistribution and use in source and binary forms, with or without
13569 * modification, are permitted provided that the following conditions
13571 * 1. Redistributions of source code must retain the above copyright
13572 * notice, this list of conditions and the following disclaimer.
13573 * 2. Redistributions in binary form must reproduce the above copyright
13574 * notice, this list of conditions and the following disclaimer in the
13575 * documentation and/or other materials provided with the distribution.
13576 * 3. Neither the name of the University nor the names of its contributors
13577 * may be used to endorse or promote products derived from this software
13578 * without specific prior written permission.
13580 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13581 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13582 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13583 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13584 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13585 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13586 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13587 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13588 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13589 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF