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, ...)
1290 ash_vmsg_and_raise(EXERROR, msg, ap);
1295 static void raise_error_syntax(const char *) NORETURN;
1297 raise_error_syntax(const char *msg)
1299 ash_msg_and_raise_error("syntax error: %s", msg);
1303 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1305 ash_msg_and_raise(int cond, const char *msg, ...)
1310 ash_vmsg_and_raise(cond, msg, ap);
1316 * error/warning routines for external builtins
1319 ash_msg(const char *fmt, ...)
1329 * Return a string describing an error. The returned string may be a
1330 * pointer to a static buffer that will be overwritten on the next call.
1331 * Action describes the operation that got the error.
1334 errmsg(int e, const char *em)
1336 if (e == ENOENT || e == ENOTDIR) {
1343 /* ============ Memory allocation */
1346 /* I consider these wrappers nearly useless:
1347 * ok, they return you to nearest exception handler, but
1348 * how much memory do you leak in the process, making
1349 * memory starvation worse?
1352 ckrealloc(void * p, size_t nbytes)
1354 p = realloc(p, nbytes);
1356 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1361 ckmalloc(size_t nbytes)
1363 return ckrealloc(NULL, nbytes);
1367 ckzalloc(size_t nbytes)
1369 return memset(ckmalloc(nbytes), 0, nbytes);
1373 ckstrdup(const char *s)
1375 char *p = strdup(s);
1377 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1381 /* Using bbox equivalents. They exit if out of memory */
1382 # define ckrealloc xrealloc
1383 # define ckmalloc xmalloc
1384 # define ckzalloc xzalloc
1385 # define ckstrdup xstrdup
1389 * It appears that grabstackstr() will barf with such alignments
1390 * because stalloc() will return a string allocated in a new stackblock.
1392 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1394 /* Most machines require the value returned from malloc to be aligned
1395 * in some way. The following macro will get this right
1396 * on many machines. */
1397 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1398 /* Minimum size of a block */
1399 MINSIZE = SHELL_ALIGN(504),
1402 struct stack_block {
1403 struct stack_block *prev;
1404 char space[MINSIZE];
1408 struct stack_block *stackp;
1414 struct globals_memstack {
1415 struct stack_block *g_stackp; // = &stackbase;
1416 char *g_stacknxt; // = stackbase.space;
1417 char *sstrend; // = stackbase.space + MINSIZE;
1418 size_t g_stacknleft; // = MINSIZE;
1419 struct stack_block stackbase;
1421 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1422 #define G_memstack (*ash_ptr_to_globals_memstack)
1423 #define g_stackp (G_memstack.g_stackp )
1424 #define g_stacknxt (G_memstack.g_stacknxt )
1425 #define sstrend (G_memstack.sstrend )
1426 #define g_stacknleft (G_memstack.g_stacknleft)
1427 #define stackbase (G_memstack.stackbase )
1428 #define INIT_G_memstack() do { \
1429 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1431 g_stackp = &stackbase; \
1432 g_stacknxt = stackbase.space; \
1433 g_stacknleft = MINSIZE; \
1434 sstrend = stackbase.space + MINSIZE; \
1438 #define stackblock() ((void *)g_stacknxt)
1439 #define stackblocksize() g_stacknleft
1442 * Parse trees for commands are allocated in lifo order, so we use a stack
1443 * to make this more efficient, and also to avoid all sorts of exception
1444 * handling code to handle interrupts in the middle of a parse.
1446 * The size 504 was chosen because the Ultrix malloc handles that size
1450 stalloc(size_t nbytes)
1455 aligned = SHELL_ALIGN(nbytes);
1456 if (aligned > g_stacknleft) {
1459 struct stack_block *sp;
1461 blocksize = aligned;
1462 if (blocksize < MINSIZE)
1463 blocksize = MINSIZE;
1464 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1465 if (len < blocksize)
1466 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1469 sp->prev = g_stackp;
1470 g_stacknxt = sp->space;
1471 g_stacknleft = blocksize;
1472 sstrend = g_stacknxt + blocksize;
1477 g_stacknxt += aligned;
1478 g_stacknleft -= aligned;
1483 stzalloc(size_t nbytes)
1485 return memset(stalloc(nbytes), 0, nbytes);
1492 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1493 write(STDERR_FILENO, "stunalloc\n", 10);
1497 g_stacknleft += g_stacknxt - (char *)p;
1502 * Like strdup but works with the ash stack.
1505 sstrdup(const char *p)
1507 size_t len = strlen(p) + 1;
1508 return memcpy(stalloc(len), p, len);
1512 grabstackblock(size_t len)
1518 pushstackmark(struct stackmark *mark, size_t len)
1520 mark->stackp = g_stackp;
1521 mark->stacknxt = g_stacknxt;
1522 mark->stacknleft = g_stacknleft;
1523 grabstackblock(len);
1527 setstackmark(struct stackmark *mark)
1529 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1533 popstackmark(struct stackmark *mark)
1535 struct stack_block *sp;
1541 while (g_stackp != mark->stackp) {
1543 g_stackp = sp->prev;
1546 g_stacknxt = mark->stacknxt;
1547 g_stacknleft = mark->stacknleft;
1548 sstrend = mark->stacknxt + mark->stacknleft;
1553 * When the parser reads in a string, it wants to stick the string on the
1554 * stack and only adjust the stack pointer when it knows how big the
1555 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1556 * of space on top of the stack and stackblocklen returns the length of
1557 * this block. Growstackblock will grow this space by at least one byte,
1558 * possibly moving it (like realloc). Grabstackblock actually allocates the
1559 * part of the block that has been used.
1562 growstackblock(void)
1566 newlen = g_stacknleft * 2;
1567 if (newlen < g_stacknleft)
1568 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1572 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1573 struct stack_block *sp;
1574 struct stack_block *prevstackp;
1579 prevstackp = sp->prev;
1580 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1581 sp = ckrealloc(sp, grosslen);
1582 sp->prev = prevstackp;
1584 g_stacknxt = sp->space;
1585 g_stacknleft = newlen;
1586 sstrend = sp->space + newlen;
1589 char *oldspace = g_stacknxt;
1590 size_t oldlen = g_stacknleft;
1591 char *p = stalloc(newlen);
1593 /* free the space we just allocated */
1594 g_stacknxt = memcpy(p, oldspace, oldlen);
1595 g_stacknleft += newlen;
1600 * The following routines are somewhat easier to use than the above.
1601 * The user declares a variable of type STACKSTR, which may be declared
1602 * to be a register. The macro STARTSTACKSTR initializes things. Then
1603 * the user uses the macro STPUTC to add characters to the string. In
1604 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1605 * grown as necessary. When the user is done, she can just leave the
1606 * string there and refer to it using stackblock(). Or she can allocate
1607 * the space for it using grabstackstr(). If it is necessary to allow
1608 * someone else to use the stack temporarily and then continue to grow
1609 * the string, the user should use grabstack to allocate the space, and
1610 * then call ungrabstr(p) to return to the previous mode of operation.
1612 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1613 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1614 * is space for at least one character.
1619 size_t len = stackblocksize();
1621 return (char *)stackblock() + len;
1625 * Called from CHECKSTRSPACE.
1628 makestrspace(size_t newlen, char *p)
1630 size_t len = p - g_stacknxt;
1636 size = stackblocksize();
1638 if (nleft >= newlen)
1642 return (char *)stackblock() + len;
1646 stack_nputstr(const char *s, size_t n, char *p)
1648 p = makestrspace(n, p);
1649 p = (char *)memcpy(p, s, n) + n;
1654 stack_putstr(const char *s, char *p)
1656 return stack_nputstr(s, strlen(s), p);
1660 _STPUTC(int c, char *p)
1668 #define STARTSTACKSTR(p) ((p) = stackblock())
1669 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1670 #define CHECKSTRSPACE(n, p) do { \
1673 size_t m = sstrend - q; \
1675 (p) = makestrspace(l, q); \
1677 #define USTPUTC(c, p) (*(p)++ = (c))
1678 #define STACKSTRNUL(p) do { \
1679 if ((p) == sstrend) \
1680 (p) = growstackstr(); \
1683 #define STUNPUTC(p) (--(p))
1684 #define STTOPC(p) ((p)[-1])
1685 #define STADJUST(amount, p) ((p) += (amount))
1687 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1688 #define ungrabstackstr(s, p) stunalloc(s)
1689 #define stackstrend() ((void *)sstrend)
1692 /* ============ String helpers */
1695 * prefix -- see if pfx is a prefix of string.
1698 prefix(const char *string, const char *pfx)
1701 if (*pfx++ != *string++)
1704 return (char *) string;
1708 * Check for a valid number. This should be elsewhere.
1711 is_number(const char *p)
1716 } while (*++p != '\0');
1721 * Convert a string of digits to an integer, printing an error message on
1725 number(const char *s)
1728 ash_msg_and_raise_error(msg_illnum, s);
1733 * Produce a possibly single quoted string suitable as input to the shell.
1734 * The return string is allocated on the stack.
1737 single_quote(const char *s)
1747 len = strchrnul(s, '\'') - s;
1749 q = p = makestrspace(len + 3, p);
1752 q = (char *)memcpy(q, s, len) + len;
1761 do len++; while (*++s == '\'');
1763 q = p = makestrspace(len + 3, p);
1766 q = (char *)memcpy(q, s - len, len) + len;
1774 return stackblock();
1778 /* ============ nextopt */
1780 static char **argptr; /* argument list for builtin commands */
1781 static char *optionarg; /* set by nextopt (like getopt) */
1782 static char *optptr; /* used by nextopt */
1785 * XXX - should get rid of. Have all builtins use getopt(3).
1786 * The library getopt must have the BSD extension static variable
1787 * "optreset", otherwise it can't be used within the shell safely.
1789 * Standard option processing (a la getopt) for builtin routines.
1790 * The only argument that is passed to nextopt is the option string;
1791 * the other arguments are unnecessary. It returns the character,
1792 * or '\0' on end of input.
1795 nextopt(const char *optstring)
1802 if (p == NULL || *p == '\0') {
1803 /* We ate entire "-param", take next one */
1809 if (*++p == '\0') /* just "-" ? */
1812 if (LONE_DASH(p)) /* "--" ? */
1814 /* p => next "-param" */
1816 /* p => some option char in the middle of a "-param" */
1818 for (q = optstring; *q != c;) {
1820 ash_msg_and_raise_error("illegal option -%c", c);
1828 ash_msg_and_raise_error("no arg for -%c option", c);
1838 /* ============ Shell variables */
1841 * The parsefile structure pointed to by the global variable parsefile
1842 * contains information about the current file being read.
1845 int nparam; /* # of positional parameters (without $0) */
1846 #if ENABLE_ASH_GETOPTS
1847 int optind; /* next parameter to be processed by getopts */
1848 int optoff; /* used by getopts */
1850 unsigned char malloced; /* if parameter list dynamically allocated */
1851 char **p; /* parameter list */
1855 * Free the list of positional parameters.
1858 freeparam(volatile struct shparam *param)
1860 if (param->malloced) {
1862 ap = ap1 = param->p;
1869 #if ENABLE_ASH_GETOPTS
1870 static void FAST_FUNC getoptsreset(const char *value);
1874 struct var *next; /* next entry in hash list */
1875 int flags; /* flags are defined above */
1876 const char *var_text; /* name=value */
1877 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1878 /* the variable gets set/unset */
1882 struct localvar *next; /* next local variable in list */
1883 struct var *vp; /* the variable that was made local */
1884 int flags; /* saved flags */
1885 const char *text; /* saved text */
1889 #define VEXPORT 0x01 /* variable is exported */
1890 #define VREADONLY 0x02 /* variable cannot be modified */
1891 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1892 #define VTEXTFIXED 0x08 /* text is statically allocated */
1893 #define VSTACK 0x10 /* text is allocated on the stack */
1894 #define VUNSET 0x20 /* the variable is not set */
1895 #define VNOFUNC 0x40 /* don't call the callback function */
1896 #define VNOSET 0x80 /* do not set variable - just readonly test */
1897 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1898 #if ENABLE_ASH_RANDOM_SUPPORT
1899 # define VDYNAMIC 0x200 /* dynamic variable */
1905 /* Need to be before varinit_data[] */
1906 #if ENABLE_LOCALE_SUPPORT
1907 static void FAST_FUNC
1908 change_lc_all(const char *value)
1910 if (value && *value != '\0')
1911 setlocale(LC_ALL, value);
1913 static void FAST_FUNC
1914 change_lc_ctype(const char *value)
1916 if (value && *value != '\0')
1917 setlocale(LC_CTYPE, value);
1921 static void chkmail(void);
1922 static void changemail(const char *var_value) FAST_FUNC;
1924 # define chkmail() ((void)0)
1926 static void changepath(const char *) FAST_FUNC;
1927 #if ENABLE_ASH_RANDOM_SUPPORT
1928 static void change_random(const char *) FAST_FUNC;
1931 static const struct {
1933 const char *var_text;
1934 void (*var_func)(const char *) FAST_FUNC;
1935 } varinit_data[] = {
1937 * Note: VEXPORT would not work correctly here for NOFORK applets:
1938 * some environment strings may be constant.
1940 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1942 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1943 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1945 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1946 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1947 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1948 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1949 #if ENABLE_ASH_GETOPTS
1950 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1952 #if ENABLE_ASH_RANDOM_SUPPORT
1953 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1955 #if ENABLE_LOCALE_SUPPORT
1956 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1957 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1959 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1960 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1966 struct globals_var {
1967 struct shparam shellparam; /* $@ current positional parameters */
1968 struct redirtab *redirlist;
1969 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1970 struct var *vartab[VTABSIZE];
1971 struct var varinit[ARRAY_SIZE(varinit_data)];
1973 extern struct globals_var *const ash_ptr_to_globals_var;
1974 #define G_var (*ash_ptr_to_globals_var)
1975 #define shellparam (G_var.shellparam )
1976 //#define redirlist (G_var.redirlist )
1977 #define preverrout_fd (G_var.preverrout_fd)
1978 #define vartab (G_var.vartab )
1979 #define varinit (G_var.varinit )
1980 #define INIT_G_var() do { \
1982 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1984 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1985 varinit[i].flags = varinit_data[i].flags; \
1986 varinit[i].var_text = varinit_data[i].var_text; \
1987 varinit[i].var_func = varinit_data[i].var_func; \
1991 #define vifs varinit[0]
1993 # define vmail (&vifs)[1]
1994 # define vmpath (&vmail)[1]
1995 # define vpath (&vmpath)[1]
1997 # define vpath (&vifs)[1]
1999 #define vps1 (&vpath)[1]
2000 #define vps2 (&vps1)[1]
2001 #define vps4 (&vps2)[1]
2002 #if ENABLE_ASH_GETOPTS
2003 # define voptind (&vps4)[1]
2004 # if ENABLE_ASH_RANDOM_SUPPORT
2005 # define vrandom (&voptind)[1]
2008 # if ENABLE_ASH_RANDOM_SUPPORT
2009 # define vrandom (&vps4)[1]
2014 * The following macros access the values of the above variables.
2015 * They have to skip over the name. They return the null string
2016 * for unset variables.
2018 #define ifsval() (vifs.var_text + 4)
2019 #define ifsset() ((vifs.flags & VUNSET) == 0)
2021 # define mailval() (vmail.var_text + 5)
2022 # define mpathval() (vmpath.var_text + 9)
2023 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2025 #define pathval() (vpath.var_text + 5)
2026 #define ps1val() (vps1.var_text + 4)
2027 #define ps2val() (vps2.var_text + 4)
2028 #define ps4val() (vps4.var_text + 4)
2029 #if ENABLE_ASH_GETOPTS
2030 # define optindval() (voptind.var_text + 7)
2033 #if ENABLE_ASH_GETOPTS
2034 static void FAST_FUNC
2035 getoptsreset(const char *value)
2037 shellparam.optind = number(value) ?: 1;
2038 shellparam.optoff = -1;
2043 * Compares two strings up to the first = or '\0'. The first
2044 * string must be terminated by '='; the second may be terminated by
2045 * either '=' or '\0'.
2048 varcmp(const char *p, const char *q)
2052 while ((c = *p) == (d = *q)) {
2053 if (c == '\0' || c == '=')
2067 * Find the appropriate entry in the hash table from the name.
2069 static struct var **
2070 hashvar(const char *p)
2074 hashval = ((unsigned char) *p) << 4;
2075 while (*p && *p != '=')
2076 hashval += (unsigned char) *p++;
2077 return &vartab[hashval % VTABSIZE];
2081 vpcmp(const void *a, const void *b)
2083 return varcmp(*(const char **)a, *(const char **)b);
2087 * This routine initializes the builtin variables.
2097 * PS1 depends on uid
2099 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2100 vps1.var_text = "PS1=\\w \\$ ";
2103 vps1.var_text = "PS1=# ";
2106 end = vp + ARRAY_SIZE(varinit);
2108 vpp = hashvar(vp->var_text);
2111 } while (++vp < end);
2114 static struct var **
2115 findvar(struct var **vpp, const char *name)
2117 for (; *vpp; vpp = &(*vpp)->next) {
2118 if (varcmp((*vpp)->var_text, name) == 0) {
2126 * Find the value of a variable. Returns NULL if not set.
2128 static const char* FAST_FUNC
2129 lookupvar(const char *name)
2133 v = *findvar(hashvar(name), name);
2135 #if ENABLE_ASH_RANDOM_SUPPORT
2137 * Dynamic variables are implemented roughly the same way they are
2138 * in bash. Namely, they're "special" so long as they aren't unset.
2139 * As soon as they're unset, they're no longer dynamic, and dynamic
2140 * lookup will no longer happen at that point. -- PFM.
2142 if (v->flags & VDYNAMIC)
2145 if (!(v->flags & VUNSET))
2146 return var_end(v->var_text);
2151 #if ENABLE_UNICODE_SUPPORT
2153 reinit_unicode_for_ash(void)
2155 /* Unicode support should be activated even if LANG is set
2156 * _during_ shell execution, not only if it was set when
2157 * shell was started. Therefore, re-check LANG every time:
2159 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2160 || ENABLE_UNICODE_USING_LOCALE
2162 const char *s = lookupvar("LC_ALL");
2163 if (!s) s = lookupvar("LC_CTYPE");
2164 if (!s) s = lookupvar("LANG");
2169 # define reinit_unicode_for_ash() ((void)0)
2173 * Search the environment of a builtin command.
2176 bltinlookup(const char *name)
2180 for (sp = cmdenviron; sp; sp = sp->next) {
2181 if (varcmp(sp->text, name) == 0)
2182 return var_end(sp->text);
2184 return lookupvar(name);
2188 * Same as setvar except that the variable and value are passed in
2189 * the first argument as name=value. Since the first argument will
2190 * be actually stored in the table, it should not be a string that
2192 * Called with interrupts off.
2195 setvareq(char *s, int flags)
2197 struct var *vp, **vpp;
2200 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2201 vp = *findvar(vpp, s);
2203 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2206 if (flags & VNOSAVE)
2210 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2216 if (vp->var_func && !(flags & VNOFUNC))
2217 vp->var_func(var_end(s));
2219 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2220 free((char*)vp->var_text);
2222 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2224 /* variable s is not found */
2227 vp = ckzalloc(sizeof(*vp));
2229 /*vp->func = NULL; - ckzalloc did it */
2232 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2239 * Set the value of a variable. The flags argument is ored with the
2240 * flags of the variable. If val is NULL, the variable is unset.
2243 setvar(const char *name, const char *val, int flags)
2251 q = endofname(name);
2252 p = strchrnul(q, '=');
2254 if (!namelen || p != q)
2255 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2260 vallen = strlen(val);
2264 nameeq = ckmalloc(namelen + vallen + 2);
2265 p = memcpy(nameeq, name, namelen) + namelen;
2268 p = memcpy(p, val, vallen) + vallen;
2271 setvareq(nameeq, flags | VNOSAVE);
2275 static void FAST_FUNC
2276 setvar0(const char *name, const char *val)
2278 setvar(name, val, 0);
2282 * Unset the specified variable.
2285 unsetvar(const char *s)
2291 vpp = findvar(hashvar(s), s);
2295 int flags = vp->flags;
2298 if (flags & VREADONLY)
2300 #if ENABLE_ASH_RANDOM_SUPPORT
2301 vp->flags &= ~VDYNAMIC;
2305 if ((flags & VSTRFIXED) == 0) {
2307 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2308 free((char*)vp->var_text);
2314 vp->flags &= ~VEXPORT;
2324 * Process a linked list of variable assignments.
2327 listsetvar(struct strlist *list_set_var, int flags)
2329 struct strlist *lp = list_set_var;
2335 setvareq(lp->text, flags);
2342 * Generate a list of variables satisfying the given conditions.
2345 listvars(int on, int off, char ***end)
2356 for (vp = *vpp; vp; vp = vp->next) {
2357 if ((vp->flags & mask) == on) {
2358 if (ep == stackstrend())
2359 ep = growstackstr();
2360 *ep++ = (char*)vp->var_text;
2363 } while (++vpp < vartab + VTABSIZE);
2364 if (ep == stackstrend())
2365 ep = growstackstr();
2369 return grabstackstr(ep);
2373 /* ============ Path search helper
2375 * The variable path (passed by reference) should be set to the start
2376 * of the path before the first call; path_advance will update
2377 * this value as it proceeds. Successive calls to path_advance will return
2378 * the possible path expansions in sequence. If an option (indicated by
2379 * a percent sign) appears in the path entry then the global variable
2380 * pathopt will be set to point to it; otherwise pathopt will be set to
2383 static const char *pathopt; /* set by path_advance */
2386 path_advance(const char **path, const char *name)
2396 for (p = start; *p && *p != ':' && *p != '%'; p++)
2398 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2399 while (stackblocksize() < len)
2403 memcpy(q, start, p - start);
2411 while (*p && *p != ':')
2418 return stalloc(len);
2422 /* ============ Prompt */
2424 static smallint doprompt; /* if set, prompt the user */
2425 static smallint needprompt; /* true if interactive and at start of line */
2427 #if ENABLE_FEATURE_EDITING
2428 static line_input_t *line_input_state;
2429 static const char *cmdedit_prompt;
2431 putprompt(const char *s)
2433 if (ENABLE_ASH_EXPAND_PRMT) {
2434 free((char*)cmdedit_prompt);
2435 cmdedit_prompt = ckstrdup(s);
2442 putprompt(const char *s)
2448 #if ENABLE_ASH_EXPAND_PRMT
2449 /* expandstr() needs parsing machinery, so it is far away ahead... */
2450 static const char *expandstr(const char *ps);
2452 #define expandstr(s) s
2456 setprompt_if(smallint do_set, int whichprompt)
2459 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2466 switch (whichprompt) {
2476 #if ENABLE_ASH_EXPAND_PRMT
2477 pushstackmark(&smark, stackblocksize());
2479 putprompt(expandstr(prompt));
2480 #if ENABLE_ASH_EXPAND_PRMT
2481 popstackmark(&smark);
2486 /* ============ The cd and pwd commands */
2488 #define CD_PHYSICAL 1
2498 while ((i = nextopt("LP")) != '\0') {
2500 flags ^= CD_PHYSICAL;
2509 * Update curdir (the name of the current directory) in response to a
2513 updatepwd(const char *dir)
2520 cdcomppath = sstrdup(dir);
2523 if (curdir == nullstr)
2525 new = stack_putstr(curdir, new);
2527 new = makestrspace(strlen(dir) + 2, new);
2528 lim = (char *)stackblock() + 1;
2532 if (new > lim && *lim == '/')
2537 if (dir[1] == '/' && dir[2] != '/') {
2543 p = strtok(cdcomppath, "/");
2547 if (p[1] == '.' && p[2] == '\0') {
2559 new = stack_putstr(p, new);
2562 p = strtok(NULL, "/");
2567 return stackblock();
2571 * Find out what the current directory is. If we already know the current
2572 * directory, this routine returns immediately.
2577 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2578 return dir ? dir : nullstr;
2582 setpwd(const char *val, int setold)
2586 oldcur = dir = curdir;
2589 setvar("OLDPWD", oldcur, VEXPORT);
2592 if (physdir != nullstr) {
2593 if (physdir != oldcur)
2597 if (oldcur == val || !val) {
2603 dir = ckstrdup(val);
2604 if (oldcur != dir && oldcur != nullstr) {
2609 setvar("PWD", dir, VEXPORT);
2612 static void hashcd(void);
2615 * Actually do the chdir. We also call hashcd to let other routines
2616 * know that the current directory has changed.
2619 docd(const char *dest, int flags)
2621 const char *dir = NULL;
2624 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2627 if (!(flags & CD_PHYSICAL)) {
2628 dir = updatepwd(dest);
2642 static int FAST_FUNC
2643 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2655 dest = bltinlookup("HOME");
2656 else if (LONE_DASH(dest)) {
2657 dest = bltinlookup("OLDPWD");
2679 path = bltinlookup("CDPATH");
2682 p = path_advance(&path, dest);
2683 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2687 if (!docd(p, flags))
2698 ash_msg_and_raise_error("can't cd to %s", dest);
2701 if (flags & CD_PRINT)
2702 out1fmt("%s\n", curdir);
2706 static int FAST_FUNC
2707 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2710 const char *dir = curdir;
2714 if (physdir == nullstr)
2718 out1fmt("%s\n", dir);
2723 /* ============ ... */
2726 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2728 /* Syntax classes */
2729 #define CWORD 0 /* character is nothing special */
2730 #define CNL 1 /* newline character */
2731 #define CBACK 2 /* a backslash character */
2732 #define CSQUOTE 3 /* single quote */
2733 #define CDQUOTE 4 /* double quote */
2734 #define CENDQUOTE 5 /* a terminating quote */
2735 #define CBQUOTE 6 /* backwards single quote */
2736 #define CVAR 7 /* a dollar sign */
2737 #define CENDVAR 8 /* a '}' character */
2738 #define CLP 9 /* a left paren in arithmetic */
2739 #define CRP 10 /* a right paren in arithmetic */
2740 #define CENDFILE 11 /* end of file */
2741 #define CCTL 12 /* like CWORD, except it must be escaped */
2742 #define CSPCL 13 /* these terminate a word */
2743 #define CIGN 14 /* character should be ignored */
2746 #if ENABLE_ASH_ALIAS
2750 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2752 #if ENABLE_FEATURE_SH_MATH
2753 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2755 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2757 static const uint16_t S_I_T[] ALIGN2 = {
2758 #if ENABLE_ASH_ALIAS
2759 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2761 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2762 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2763 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2764 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2765 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2766 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2767 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2768 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2769 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2770 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2771 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2772 #if !USE_SIT_FUNCTION
2773 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2774 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2775 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2779 /* Constants below must match table above */
2781 #if ENABLE_ASH_ALIAS
2782 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2784 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2785 CNL_CNL_CNL_CNL , /* 2 */
2786 CWORD_CCTL_CCTL_CWORD , /* 3 */
2787 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2788 CVAR_CVAR_CWORD_CVAR , /* 5 */
2789 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2790 CSPCL_CWORD_CWORD_CLP , /* 7 */
2791 CSPCL_CWORD_CWORD_CRP , /* 8 */
2792 CBACK_CBACK_CCTL_CBACK , /* 9 */
2793 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2794 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2795 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2796 CWORD_CWORD_CWORD_CWORD , /* 13 */
2797 CCTL_CCTL_CCTL_CCTL , /* 14 */
2800 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2801 * caller must ensure proper cast on it if c is *char_ptr!
2803 /* Values for syntax param */
2804 #define BASESYNTAX 0 /* not in quotes */
2805 #define DQSYNTAX 1 /* in double quotes */
2806 #define SQSYNTAX 2 /* in single quotes */
2807 #define ARISYNTAX 3 /* in arithmetic */
2808 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2810 #if USE_SIT_FUNCTION
2813 SIT(int c, int syntax)
2815 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2816 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2818 * This causes '/' to be prepended with CTLESC in dquoted string,
2819 * making "./file"* treated incorrectly because we feed
2820 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2821 * The "homegrown" glob implementation is okay with that,
2822 * but glibc one isn't. With '/' always treated as CWORD,
2825 # if ENABLE_ASH_ALIAS
2826 static const uint8_t syntax_index_table[] ALIGN1 = {
2827 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2828 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2829 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2833 static const uint8_t syntax_index_table[] ALIGN1 = {
2834 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2835 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2836 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2845 # if ENABLE_ASH_ALIAS
2851 /* Cast is purely for paranoia here,
2852 * just in case someone passed signed char to us */
2853 if ((unsigned char)c >= CTL_FIRST
2854 && (unsigned char)c <= CTL_LAST
2858 s = strchrnul(spec_symbls, c);
2861 indx = syntax_index_table[s - spec_symbls];
2863 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2866 #else /* !USE_SIT_FUNCTION */
2868 static const uint8_t syntax_index_table[] ALIGN1 = {
2869 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2870 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2880 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2881 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2903 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2904 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2905 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2907 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2910 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2911 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2912 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2915 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2916 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2917 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2918 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2931 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2932 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2933 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2934 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2964 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2968 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2996 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2997 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2998 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2999 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3001 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3002 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3003 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3004 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3005 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3006 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3007 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3008 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3127 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3128 # if ENABLE_ASH_ALIAS
3129 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3134 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3135 #else /* debug version, caught one signed char bug */
3136 # define SIT(c, syntax) \
3138 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3139 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3140 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3141 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3142 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3146 #endif /* !USE_SIT_FUNCTION */
3149 /* ============ Alias handling */
3151 #if ENABLE_ASH_ALIAS
3153 #define ALIASINUSE 1
3164 static struct alias **atab; // [ATABSIZE];
3165 #define INIT_G_alias() do { \
3166 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3170 static struct alias **
3171 __lookupalias(const char *name)
3173 unsigned int hashval;
3180 ch = (unsigned char)*p;
3184 ch = (unsigned char)*++p;
3186 app = &atab[hashval % ATABSIZE];
3188 for (; *app; app = &(*app)->next) {
3189 if (strcmp(name, (*app)->name) == 0) {
3197 static struct alias *
3198 lookupalias(const char *name, int check)
3200 struct alias *ap = *__lookupalias(name);
3202 if (check && ap && (ap->flag & ALIASINUSE))
3207 static struct alias *
3208 freealias(struct alias *ap)
3212 if (ap->flag & ALIASINUSE) {
3213 ap->flag |= ALIASDEAD;
3225 setalias(const char *name, const char *val)
3227 struct alias *ap, **app;
3229 app = __lookupalias(name);
3233 if (!(ap->flag & ALIASINUSE)) {
3236 ap->val = ckstrdup(val);
3237 ap->flag &= ~ALIASDEAD;
3240 ap = ckzalloc(sizeof(struct alias));
3241 ap->name = ckstrdup(name);
3242 ap->val = ckstrdup(val);
3243 /*ap->flag = 0; - ckzalloc did it */
3244 /*ap->next = NULL;*/
3251 unalias(const char *name)
3255 app = __lookupalias(name);
3259 *app = freealias(*app);
3270 struct alias *ap, **app;
3274 for (i = 0; i < ATABSIZE; i++) {
3276 for (ap = *app; ap; ap = *app) {
3277 *app = freealias(*app);
3287 printalias(const struct alias *ap)
3289 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3293 * TODO - sort output
3295 static int FAST_FUNC
3296 aliascmd(int argc UNUSED_PARAM, char **argv)
3305 for (i = 0; i < ATABSIZE; i++) {
3306 for (ap = atab[i]; ap; ap = ap->next) {
3312 while ((n = *++argv) != NULL) {
3313 v = strchr(n+1, '=');
3314 if (v == NULL) { /* n+1: funny ksh stuff */
3315 ap = *__lookupalias(n);
3317 fprintf(stderr, "%s: %s not found\n", "alias", n);
3330 static int FAST_FUNC
3331 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3335 while ((i = nextopt("a")) != '\0') {
3341 for (i = 0; *argptr; argptr++) {
3342 if (unalias(*argptr)) {
3343 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3351 #endif /* ASH_ALIAS */
3354 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3357 #define FORK_NOJOB 2
3359 /* mode flags for showjob(s) */
3360 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3361 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3362 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3363 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3366 * A job structure contains information about a job. A job is either a
3367 * single process or a set of processes contained in a pipeline. In the
3368 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3372 pid_t ps_pid; /* process id */
3373 int ps_status; /* last process status from wait() */
3374 char *ps_cmd; /* text of command being run */
3378 struct procstat ps0; /* status of process */
3379 struct procstat *ps; /* status or processes when more than one */
3381 int stopstatus; /* status of a stopped job */
3384 nprocs: 16, /* number of processes */
3386 #define JOBRUNNING 0 /* at least one proc running */
3387 #define JOBSTOPPED 1 /* all procs are stopped */
3388 #define JOBDONE 2 /* all procs are completed */
3390 sigint: 1, /* job was killed by SIGINT */
3391 jobctl: 1, /* job running under job control */
3393 waited: 1, /* true if this entry has been waited for */
3394 used: 1, /* true if this entry is in used */
3395 changed: 1; /* true if status has changed */
3396 struct job *prev_job; /* previous job */
3399 static struct job *makejob(/*union node *,*/ int);
3400 static int forkshell(struct job *, union node *, int);
3401 static int waitforjob(struct job *);
3404 enum { doing_jobctl = 0 };
3405 #define setjobctl(on) do {} while (0)
3407 static smallint doing_jobctl; //references:8
3408 static void setjobctl(int);
3415 ignoresig(int signo)
3417 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3418 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3419 /* No, need to do it */
3420 signal(signo, SIG_IGN);
3422 sigmode[signo - 1] = S_HARD_IGN;
3426 * Only one usage site - in setsignal()
3429 signal_handler(int signo)
3431 if (signo == SIGCHLD) {
3437 gotsig[signo - 1] = 1;
3438 pending_sig = signo;
3440 if (signo == SIGINT && !trap[SIGINT]) {
3441 if (!suppress_int) {
3443 raise_interrupt(); /* does not return */
3450 * Set the signal handler for the specified signal. The routine figures
3451 * out what it should be set to.
3454 setsignal(int signo)
3457 char cur_act, new_act;
3458 struct sigaction act;
3462 if (t != NULL) { /* trap for this sig is set */
3464 if (t[0] == '\0') /* trap is "": ignore this sig */
3468 if (rootshell && new_act == S_DFL) {
3471 if (iflag || minusc || sflag == 0)
3480 * "In all cases, bash ignores SIGQUIT. Non-builtin
3481 * commands run by bash have signal handlers
3482 * set to the values inherited by the shell
3483 * from its parent". */
3499 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3500 //whereas we have to restore it to what shell got on entry
3501 //from the parent. See comment above
3503 if (signo == SIGCHLD)
3506 t = &sigmode[signo - 1];
3509 /* current setting is not yet known */
3510 if (sigaction(signo, NULL, &act)) {
3511 /* pretend it worked; maybe we should give a warning,
3512 * but other shells don't. We don't alter sigmode,
3513 * so we retry every time.
3514 * btw, in Linux it never fails. --vda */
3517 if (act.sa_handler == SIG_IGN) {
3518 cur_act = S_HARD_IGN;
3520 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3522 cur_act = S_IGN; /* don't hard ignore these */
3526 if (cur_act == S_HARD_IGN || cur_act == new_act)
3529 act.sa_handler = SIG_DFL;
3532 act.sa_handler = signal_handler;
3535 act.sa_handler = SIG_IGN;
3539 /* flags and mask matter only if !DFL and !IGN, but we do it
3540 * for all cases for more deterministic behavior:
3543 sigfillset(&act.sa_mask);
3545 sigaction_set(signo, &act);
3550 /* mode flags for set_curjob */
3551 #define CUR_DELETE 2
3552 #define CUR_RUNNING 1
3553 #define CUR_STOPPED 0
3556 /* pgrp of shell on invocation */
3557 static int initialpgrp; //references:2
3558 static int ttyfd = -1; //5
3561 static struct job *jobtab; //5
3563 static unsigned njobs; //4
3565 static struct job *curjob; //lots
3566 /* number of presumed living untracked jobs */
3567 static int jobless; //4
3570 set_curjob(struct job *jp, unsigned mode)
3573 struct job **jpp, **curp;
3575 /* first remove from list */
3576 jpp = curp = &curjob;
3581 jpp = &jp1->prev_job;
3583 *jpp = jp1->prev_job;
3585 /* Then re-insert in correct position */
3593 /* job being deleted */
3596 /* newly created job or backgrounded job,
3597 * put after all stopped jobs.
3602 if (!jp1 || jp1->state != JOBSTOPPED)
3605 jpp = &jp1->prev_job;
3611 /* newly stopped job - becomes curjob */
3612 jp->prev_job = *jpp;
3620 jobno(const struct job *jp)
3622 return jp - jobtab + 1;
3627 * Convert a job name to a job structure.
3630 #define getjob(name, getctl) getjob(name)
3633 getjob(const char *name, int getctl)
3637 const char *err_msg = "%s: no such job";
3641 char *(*match)(const char *, const char *);
3656 if (c == '+' || c == '%') {
3658 err_msg = "No current job";
3664 err_msg = "No previous job";
3674 if (num > 0 && num <= njobs) {
3675 jp = jobtab + num - 1;
3690 if (match(jp->ps[0].ps_cmd, p)) {
3694 err_msg = "%s: ambiguous";
3704 err_msg = "job %s not created under job control";
3705 if (getctl && jp->jobctl == 0)
3710 ash_msg_and_raise_error(err_msg, name);
3714 * Mark a job structure as unused.
3717 freejob(struct job *jp)
3719 struct procstat *ps;
3723 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3724 if (ps->ps_cmd != nullstr)
3727 if (jp->ps != &jp->ps0)
3730 set_curjob(jp, CUR_DELETE);
3736 xtcsetpgrp(int fd, pid_t pgrp)
3738 if (tcsetpgrp(fd, pgrp))
3739 ash_msg_and_raise_error("can't set tty process group (%m)");
3743 * Turn job control on and off.
3745 * Note: This code assumes that the third arg to ioctl is a character
3746 * pointer, which is true on Berkeley systems but not System V. Since
3747 * System V doesn't have job control yet, this isn't a problem now.
3749 * Called with interrupts off.
3757 if (on == doing_jobctl || rootshell == 0)
3761 ofd = fd = open(_PATH_TTY, O_RDWR);
3763 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3764 * That sometimes helps to acquire controlling tty.
3765 * Obviously, a workaround for bugs when someone
3766 * failed to provide a controlling tty to bash! :) */
3772 /* fd is a tty at this point */
3773 fd = fcntl(fd, F_DUPFD, 10);
3774 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
3777 goto out; /* F_DUPFD failed */
3778 close_on_exec_on(fd);
3779 while (1) { /* while we are in the background */
3780 pgrp = tcgetpgrp(fd);
3783 ash_msg("can't access tty; job control turned off");
3787 if (pgrp == getpgrp())
3798 xtcsetpgrp(fd, pgrp);
3800 /* turning job control off */
3803 /* was xtcsetpgrp, but this can make exiting ash
3804 * loop forever if pty is already deleted */
3805 tcsetpgrp(fd, pgrp);
3819 static int FAST_FUNC
3820 killcmd(int argc, char **argv)
3822 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3825 if (argv[i][0] == '%') {
3827 * "kill %N" - job kill
3828 * Converting to pgrp / pid kill
3834 jp = getjob(argv[i], 0);
3836 * In jobs started under job control, we signal
3837 * entire process group by kill -PGRP_ID.
3838 * This happens, f.e., in interactive shell.
3840 * Otherwise, we signal each child via
3841 * kill PID1 PID2 PID3.
3843 * sh -c 'sleep 1|sleep 1 & kill %1'
3844 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3845 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3847 n = jp->nprocs; /* can't be 0 (I hope) */
3850 dst = alloca(n * sizeof(int)*4);
3852 for (j = 0; j < n; j++) {
3853 struct procstat *ps = &jp->ps[j];
3854 /* Skip non-running and not-stopped members
3855 * (i.e. dead members) of the job
3857 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3860 * kill_main has matching code to expect
3861 * leading space. Needed to not confuse
3862 * negative pids with "kill -SIGNAL_NO" syntax
3864 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3868 } while (argv[++i]);
3870 return kill_main(argc, argv);
3874 showpipe(struct job *jp /*, FILE *out*/)
3876 struct procstat *ps;
3877 struct procstat *psend;
3879 psend = jp->ps + jp->nprocs;
3880 for (ps = jp->ps + 1; ps < psend; ps++)
3881 printf(" | %s", ps->ps_cmd);
3882 newline_and_flush(stdout);
3883 flush_stdout_stderr();
3888 restartjob(struct job *jp, int mode)
3890 struct procstat *ps;
3896 if (jp->state == JOBDONE)
3898 jp->state = JOBRUNNING;
3899 pgid = jp->ps[0].ps_pid;
3900 if (mode == FORK_FG)
3901 xtcsetpgrp(ttyfd, pgid);
3902 killpg(pgid, SIGCONT);
3906 if (WIFSTOPPED(ps->ps_status)) {
3912 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3917 static int FAST_FUNC
3918 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3924 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3928 jp = getjob(*argv, 1);
3929 if (mode == FORK_BG) {
3930 set_curjob(jp, CUR_RUNNING);
3931 printf("[%d] ", jobno(jp));
3933 out1str(jp->ps[0].ps_cmd);
3934 showpipe(jp /*, stdout*/);
3935 retval = restartjob(jp, mode);
3936 } while (*argv && *++argv);
3942 sprint_status48(char *s, int status, int sigonly)
3948 if (!WIFEXITED(status)) {
3949 if (JOBS && WIFSTOPPED(status))
3950 st = WSTOPSIG(status);
3952 st = WTERMSIG(status);
3954 if (st == SIGINT || st == SIGPIPE)
3956 if (JOBS && WIFSTOPPED(status))
3960 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3961 col = fmtstr(s, 32, strsignal(st));
3962 if (WCOREDUMP(status)) {
3963 strcpy(s + col, " (core dumped)");
3964 col += sizeof(" (core dumped)")-1;
3966 } else if (!sigonly) {
3967 st = WEXITSTATUS(status);
3968 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
3975 wait_block_or_sig(int *status)
3982 /* Poll all children for changes in their state */
3984 /* if job control is active, accept stopped processes too */
3985 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
3987 break; /* Error (e.g. EINTR, ECHILD) or pid */
3989 /* Children exist, but none are ready. Sleep until interesting signal */
3992 sigprocmask(SIG_SETMASK, &mask, &mask);
3993 while (!got_sigchld && !pending_sig)
3995 sigprocmask(SIG_SETMASK, &mask, NULL);
3996 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
3997 while (!got_sigchld && !pending_sig)
4001 /* If it was SIGCHLD, poll children again */
4002 } while (got_sigchld);
4007 #define DOWAIT_NONBLOCK 0
4008 #define DOWAIT_BLOCK 1
4009 #define DOWAIT_BLOCK_OR_SIG 2
4012 dowait(int block, struct job *job)
4017 struct job *thisjob = NULL;
4019 TRACE(("dowait(0x%x) called\n", block));
4021 /* It's wrong to call waitpid() outside of INT_OFF region:
4022 * signal can arrive just after syscall return and handler can
4023 * longjmp away, losing stop/exit notification processing.
4024 * Thus, for "jobs" builtin, and for waiting for a fg job,
4025 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4027 * However, for "wait" builtin it is wrong to simply call waitpid()
4028 * in INT_OFF region: "wait" needs to wait for any running job
4029 * to change state, but should exit on any trap too.
4030 * In INT_OFF region, a signal just before syscall entry can set
4031 * pending_sig variables, but we can't check them, and we would
4032 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4034 * Because of this, we run inside INT_OFF, but use a special routine
4035 * which combines waitpid() and sigsuspend().
4036 * This is the reason why we need to have a handler for SIGCHLD:
4037 * SIG_DFL handler does not wake sigsuspend().
4040 if (block == DOWAIT_BLOCK_OR_SIG) {
4041 pid = wait_block_or_sig(&status);
4044 if (block == DOWAIT_NONBLOCK)
4045 wait_flags = WNOHANG;
4046 /* if job control is active, accept stopped processes too */
4048 wait_flags |= WUNTRACED;
4049 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4050 pid = waitpid(-1, &status, wait_flags);
4052 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4053 pid, status, errno, strerror(errno)));
4058 for (jp = curjob; jp; jp = jp->prev_job) {
4060 struct procstat *ps;
4061 struct procstat *psend;
4062 if (jp->state == JOBDONE)
4066 psend = ps + jp->nprocs;
4068 if (ps->ps_pid == pid) {
4069 TRACE(("Job %d: changing status of proc %d "
4070 "from 0x%x to 0x%x\n",
4071 jobno(jp), pid, ps->ps_status, status));
4072 ps->ps_status = status;
4075 if (ps->ps_status == -1)
4076 jobstate = JOBRUNNING;
4078 if (jobstate == JOBRUNNING)
4080 if (WIFSTOPPED(ps->ps_status)) {
4081 jp->stopstatus = ps->ps_status;
4082 jobstate = JOBSTOPPED;
4085 } while (++ps < psend);
4089 /* Found the job where one of its processes changed its state.
4090 * Is there at least one live and running process in this job? */
4091 if (jobstate != JOBRUNNING) {
4092 /* No. All live processes in the job are stopped
4093 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4095 thisjob->changed = 1;
4096 if (thisjob->state != jobstate) {
4097 TRACE(("Job %d: changing state from %d to %d\n",
4098 jobno(thisjob), thisjob->state, jobstate));
4099 thisjob->state = jobstate;
4101 if (jobstate == JOBSTOPPED)
4102 set_curjob(thisjob, CUR_STOPPED);
4108 /* The process wasn't found in job list */
4109 if (JOBS && !WIFSTOPPED(status))
4114 if (thisjob && thisjob == job) {
4118 len = sprint_status48(s, status, 1);
4130 showjob(struct job *jp, int mode)
4132 struct procstat *ps;
4133 struct procstat *psend;
4136 char s[16 + 16 + 48];
4137 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4141 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4142 /* just output process (group) id of pipeline */
4143 fprintf(out, "%d\n", ps->ps_pid);
4147 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4152 else if (curjob && jp == curjob->prev_job)
4155 if (mode & SHOW_PIDS)
4156 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4158 psend = ps + jp->nprocs;
4160 if (jp->state == JOBRUNNING) {
4161 strcpy(s + col, "Running");
4162 col += sizeof("Running") - 1;
4164 int status = psend[-1].ps_status;
4165 if (jp->state == JOBSTOPPED)
4166 status = jp->stopstatus;
4167 col += sprint_status48(s + col, status, 0);
4169 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4171 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4172 * or prints several "PID | <cmdN>" lines,
4173 * depending on SHOW_PIDS bit.
4174 * We do not print status of individual processes
4175 * between PID and <cmdN>. bash does it, but not very well:
4176 * first line shows overall job status, not process status,
4177 * making it impossible to know 1st process status.
4181 /* for each process */
4184 if (mode & SHOW_PIDS)
4185 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4187 fprintf(out, "%s%*c%s%s",
4189 33 - col >= 0 ? 33 - col : 0, ' ',
4190 ps == jp->ps ? "" : "| ",
4193 } while (++ps != psend);
4194 newline_and_flush(out);
4198 if (jp->state == JOBDONE) {
4199 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4205 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4206 * statuses have changed since the last call to showjobs.
4213 TRACE(("showjobs(0x%x) called\n", mode));
4215 /* Handle all finished jobs */
4216 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4219 for (jp = curjob; jp; jp = jp->prev_job) {
4220 if (!(mode & SHOW_CHANGED) || jp->changed) {
4226 static int FAST_FUNC
4227 jobscmd(int argc UNUSED_PARAM, char **argv)
4232 while ((m = nextopt("lp")) != '\0') {
4236 mode |= SHOW_ONLY_PGID;
4242 showjob(getjob(*argv, 0), mode);
4252 /* Called only on finished or stopped jobs (no members are running) */
4254 getstatus(struct job *job)
4258 struct procstat *ps;
4260 /* Fetch last member's status */
4261 ps = job->ps + job->nprocs - 1;
4262 status = ps->ps_status;
4264 /* "set -o pipefail" mode: use last _nonzero_ status */
4265 while (status == 0 && --ps >= job->ps)
4266 status = ps->ps_status;
4269 retval = WEXITSTATUS(status);
4270 if (!WIFEXITED(status)) {
4272 retval = WSTOPSIG(status);
4273 if (!WIFSTOPPED(status))
4276 /* XXX: limits number of signals */
4277 retval = WTERMSIG(status);
4279 if (retval == SIGINT)
4285 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4286 jobno(job), job->nprocs, status, retval));
4290 static int FAST_FUNC
4291 waitcmd(int argc UNUSED_PARAM, char **argv)
4302 /* wait for all jobs */
4306 if (!jp) /* no running procs */
4308 if (jp->state == JOBRUNNING)
4314 * "When bash is waiting for an asynchronous command via
4315 * the wait builtin, the reception of a signal for which a trap
4316 * has been set will cause the wait builtin to return immediately
4317 * with an exit status greater than 128, immediately after which
4318 * the trap is executed."
4320 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4321 /* if child sends us a signal *and immediately exits*,
4322 * dowait() returns pid > 0. Check this case,
4323 * not "if (dowait() < 0)"!
4332 if (**argv != '%') {
4333 pid_t pid = number(*argv);
4338 if (job->ps[job->nprocs - 1].ps_pid == pid)
4340 job = job->prev_job;
4343 job = getjob(*argv, 0);
4345 /* loop until process terminated or stopped */
4346 while (job->state == JOBRUNNING) {
4347 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4352 retval = getstatus(job);
4359 retval = 128 + pending_sig;
4368 struct job *jp, *jq;
4370 len = njobs * sizeof(*jp);
4372 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4374 offset = (char *)jp - (char *)jq;
4376 /* Relocate pointers */
4379 jq = (struct job *)((char *)jq + l);
4383 #define joff(p) ((struct job *)((char *)(p) + l))
4384 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4385 if (joff(jp)->ps == &jq->ps0)
4386 jmove(joff(jp)->ps);
4387 if (joff(jp)->prev_job)
4388 jmove(joff(jp)->prev_job);
4398 jp = (struct job *)((char *)jp + len);
4402 } while (--jq >= jp);
4407 * Return a new job structure.
4408 * Called with interrupts off.
4411 makejob(/*union node *node,*/ int nprocs)
4416 for (i = njobs, jp = jobtab; ; jp++) {
4423 if (jp->state != JOBDONE || !jp->waited)
4432 memset(jp, 0, sizeof(*jp));
4434 /* jp->jobctl is a bitfield.
4435 * "jp->jobctl |= jobctl" likely to give awful code */
4439 jp->prev_job = curjob;
4444 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4446 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4453 * Return a string identifying a command (to be printed by the
4456 static char *cmdnextc;
4459 cmdputs(const char *s)
4461 static const char vstype[VSTYPE + 1][3] = {
4462 "", "}", "-", "+", "?", "=",
4463 "%", "%%", "#", "##"
4464 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4467 const char *p, *str;
4471 unsigned char subtype = 0;
4475 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4477 while ((c = *p++) != '\0') {
4485 if ((subtype & VSTYPE) == VSLENGTH)
4491 str = "\"}" + !(quoted & 1);
4498 #if ENABLE_FEATURE_SH_MATH
4513 if ((subtype & VSTYPE) != VSNORMAL)
4515 str = vstype[subtype & VSTYPE];
4516 if (subtype & VSNUL)
4525 /* These can only happen inside quotes */
4538 while ((c = *str++) != '\0') {
4541 } /* while *p++ not NUL */
4544 USTPUTC('"', nextc);
4550 /* cmdtxt() and cmdlist() call each other */
4551 static void cmdtxt(union node *n);
4554 cmdlist(union node *np, int sep)
4556 for (; np; np = np->narg.next) {
4560 if (sep && np->narg.next)
4566 cmdtxt(union node *n)
4569 struct nodelist *lp;
4580 lp = n->npipe.cmdlist;
4598 cmdtxt(n->nbinary.ch1);
4614 cmdtxt(n->nif.test);
4616 if (n->nif.elsepart) {
4617 cmdtxt(n->nif.ifpart);
4619 n = n->nif.elsepart;
4637 cmdtxt(n->nbinary.ch1);
4647 cmdputs(n->nfor.var);
4649 cmdlist(n->nfor.args, 1);
4654 cmdputs(n->narg.text);
4658 cmdlist(n->ncmd.args, 1);
4659 cmdlist(n->ncmd.redirect, 0);
4672 cmdputs(n->ncase.expr->narg.text);
4674 for (np = n->ncase.cases; np; np = np->nclist.next) {
4675 cmdtxt(np->nclist.pattern);
4677 cmdtxt(np->nclist.body);
4691 #if ENABLE_ASH_BASH_COMPAT
4706 cmdputs(utoa(n->nfile.fd));
4708 if (n->type == NTOFD || n->type == NFROMFD) {
4709 cmdputs(utoa(n->ndup.dupfd));
4718 commandtext(union node *n)
4722 STARTSTACKSTR(cmdnextc);
4724 name = stackblock();
4725 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4726 return ckstrdup(name);
4731 * Fork off a subshell. If we are doing job control, give the subshell its
4732 * own process group. Jp is a job structure that the job is to be added to.
4733 * N is the command that will be evaluated by the child. Both jp and n may
4734 * be NULL. The mode parameter can be one of the following:
4735 * FORK_FG - Fork off a foreground process.
4736 * FORK_BG - Fork off a background process.
4737 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4738 * process group even if job control is on.
4740 * When job control is turned off, background processes have their standard
4741 * input redirected to /dev/null (except for the second and later processes
4744 * Called with interrupts off.
4747 * Clear traps on a fork.
4755 for (tp = trap; tp < &trap[NSIG]; tp++) {
4756 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4757 if (trap_ptr == trap)
4759 /* else: it "belongs" to trap_ptr vector, don't free */
4761 if ((tp - trap) != 0)
4762 setsignal(tp - trap);
4769 /* Lives far away from here, needed for forkchild */
4770 static void closescript(void);
4772 /* Called after fork(), in child */
4773 /* jp and n are NULL when called by openhere() for heredoc support */
4774 static NOINLINE void
4775 forkchild(struct job *jp, union node *n, int mode)
4779 TRACE(("Child shell %d\n", getpid()));
4783 /* man bash: "Non-builtin commands run by bash have signal handlers
4784 * set to the values inherited by the shell from its parent".
4785 * Do we do it correctly? */
4789 if (mode == FORK_NOJOB /* is it `xxx` ? */
4790 && n && n->type == NCMD /* is it single cmd? */
4791 /* && n->ncmd.args->type == NARG - always true? */
4792 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4793 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4794 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4796 TRACE(("Trap hack\n"));
4797 /* Awful hack for `trap` or $(trap).
4799 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4800 * contains an example where "trap" is executed in a subshell:
4802 * save_traps=$(trap)
4804 * eval "$save_traps"
4806 * Standard does not say that "trap" in subshell shall print
4807 * parent shell's traps. It only says that its output
4808 * must have suitable form, but then, in the above example
4809 * (which is not supposed to be normative), it implies that.
4811 * bash (and probably other shell) does implement it
4812 * (traps are reset to defaults, but "trap" still shows them),
4813 * but as a result, "trap" logic is hopelessly messed up:
4816 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4817 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4818 * # true | trap <--- trap is in subshell - no output (ditto)
4819 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4820 * trap -- 'echo Ho' SIGWINCH
4821 * # echo `(trap)` <--- in subshell in subshell - output
4822 * trap -- 'echo Ho' SIGWINCH
4823 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4824 * trap -- 'echo Ho' SIGWINCH
4826 * The rules when to forget and when to not forget traps
4827 * get really complex and nonsensical.
4829 * Our solution: ONLY bare $(trap) or `trap` is special.
4831 /* Save trap handler strings for trap builtin to print */
4832 trap_ptr = xmemdup(trap, sizeof(trap));
4833 /* Fall through into clearing traps */
4837 /* do job control only in root shell */
4839 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4842 if (jp->nprocs == 0)
4845 pgrp = jp->ps[0].ps_pid;
4846 /* this can fail because we are doing it in the parent also */
4848 if (mode == FORK_FG)
4849 xtcsetpgrp(ttyfd, pgrp);
4854 if (mode == FORK_BG) {
4855 /* man bash: "When job control is not in effect,
4856 * asynchronous commands ignore SIGINT and SIGQUIT" */
4859 if (jp->nprocs == 0) {
4861 if (open(bb_dev_null, O_RDONLY) != 0)
4862 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4866 if (iflag) { /* why if iflag only? */
4871 * "In all cases, bash ignores SIGQUIT. Non-builtin
4872 * commands run by bash have signal handlers
4873 * set to the values inherited by the shell
4875 * Take care of the second rule: */
4879 if (n && n->type == NCMD
4880 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4882 TRACE(("Job hack\n"));
4883 /* "jobs": we do not want to clear job list for it,
4884 * instead we remove only _its_ own_ job from job list.
4885 * This makes "jobs .... | cat" more useful.
4891 for (jp = curjob; jp; jp = jp->prev_job)
4896 /* Called after fork(), in parent */
4898 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4901 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4903 TRACE(("In parent shell: child = %d\n", pid));
4905 /* jp is NULL when called by openhere() for heredoc support */
4906 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4912 if (mode != FORK_NOJOB && jp->jobctl) {
4915 if (jp->nprocs == 0)
4918 pgrp = jp->ps[0].ps_pid;
4919 /* This can fail because we are doing it in the child also */
4923 if (mode == FORK_BG) {
4924 backgndpid = pid; /* set $! */
4925 set_curjob(jp, CUR_RUNNING);
4928 struct procstat *ps = &jp->ps[jp->nprocs++];
4931 ps->ps_cmd = nullstr;
4933 if (doing_jobctl && n)
4934 ps->ps_cmd = commandtext(n);
4939 /* jp and n are NULL when called by openhere() for heredoc support */
4941 forkshell(struct job *jp, union node *n, int mode)
4945 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4948 TRACE(("Fork failed, errno=%d", errno));
4951 ash_msg_and_raise_error("can't fork");
4954 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4955 forkchild(jp, n, mode);
4957 forkparent(jp, n, mode, pid);
4963 * Wait for job to finish.
4965 * Under job control we have the problem that while a child process
4966 * is running interrupts generated by the user are sent to the child
4967 * but not to the shell. This means that an infinite loop started by
4968 * an interactive user may be hard to kill. With job control turned off,
4969 * an interactive user may place an interactive program inside a loop.
4970 * If the interactive program catches interrupts, the user doesn't want
4971 * these interrupts to also abort the loop. The approach we take here
4972 * is to have the shell ignore interrupt signals while waiting for a
4973 * foreground process to terminate, and then send itself an interrupt
4974 * signal if the child process was terminated by an interrupt signal.
4975 * Unfortunately, some programs want to do a bit of cleanup and then
4976 * exit on interrupt; unless these processes terminate themselves by
4977 * sending a signal to themselves (instead of calling exit) they will
4978 * confuse this approach.
4980 * Called with interrupts off.
4983 waitforjob(struct job *jp)
4987 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4990 while (jp->state == JOBRUNNING) {
4991 /* In non-interactive shells, we _can_ get
4992 * a keyboard signal here and be EINTRed,
4993 * but we just loop back, waiting for command to complete.
4996 * "If bash is waiting for a command to complete and receives
4997 * a signal for which a trap has been set, the trap
4998 * will not be executed until the command completes."
5000 * Reality is that even if trap is not set, bash
5001 * will not act on the signal until command completes.
5002 * Try this. sleep5intoff.c:
5003 * #include <signal.h>
5004 * #include <unistd.h>
5007 * sigemptyset(&set);
5008 * sigaddset(&set, SIGINT);
5009 * sigaddset(&set, SIGQUIT);
5010 * sigprocmask(SIG_BLOCK, &set, NULL);
5014 * $ bash -c './sleep5intoff; echo hi'
5015 * ^C^C^C^C <--- pressing ^C once a second
5017 * $ bash -c './sleep5intoff; echo hi'
5018 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5021 dowait(DOWAIT_BLOCK, jp);
5028 xtcsetpgrp(ttyfd, rootpid);
5030 * This is truly gross.
5031 * If we're doing job control, then we did a TIOCSPGRP which
5032 * caused us (the shell) to no longer be in the controlling
5033 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5034 * intuit from the subprocess exit status whether a SIGINT
5035 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5037 if (jp->sigint) /* TODO: do the same with all signals */
5038 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5040 if (jp->state == JOBDONE)
5047 * return 1 if there are stopped jobs, otherwise 0
5059 if (jp && jp->state == JOBSTOPPED) {
5060 out2str("You have stopped jobs.\n");
5070 * Code for dealing with input/output redirection.
5075 #define EMPTY -2 /* marks an unused slot in redirtab */
5076 #define CLOSED -3 /* marks a slot of previously-closed fd */
5079 * Open a file in noclobber mode.
5080 * The code was copied from bash.
5083 noclobberopen(const char *fname)
5086 struct stat finfo, finfo2;
5089 * If the file exists and is a regular file, return an error
5092 r = stat(fname, &finfo);
5093 if (r == 0 && S_ISREG(finfo.st_mode)) {
5099 * If the file was not present (r != 0), make sure we open it
5100 * exclusively so that if it is created before we open it, our open
5101 * will fail. Make sure that we do not truncate an existing file.
5102 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5103 * file was not a regular file, we leave O_EXCL off.
5106 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5107 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5109 /* If the open failed, return the file descriptor right away. */
5114 * OK, the open succeeded, but the file may have been changed from a
5115 * non-regular file to a regular file between the stat and the open.
5116 * We are assuming that the O_EXCL open handles the case where FILENAME
5117 * did not exist and is symlinked to an existing file between the stat
5122 * If we can open it and fstat the file descriptor, and neither check
5123 * revealed that it was a regular file, and the file has not been
5124 * replaced, return the file descriptor.
5126 if (fstat(fd, &finfo2) == 0
5127 && !S_ISREG(finfo2.st_mode)
5128 && finfo.st_dev == finfo2.st_dev
5129 && finfo.st_ino == finfo2.st_ino
5134 /* The file has been replaced. badness. */
5141 * Handle here documents. Normally we fork off a process to write the
5142 * data to a pipe. If the document is short, we can stuff the data in
5143 * the pipe without forking.
5145 /* openhere needs this forward reference */
5146 static void expandhere(union node *arg, int fd);
5148 openhere(union node *redir)
5154 ash_msg_and_raise_error("pipe call failed");
5155 if (redir->type == NHERE) {
5156 len = strlen(redir->nhere.doc->narg.text);
5157 if (len <= PIPE_BUF) {
5158 full_write(pip[1], redir->nhere.doc->narg.text, len);
5162 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5165 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5166 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5167 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5168 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5169 signal(SIGPIPE, SIG_DFL);
5170 if (redir->type == NHERE)
5171 full_write(pip[1], redir->nhere.doc->narg.text, len);
5173 expandhere(redir->nhere.doc, pip[1]);
5174 _exit(EXIT_SUCCESS);
5182 openredirect(union node *redir)
5187 switch (redir->nfile.type) {
5188 /* Can't happen, our single caller does this itself */
5194 return openhere(redir);
5197 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5198 * allocated space. Do it only when we know it is safe.
5200 fname = redir->nfile.expfname;
5202 switch (redir->nfile.type) {
5208 f = open(fname, O_RDONLY);
5213 f = open(fname, O_RDWR|O_CREAT, 0666);
5218 #if ENABLE_ASH_BASH_COMPAT
5221 /* Take care of noclobber mode. */
5223 f = noclobberopen(fname);
5230 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5235 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5243 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5245 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5249 * Copy a file descriptor to be >= 10. Throws exception on error.
5257 newfd = fcntl(from, F_DUPFD, 10);
5258 err = newfd < 0 ? errno : 0;
5261 ash_msg_and_raise_error("%d: %m", from);
5263 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5269 dup2_or_raise(int from, int to)
5273 newfd = (from != to) ? dup2(from, to) : to;
5275 /* Happens when source fd is not open: try "echo >&99" */
5276 ash_msg_and_raise_error("%d: %m", from);
5281 /* Struct def and variable are moved down to the first usage site */
5286 struct redirtab *next;
5288 struct two_fd_t two_fd[];
5290 #define redirlist (G_var.redirlist)
5292 COPYFD_RESTORE = (int)~(INT_MAX),
5296 need_to_remember(struct redirtab *rp, int fd)
5300 if (!rp) /* remembering was not requested */
5303 for (i = 0; i < rp->pair_count; i++) {
5304 if (rp->two_fd[i].orig == fd) {
5305 /* already remembered */
5312 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5314 is_hidden_fd(struct redirtab *rp, int fd)
5317 struct parsefile *pf;
5321 /* Check open scripts' fds */
5324 /* We skip pf_fd == 0 case because of the following case:
5325 * $ ash # running ash interactively
5327 * and in script.sh: "exec 9>&0".
5328 * Even though top-level pf_fd _is_ 0,
5329 * it's still ok to use it: "read" builtin uses it,
5330 * why should we cripple "exec" builtin?
5332 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5340 /* Check saved fds of redirects */
5341 fd |= COPYFD_RESTORE;
5342 for (i = 0; i < rp->pair_count; i++) {
5343 if (rp->two_fd[i].copy == fd) {
5351 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5352 * old file descriptors are stashed away so that the redirection can be
5353 * undone by calling popredir.
5355 /* flags passed to redirect */
5356 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5357 #define REDIR_SAVEFD2 03 /* set preverrout */
5359 redirect(union node *redir, int flags)
5361 struct redirtab *sv;
5366 int copied_fd2 = -1;
5375 if (flags & REDIR_PUSH) {
5376 union node *tmp = redir;
5379 #if ENABLE_ASH_BASH_COMPAT
5380 if (tmp->nfile.type == NTO2)
5383 tmp = tmp->nfile.next;
5385 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5386 sv->next = redirlist;
5387 sv->pair_count = sv_pos;
5389 while (sv_pos > 0) {
5391 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5397 fd = redir->nfile.fd;
5398 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5399 right_fd = redir->ndup.dupfd;
5400 //bb_error_msg("doing %d > %d", fd, right_fd);
5401 /* redirect from/to same file descriptor? */
5404 /* "echo >&10" and 10 is a fd opened to a sh script? */
5405 if (is_hidden_fd(sv, right_fd)) {
5406 errno = EBADF; /* as if it is closed */
5407 ash_msg_and_raise_error("%d: %m", right_fd);
5411 newfd = openredirect(redir); /* always >= 0 */
5413 /* Descriptor wasn't open before redirect.
5414 * Mark it for close in the future */
5415 if (need_to_remember(sv, fd)) {
5416 goto remember_to_close;
5421 #if ENABLE_ASH_BASH_COMPAT
5424 if (need_to_remember(sv, fd)) {
5425 /* Copy old descriptor */
5426 /* Careful to not accidentally "save"
5427 * to the same fd as right side fd in N>&M */
5428 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5429 i = fcntl(fd, F_DUPFD, minfd);
5430 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5431 * are closed in popredir() in the child, preventing them from leaking
5432 * into child. (popredir() also cleans up the mess in case of failures)
5437 /* Strange error (e.g. "too many files" EMFILE?) */
5441 ash_msg_and_raise_error("%d: %m", fd);
5444 /* EBADF: it is not open - good, remember to close it */
5447 } else { /* fd is open, save its copy */
5448 /* "exec fd>&-" should not close fds
5449 * which point to script file(s).
5450 * Force them to be restored afterwards */
5451 if (is_hidden_fd(sv, fd))
5452 i |= COPYFD_RESTORE;
5456 sv->two_fd[sv_pos].orig = fd;
5457 sv->two_fd[sv_pos].copy = i;
5461 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5462 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5463 /* Don't want to trigger debugging */
5467 dup2_or_raise(redir->ndup.dupfd, fd);
5469 } else if (fd != newfd) { /* move newfd to fd */
5470 dup2_or_raise(newfd, fd);
5471 #if ENABLE_ASH_BASH_COMPAT
5472 if (!(redir->nfile.type == NTO2 && fd == 2))
5476 #if ENABLE_ASH_BASH_COMPAT
5477 if (redir->nfile.type == NTO2 && fd == 1) {
5478 /* We already redirected it to fd 1, now copy it to 2 */
5484 } while ((redir = redir->nfile.next) != NULL);
5487 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5488 preverrout_fd = copied_fd2;
5492 * Undo the effects of the last redirection.
5495 popredir(int drop, int restore)
5497 struct redirtab *rp;
5500 if (redirlist == NULL)
5504 for (i = 0; i < rp->pair_count; i++) {
5505 int fd = rp->two_fd[i].orig;
5506 int copy = rp->two_fd[i].copy;
5507 if (copy == CLOSED) {
5512 if (copy != EMPTY) {
5513 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5514 copy &= ~COPYFD_RESTORE;
5516 dup2_or_raise(copy, fd);
5518 close(copy & ~COPYFD_RESTORE);
5521 redirlist = rp->next;
5527 * Undo all redirections. Called on error or interrupt.
5531 redirectsafe(union node *redir, int flags)
5534 volatile int saveint;
5535 struct jmploc *volatile savehandler = exception_handler;
5536 struct jmploc jmploc;
5539 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5540 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5542 exception_handler = &jmploc;
5543 redirect(redir, flags);
5545 exception_handler = savehandler;
5546 if (err && exception_type != EXERROR)
5547 longjmp(exception_handler->loc, 1);
5548 RESTORE_INT(saveint);
5553 /* ============ Routines to expand arguments to commands
5555 * We have to deal with backquotes, shell variables, and file metacharacters.
5558 #if ENABLE_FEATURE_SH_MATH
5560 ash_arith(const char *s)
5562 arith_state_t math_state;
5565 math_state.lookupvar = lookupvar;
5566 math_state.setvar = setvar0;
5567 //math_state.endofname = endofname;
5570 result = arith(&math_state, s);
5571 if (math_state.errmsg)
5572 ash_msg_and_raise_error(math_state.errmsg);
5582 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5583 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5584 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5585 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5586 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5587 * POSIX says for this case:
5588 * Pathname expansion shall not be performed on the word by a
5589 * non-interactive shell; an interactive shell may perform it, but shall
5590 * do so only when the expansion would result in one word.
5591 * Currently, our code complies to the above rule by never globbing
5592 * redirection filenames.
5593 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5594 * (this means that on a typical Linux distro, bash almost always
5595 * performs globbing, and thus diverges from what we do).
5597 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5598 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5599 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5600 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5601 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5605 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5606 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5607 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5608 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5609 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5611 /* Add CTLESC when necessary. */
5612 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5613 /* Do not skip NUL characters. */
5614 #define QUOTES_KEEPNUL EXP_TILDE
5617 * Structure specifying which parts of the string should be searched
5618 * for IFS characters.
5621 struct ifsregion *next; /* next region in list */
5622 int begoff; /* offset of start of region */
5623 int endoff; /* offset of end of region */
5624 int nulonly; /* search for nul bytes only */
5628 struct strlist *list;
5629 struct strlist **lastp;
5632 /* output of current string */
5633 static char *expdest;
5634 /* list of back quote expressions */
5635 static struct nodelist *argbackq;
5636 /* first struct in list of ifs regions */
5637 static struct ifsregion ifsfirst;
5638 /* last struct in list */
5639 static struct ifsregion *ifslastp;
5640 /* holds expanded arg list */
5641 static struct arglist exparg;
5646 #if !ENABLE_FEATURE_SH_MATH
5647 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5648 typedef long arith_t;
5649 # define ARITH_FMT "%ld"
5656 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5657 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5658 STADJUST(len, expdest);
5663 * Break the argument string into pieces based upon IFS and add the
5664 * strings to the argument list. The regions of the string to be
5665 * searched for IFS characters have been stored by recordregion.
5668 ifsbreakup(char *string, struct arglist *arglist)
5670 struct ifsregion *ifsp;
5675 const char *ifs, *realifs;
5680 if (ifslastp != NULL) {
5683 realifs = ifsset() ? ifsval() : defifs;
5686 p = string + ifsp->begoff;
5687 nulonly = ifsp->nulonly;
5688 ifs = nulonly ? nullstr : realifs;
5690 while (p < string + ifsp->endoff) {
5692 if ((unsigned char)*p == CTLESC)
5694 if (!strchr(ifs, *p)) {
5699 ifsspc = (strchr(defifs, *p) != NULL);
5700 /* Ignore IFS whitespace at start */
5701 if (q == start && ifsspc) {
5707 sp = stzalloc(sizeof(*sp));
5709 *arglist->lastp = sp;
5710 arglist->lastp = &sp->next;
5714 if (p >= string + ifsp->endoff) {
5718 if ((unsigned char)*p == CTLESC)
5720 if (strchr(ifs, *p) == NULL) {
5724 if (strchr(defifs, *p) == NULL) {
5739 } while (ifsp != NULL);
5748 sp = stzalloc(sizeof(*sp));
5750 *arglist->lastp = sp;
5751 arglist->lastp = &sp->next;
5757 struct ifsregion *p = ifsfirst.next;
5764 struct ifsregion *ifsp;
5769 ifsfirst.next = NULL;
5776 esclen(const char *start, const char *p)
5780 while (p > start && (unsigned char)*--p == CTLESC) {
5787 * Remove any CTLESC characters from a string.
5790 rmescapes(char *str, int flag)
5792 static const char qchars[] ALIGN1 = {
5793 IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
5797 unsigned protect_against_glob;
5799 IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
5801 p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
5807 if (flag & RMESCAPE_ALLOC) {
5808 size_t len = p - str;
5809 size_t fulllen = len + strlen(p) + 1;
5811 if (flag & RMESCAPE_GROW) {
5812 int strloc = str - (char *)stackblock();
5813 r = makestrspace(fulllen, expdest);
5814 /* p and str may be invalidated by makestrspace */
5815 str = (char *)stackblock() + strloc;
5817 } else if (flag & RMESCAPE_HEAP) {
5818 r = ckmalloc(fulllen);
5820 r = stalloc(fulllen);
5824 q = (char *)memcpy(q, str, len) + len;
5829 globbing = flag & RMESCAPE_GLOB;
5830 protect_against_glob = globbing;
5832 if ((unsigned char)*p == CTLQUOTEMARK) {
5833 // Note: both inquotes and protect_against_glob only affect whether
5834 inquotes = ~inquotes;
5836 protect_against_glob = globbing;
5839 if ((unsigned char)*p == CTLESC) {
5843 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5845 if (protect_against_glob) {
5848 } else if (*p == '\\' && !inquotes) {
5849 /* naked back slash */
5850 protect_against_glob = 0;
5853 #if ENABLE_ASH_BASH_COMPAT
5854 else if (*p == '/' && slash) {
5855 /* stop handling globbing and mark location of slash */
5856 globbing = slash = 0;
5860 protect_against_glob = globbing;
5865 if (flag & RMESCAPE_GROW) {
5867 STADJUST(q - r + 1, expdest);
5871 #define pmatch(a, b) !fnmatch((a), (b), 0)
5874 * Prepare a pattern for a expmeta (internal glob(3)) call.
5876 * Returns an stalloced string.
5879 preglob(const char *pattern, int flag)
5881 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5885 * Put a string on the stack.
5888 memtodest(const char *p, size_t len, int syntax, int quotes)
5895 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5898 unsigned char c = *p++;
5900 if (quotes & QUOTES_ESC) {
5901 int n = SIT(c, syntax);
5903 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5910 } else if (!(quotes & QUOTES_KEEPNUL))
5919 strtodest(const char *p, int syntax, int quotes)
5921 size_t len = strlen(p);
5922 memtodest(p, len, syntax, quotes);
5927 * Record the fact that we have to scan this region of the
5928 * string for IFS characters.
5931 recordregion(int start, int end, int nulonly)
5933 struct ifsregion *ifsp;
5935 if (ifslastp == NULL) {
5939 ifsp = ckzalloc(sizeof(*ifsp));
5940 /*ifsp->next = NULL; - ckzalloc did it */
5941 ifslastp->next = ifsp;
5945 ifslastp->begoff = start;
5946 ifslastp->endoff = end;
5947 ifslastp->nulonly = nulonly;
5951 removerecordregions(int endoff)
5953 if (ifslastp == NULL)
5956 if (ifsfirst.endoff > endoff) {
5957 while (ifsfirst.next) {
5958 struct ifsregion *ifsp;
5960 ifsp = ifsfirst.next->next;
5961 free(ifsfirst.next);
5962 ifsfirst.next = ifsp;
5965 if (ifsfirst.begoff > endoff) {
5968 ifslastp = &ifsfirst;
5969 ifsfirst.endoff = endoff;
5974 ifslastp = &ifsfirst;
5975 while (ifslastp->next && ifslastp->next->begoff < endoff)
5976 ifslastp = ifslastp->next;
5977 while (ifslastp->next) {
5978 struct ifsregion *ifsp;
5980 ifsp = ifslastp->next->next;
5981 free(ifslastp->next);
5982 ifslastp->next = ifsp;
5985 if (ifslastp->endoff > endoff)
5986 ifslastp->endoff = endoff;
5990 exptilde(char *startp, char *p, int flags)
5996 int quotes = flags & QUOTES_ESC;
6000 while ((c = *++p) != '\0') {
6007 if (flags & EXP_VARTILDE)
6017 if (*name == '\0') {
6018 home = lookupvar("HOME");
6020 pw = getpwnam(name);
6025 if (!home || !*home)
6028 strtodest(home, SQSYNTAX, quotes);
6036 * Execute a command inside back quotes. If it's a builtin command, we
6037 * want to save its output in a block obtained from malloc. Otherwise
6038 * we fork off a subprocess and get the output of the command via a pipe.
6039 * Should be called with interrupts off.
6041 struct backcmd { /* result of evalbackcmd */
6042 int fd; /* file descriptor to read from */
6043 int nleft; /* number of chars in buffer */
6044 char *buf; /* buffer */
6045 struct job *jp; /* job structure for command */
6048 /* These forward decls are needed to use "eval" code for backticks handling: */
6049 #define EV_EXIT 01 /* exit after evaluating tree */
6050 static int evaltree(union node *, int);
6052 static void FAST_FUNC
6053 evalbackcmd(union node *n, struct backcmd *result)
6067 ash_msg_and_raise_error("pipe call failed");
6068 jp = makejob(/*n,*/ 1);
6069 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6075 dup2_or_raise(pip[1], 1);
6078 /* TODO: eflag clearing makes the following not abort:
6079 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6080 * which is what bash does (unless it is in POSIX mode).
6081 * dash deleted "eflag = 0" line in the commit
6082 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6083 * [EVAL] Don't clear eflag in evalbackcmd
6084 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6088 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6093 result->fd = pip[0];
6097 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6098 result->fd, result->buf, result->nleft, result->jp));
6102 * Expand stuff in backwards quotes.
6105 expbackq(union node *cmd, int flag)
6113 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6114 struct stackmark smark;
6117 startloc = expdest - (char *)stackblock();
6118 pushstackmark(&smark, startloc);
6119 evalbackcmd(cmd, &in);
6120 popstackmark(&smark);
6127 memtodest(p, i, syntax, flag & QUOTES_ESC);
6131 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6132 TRACE(("expbackq: read returns %d\n", i));
6141 back_exitstatus = waitforjob(in.jp);
6145 /* Eat all trailing newlines */
6147 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6151 if (!(flag & EXP_QUOTED))
6152 recordregion(startloc, dest - (char *)stackblock(), 0);
6153 TRACE(("evalbackq: size:%d:'%.*s'\n",
6154 (int)((dest - (char *)stackblock()) - startloc),
6155 (int)((dest - (char *)stackblock()) - startloc),
6156 stackblock() + startloc));
6159 #if ENABLE_FEATURE_SH_MATH
6161 * Expand arithmetic expression. Backup to start of expression,
6162 * evaluate, place result in (backed up) result, adjust string position.
6174 * This routine is slightly over-complicated for
6175 * efficiency. Next we scan backwards looking for the
6176 * start of arithmetic.
6178 start = stackblock();
6185 while ((unsigned char)*p != CTLARI) {
6189 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6194 esc = esclen(start, p);
6204 removerecordregions(begoff);
6208 if (flag & QUOTES_ESC)
6209 rmescapes(p + 1, 0);
6211 len = cvtnum(ash_arith(p + 1));
6213 if (!(flag & EXP_QUOTED))
6214 recordregion(begoff, begoff + len, 0);
6218 /* argstr needs it */
6219 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6222 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6223 * characters to allow for further processing. Otherwise treat
6224 * $@ like $* since no splitting will be performed.
6226 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6227 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6228 * for correct expansion of "B=$A" word.
6231 argstr(char *p, int flags, struct strlist *var_str_list)
6233 static const char spclchars[] ALIGN1 = {
6241 #if ENABLE_FEATURE_SH_MATH
6246 const char *reject = spclchars;
6247 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6252 if (!(flags & EXP_VARTILDE)) {
6254 } else if (flags & EXP_VARTILDE2) {
6259 if (flags & EXP_TILDE) {
6262 flags &= ~EXP_TILDE;
6266 p = exptilde(p, q, flags);
6269 startloc = expdest - (char *)stackblock();
6273 length += strcspn(p + length, reject);
6277 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6279 /* c == '=' || c == ':' || c == CTLENDARI */
6285 expdest = stack_nputstr(p, length, expdest);
6286 newloc = expdest - (char *)stackblock();
6287 if (breakall && !inquotes && newloc > startloc) {
6288 recordregion(startloc, newloc, 0);
6299 if (flags & EXP_VARTILDE2) {
6303 flags |= EXP_VARTILDE2;
6308 * sort of a hack - expand tildes in variable
6309 * assignments (after the first '=' and after ':'s).
6318 case CTLENDVAR: /* ??? */
6321 inquotes ^= EXP_QUOTED;
6322 /* "$@" syntax adherence hack */
6323 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6324 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6328 if (flags & QUOTES_ESC) {
6339 * Quoted parameter expansion pattern: remove quote
6340 * unless inside inner quotes or we have a literal
6343 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6344 EXP_QPAT && *p != '\\')
6349 TRACE(("argstr: evalvar('%s')\n", p));
6350 p = evalvar(p, flags | inquotes, var_str_list);
6351 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6354 expbackq(argbackq->n, flags | inquotes);
6355 argbackq = argbackq->next;
6357 #if ENABLE_FEATURE_SH_MATH
6360 expari(flags | inquotes);
6369 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6370 char *pattern, int quotes, int zero)
6379 const char *s = loc2;
6386 match = pmatch(pattern, s);
6391 if (quotes && (unsigned char)*loc == CTLESC)
6400 scanright(char *startp, char *rmesc, char *rmescend,
6401 char *pattern, int quotes, int match_at_start)
6403 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6404 int try2optimize = match_at_start;
6410 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6411 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6412 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6414 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6415 * and on each iteration they go back two/one char until they reach the beginning.
6416 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6418 /* TODO: document in what other circumstances we are called. */
6420 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6423 const char *s = loc2;
6424 if (match_at_start) {
6428 match = pmatch(pattern, s);
6429 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6433 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6435 /* Maybe we can optimize this:
6436 * if pattern ends with unescaped *, we can avoid checking
6437 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6438 * it wont match truncated "raw_value_of_" strings too.
6440 unsigned plen = strlen(pattern);
6441 /* Does it end with "*"? */
6442 if (plen != 0 && pattern[--plen] == '*') {
6443 /* "xxxx*" is not escaped */
6444 /* "xxx\*" is escaped */
6445 /* "xx\\*" is not escaped */
6446 /* "x\\\*" is escaped */
6448 while (plen != 0 && pattern[--plen] == '\\')
6451 break; /* ends with unescaped "*" */
6459 esc = esclen(startp, loc);
6470 static void varunset(const char *, const char *, const char *, int) NORETURN;
6472 varunset(const char *end, const char *var, const char *umsg, int varflags)
6478 msg = "parameter not set";
6480 if ((unsigned char)*end == CTLENDVAR) {
6481 if (varflags & VSNUL)
6487 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6491 subevalvar(char *p, char *varname, int strloc, int subtype,
6492 int startloc, int varflags, int flag, struct strlist *var_str_list)
6494 struct nodelist *saveargbackq = argbackq;
6495 int quotes = flag & QUOTES_ESC;
6498 char *rmesc, *rmescend;
6500 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6501 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6502 int amount, resetloc;
6503 IF_ASH_BASH_COMPAT(int workloc;)
6505 char *(*scan)(char*, char*, char*, char*, int, int);
6507 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6508 // p, varname, strloc, subtype, startloc, varflags, quotes);
6510 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6511 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6513 STPUTC('\0', expdest);
6514 argbackq = saveargbackq;
6515 startp = (char *)stackblock() + startloc;
6519 setvar0(varname, startp);
6520 amount = startp - expdest;
6521 STADJUST(amount, expdest);
6525 varunset(p, varname, startp, varflags);
6528 #if ENABLE_ASH_BASH_COMPAT
6530 //TODO: support more general format ${v:EXPR:EXPR},
6531 // where EXPR follows $(()) rules
6532 loc = str = stackblock() + strloc;
6533 /* Read POS in ${var:POS:LEN} */
6534 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6535 len = str - startp - 1;
6537 /* *loc != '\0', guaranteed by parser */
6541 /* Adjust the length by the number of escapes */
6542 for (ptr = startp; ptr < (str - 1); ptr++) {
6543 if ((unsigned char)*ptr == CTLESC) {
6551 if (*loc++ == ':') {
6555 /* Skip POS in ${var:POS:LEN} */
6557 while (*loc && *loc != ':') {
6559 * bash complains on: var=qwe; echo ${var:1a:123}
6561 ash_msg_and_raise_error(msg_illnum, str);
6565 if (*loc++ == ':') {
6570 /* ${VAR:$((-n)):l} starts n chars from the end */
6571 pos = orig_len + pos;
6573 if ((unsigned)pos >= orig_len) {
6574 /* apart from obvious ${VAR:999999:l},
6575 * covers ${VAR:$((-9999999)):l} - result is ""
6581 if (len > (orig_len - pos))
6582 len = orig_len - pos;
6584 for (str = startp; pos; str++, pos--) {
6585 if (quotes && (unsigned char)*str == CTLESC)
6588 for (loc = startp; len; len--) {
6589 if (quotes && (unsigned char)*str == CTLESC)
6594 amount = loc - expdest;
6595 STADJUST(amount, expdest);
6600 resetloc = expdest - (char *)stackblock();
6602 /* We'll comeback here if we grow the stack while handling
6603 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6604 * stack will need rebasing, and we'll need to remove our work
6607 IF_ASH_BASH_COMPAT(restart:)
6609 amount = expdest - ((char *)stackblock() + resetloc);
6610 STADJUST(-amount, expdest);
6611 startp = (char *)stackblock() + startloc;
6614 rmescend = (char *)stackblock() + strloc;
6616 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6617 if (rmesc != startp) {
6619 startp = (char *)stackblock() + startloc;
6623 str = (char *)stackblock() + strloc;
6625 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6626 * The result is a_\_z_c (not a\_\_z_c)!
6628 * The search pattern and replace string treat backslashes differently!
6629 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6630 * and string. It's only used on the first call.
6632 preglob(str, IF_ASH_BASH_COMPAT(
6633 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6634 RMESCAPE_SLASH :) 0);
6636 #if ENABLE_ASH_BASH_COMPAT
6637 workloc = expdest - (char *)stackblock();
6638 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6642 repl = strchr(str, CTLESC);
6648 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6650 /* If there's no pattern to match, return the expansion unmolested */
6659 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6660 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6662 /* No match, advance */
6663 char *restart_detect = stackblock();
6665 STPUTC(*idx, expdest);
6666 if (quotes && (unsigned char)*idx == CTLESC) {
6669 STPUTC(*idx, expdest);
6671 if (stackblock() != restart_detect)
6676 /* continue; - prone to quadratic behavior, smarter code: */
6679 if (str[0] == '*') {
6680 /* Pattern is "*foo". If "*foo" does not match "long_string",
6681 * it would never match "ong_string" etc, no point in trying.
6688 if (subtype == VSREPLACEALL) {
6690 if (quotes && (unsigned char)*idx == CTLESC)
6699 //bb_error_msg("repl:'%s'", repl);
6700 for (loc = (char*)repl; *loc; loc++) {
6701 char *restart_detect = stackblock();
6702 if (quotes && *loc == '\\') {
6703 STPUTC(CTLESC, expdest);
6706 STPUTC(*loc, expdest);
6707 if (stackblock() != restart_detect)
6712 if (subtype == VSREPLACE) {
6713 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6715 char *restart_detect = stackblock();
6716 STPUTC(*idx, expdest);
6717 if (stackblock() != restart_detect)
6726 /* We've put the replaced text into a buffer at workloc, now
6727 * move it to the right place and adjust the stack.
6729 STPUTC('\0', expdest);
6730 startp = (char *)stackblock() + startloc;
6731 memmove(startp, (char *)stackblock() + workloc, len + 1);
6732 //bb_error_msg("startp:'%s'", startp);
6733 amount = expdest - (startp + len);
6734 STADJUST(-amount, expdest);
6737 #endif /* ENABLE_ASH_BASH_COMPAT */
6739 subtype -= VSTRIMRIGHT;
6741 if (subtype < 0 || subtype > 7)
6744 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6745 zero = subtype >> 1;
6746 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6747 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6749 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6752 memmove(startp, loc, str - loc);
6753 loc = startp + (str - loc) - 1;
6756 amount = loc - expdest;
6757 STADJUST(amount, expdest);
6763 * Add the value of a specialized variable to the stack string.
6764 * name parameter (examples):
6765 * ash -c 'echo $1' name:'1='
6766 * ash -c 'echo $qwe' name:'qwe='
6767 * ash -c 'echo $$' name:'$='
6768 * ash -c 'echo ${$}' name:'$='
6769 * ash -c 'echo ${$##q}' name:'$=q'
6770 * ash -c 'echo ${#$}' name:'$='
6771 * note: examples with bad shell syntax:
6772 * ash -c 'echo ${#$1}' name:'$=1'
6773 * ash -c 'echo ${#1#}' name:'1=#'
6775 static NOINLINE ssize_t
6776 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6783 int quoted = *quotedp;
6784 int subtype = varflags & VSTYPE;
6785 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6786 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6789 sep = (flags & EXP_FULL) << CHAR_BIT;
6790 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6800 num = shellparam.nparam;
6808 goto check_1char_name;
6810 expdest = makestrspace(NOPTS, expdest);
6811 for (i = NOPTS - 1; i >= 0; i--) {
6813 USTPUTC(optletters(i), expdest);
6819 /* handles cases similar to ${#$1} */
6820 if (name[2] != '\0')
6821 raise_error_syntax("bad substitution");
6834 sep |= ifsset() ? ifsval()[0] : ' ';
6841 while ((p = *ap++) != NULL) {
6842 len += strtodest(p, syntax, quotes);
6846 memtodest(&sepc, 1, syntax, quotes);
6861 num = atoi(name); /* number(name) fails on ${N#str} etc */
6862 if (num < 0 || num > shellparam.nparam)
6864 p = num ? shellparam.p[num - 1] : arg0;
6867 /* NB: name has form "VAR=..." */
6869 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6870 * which should be considered before we check variables. */
6872 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6876 str = var_str_list->text;
6877 eq = strchr(str, '=');
6878 if (!eq) /* stop at first non-assignment */
6881 if (name_len == (unsigned)(eq - str)
6882 && strncmp(str, name, name_len) == 0
6885 /* goto value; - WRONG! */
6886 /* think "A=1 A=2 B=$A" */
6888 var_str_list = var_str_list->next;
6889 } while (var_str_list);
6893 p = lookupvar(name);
6898 len = strtodest(p, syntax, quotes);
6899 #if ENABLE_UNICODE_SUPPORT
6900 if (subtype == VSLENGTH && len > 0) {
6901 reinit_unicode_for_ash();
6902 if (unicode_status == UNICODE_ON) {
6903 STADJUST(-len, expdest);
6905 len = unicode_strlen(p);
6913 STADJUST(-len, expdest);
6918 * Expand a variable, and return a pointer to the next character in the
6922 evalvar(char *p, int flag, struct strlist *var_str_list)
6933 varflags = (unsigned char) *p++;
6934 subtype = varflags & VSTYPE;
6937 raise_error_syntax("bad substitution");
6939 quoted = flag & EXP_QUOTED;
6941 easy = (!quoted || (*var == '@' && shellparam.nparam));
6942 startloc = expdest - (char *)stackblock();
6943 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6946 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
6947 if (varflags & VSNUL)
6950 if (subtype == VSPLUS) {
6951 varlen = -1 - varlen;
6955 if (subtype == VSMINUS) {
6960 flag | EXP_TILDE | EXP_WORD,
6968 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6972 subevalvar(p, var, 0, subtype, startloc, varflags,
6973 flag & ~QUOTES_ESC, var_str_list);
6976 * Remove any recorded regions beyond
6979 removerecordregions(startloc);
6983 if (varlen < 0 && uflag)
6984 varunset(p, var, 0, 0);
6986 if (subtype == VSLENGTH) {
6987 cvtnum(varlen > 0 ? varlen : 0);
6991 if (subtype == VSNORMAL) {
6995 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7004 case VSTRIMRIGHTMAX:
7005 #if ENABLE_ASH_BASH_COMPAT
7018 * Terminate the string and start recording the pattern
7021 STPUTC('\0', expdest);
7022 patloc = expdest - (char *)stackblock();
7023 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7024 startloc, varflags, flag, var_str_list)) {
7025 int amount = expdest - (
7026 (char *)stackblock() + patloc - 1
7028 STADJUST(-amount, expdest);
7030 /* Remove any recorded regions beyond start of variable */
7031 removerecordregions(startloc);
7036 if (subtype != VSNORMAL) { /* skip to end of alternative */
7039 unsigned char c = *p++;
7042 else if (c == CTLBACKQ) {
7044 argbackq = argbackq->next;
7045 } else if (c == CTLVAR) {
7046 if ((*p++ & VSTYPE) != VSNORMAL)
7048 } else if (c == CTLENDVAR) {
7058 * Add a file name to the list.
7061 addfname(const char *name)
7065 sp = stzalloc(sizeof(*sp));
7066 sp->text = sstrdup(name);
7068 exparg.lastp = &sp->next;
7071 /* If we want to use glob() from libc... */
7072 #if !ENABLE_ASH_INTERNAL_GLOB
7074 /* Add the result of glob() to the list */
7076 addglob(const glob_t *pglob)
7078 char **p = pglob->gl_pathv;
7085 expandmeta(struct strlist *str /*, int flag*/)
7087 /* TODO - EXP_REDIR */
7097 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7112 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7113 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7114 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7116 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7117 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7118 // Which means you need to unescape the string, right? Not so fast:
7119 // if there _is_ a file named "file\?" (with backslash), it is returned
7120 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7121 // You DONT KNOW by looking at the result whether you need to unescape it.
7123 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7124 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7125 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7126 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7127 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7128 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7129 i = glob(p, 0, NULL, &pglob);
7130 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7135 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7136 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7137 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7149 *exparg.lastp = str;
7150 rmescapes(str->text, 0);
7151 exparg.lastp = &str->next;
7153 default: /* GLOB_NOSPACE */
7156 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7163 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7166 * Do metacharacter (i.e. *, ?, [...]) expansion.
7169 expmeta(char *expdir, char *enddir, char *name)
7185 for (p = name; esc = 0, *p; p += esc + 1) {
7186 if (*p == '*' || *p == '?')
7188 else if (*p == '[') {
7195 if (*q == '/' || *q == '\0')
7205 if (p[esc] == '/') {
7208 start = p + esc + 1;
7212 if (metaflag == 0) { /* we've reached the end of the file name */
7213 if (enddir != expdir)
7221 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7232 } while (p < start);
7234 if (enddir == expdir) {
7236 } else if (enddir == expdir + 1 && *expdir == '/') {
7245 if (enddir != expdir)
7247 if (*endname == 0) {
7260 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7261 if (dp->d_name[0] == '.' && !matchdot)
7263 if (pmatch(start, dp->d_name)) {
7265 strcpy(enddir, dp->d_name);
7268 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7271 expmeta(expdir, p, endname);
7277 endname[-esc - 1] = esc ? '\\' : '/';
7280 static struct strlist *
7281 msort(struct strlist *list, int len)
7283 struct strlist *p, *q = NULL;
7284 struct strlist **lpp;
7292 for (n = half; --n >= 0;) {
7296 q->next = NULL; /* terminate first half of list */
7297 q = msort(list, half); /* sort first half of list */
7298 p = msort(p, len - half); /* sort second half */
7301 #if ENABLE_LOCALE_SUPPORT
7302 if (strcoll(p->text, q->text) < 0)
7304 if (strcmp(p->text, q->text) < 0)
7328 * Sort the results of file name expansion. It calculates the number of
7329 * strings to sort and then calls msort (short for merge sort) to do the
7332 static struct strlist *
7333 expsort(struct strlist *str)
7339 for (sp = str; sp; sp = sp->next)
7341 return msort(str, len);
7345 expandmeta(struct strlist *str /*, int flag*/)
7347 static const char metachars[] ALIGN1 = {
7350 /* TODO - EXP_REDIR */
7354 struct strlist **savelastp;
7360 if (!strpbrk(str->text, metachars))
7362 savelastp = exparg.lastp;
7365 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7367 int i = strlen(str->text);
7368 //BUGGY estimation of how long expanded name can be
7369 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7371 expmeta(expdir, expdir, p);
7376 if (exparg.lastp == savelastp) {
7381 *exparg.lastp = str;
7382 rmescapes(str->text, 0);
7383 exparg.lastp = &str->next;
7385 *exparg.lastp = NULL;
7386 *savelastp = sp = expsort(*savelastp);
7387 while (sp->next != NULL)
7389 exparg.lastp = &sp->next;
7394 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7397 * Perform variable substitution and command substitution on an argument,
7398 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7399 * perform splitting and file name expansion. When arglist is NULL, perform
7400 * here document expansion.
7403 expandarg(union node *arg, struct arglist *arglist, int flag)
7408 argbackq = arg->narg.backquote;
7409 STARTSTACKSTR(expdest);
7410 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7411 argstr(arg->narg.text, flag,
7412 /* var_str_list: */ arglist ? arglist->list : NULL);
7413 p = _STPUTC('\0', expdest);
7415 if (arglist == NULL) {
7416 /* here document expanded */
7419 p = grabstackstr(p);
7420 TRACE(("expandarg: p:'%s'\n", p));
7421 exparg.lastp = &exparg.list;
7425 if (flag & EXP_FULL) {
7426 ifsbreakup(p, &exparg);
7427 *exparg.lastp = NULL;
7428 exparg.lastp = &exparg.list;
7429 expandmeta(exparg.list /*, flag*/);
7431 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7433 TRACE(("expandarg: rmescapes:'%s'\n", p));
7435 sp = stzalloc(sizeof(*sp));
7438 exparg.lastp = &sp->next;
7440 *exparg.lastp = NULL;
7442 *arglist->lastp = exparg.list;
7443 arglist->lastp = exparg.lastp;
7451 * Expand shell variables and backquotes inside a here document.
7454 expandhere(union node *arg, int fd)
7456 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7457 full_write(fd, stackblock(), expdest - (char *)stackblock());
7461 * Returns true if the pattern matches the string.
7464 patmatch(char *pattern, const char *string)
7466 return pmatch(preglob(pattern, 0), string);
7470 * See if a pattern matches in a case statement.
7473 casematch(union node *pattern, char *val)
7475 struct stackmark smark;
7478 setstackmark(&smark);
7479 argbackq = pattern->narg.backquote;
7480 STARTSTACKSTR(expdest);
7481 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7482 /* var_str_list: */ NULL);
7483 STACKSTRNUL(expdest);
7485 result = patmatch(stackblock(), val);
7486 popstackmark(&smark);
7491 /* ============ find_command */
7495 int (*builtin)(int, char **) FAST_FUNC;
7496 /* unsigned flags; */
7498 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7499 /* "regular" builtins always take precedence over commands,
7500 * regardless of PATH=....%builtin... position */
7501 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7502 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7505 smallint cmdtype; /* CMDxxx */
7508 /* index >= 0 for commands without path (slashes) */
7509 /* (TODO: what exactly does the value mean? PATH position?) */
7510 /* index == -1 for commands with slashes */
7511 /* index == (-2 - applet_no) for NOFORK applets */
7512 const struct builtincmd *cmd;
7513 struct funcnode *func;
7516 /* values of cmdtype */
7517 #define CMDUNKNOWN -1 /* no entry in table for command */
7518 #define CMDNORMAL 0 /* command is an executable program */
7519 #define CMDFUNCTION 1 /* command is a shell function */
7520 #define CMDBUILTIN 2 /* command is a shell builtin */
7522 /* action to find_command() */
7523 #define DO_ERR 0x01 /* prints errors */
7524 #define DO_ABS 0x02 /* checks absolute paths */
7525 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7526 #define DO_ALTPATH 0x08 /* using alternate path */
7527 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7529 static void find_command(char *, struct cmdentry *, int, const char *);
7532 /* ============ Hashing commands */
7535 * When commands are first encountered, they are entered in a hash table.
7536 * This ensures that a full path search will not have to be done for them
7537 * on each invocation.
7539 * We should investigate converting to a linear search, even though that
7540 * would make the command name "hash" a misnomer.
7544 struct tblentry *next; /* next entry in hash chain */
7545 union param param; /* definition of builtin function */
7546 smallint cmdtype; /* CMDxxx */
7547 char rehash; /* if set, cd done since entry created */
7548 char cmdname[1]; /* name of command */
7551 static struct tblentry **cmdtable;
7552 #define INIT_G_cmdtable() do { \
7553 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7556 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7560 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7562 #if ENABLE_FEATURE_SH_STANDALONE
7563 if (applet_no >= 0) {
7564 if (APPLET_IS_NOEXEC(applet_no)) {
7568 run_applet_no_and_exit(applet_no, argv);
7570 /* re-exec ourselves with the new arguments */
7571 execve(bb_busybox_exec_path, argv, envp);
7572 /* If they called chroot or otherwise made the binary no longer
7573 * executable, fall through */
7580 execve(cmd, argv, envp);
7581 } while (errno == EINTR);
7583 execve(cmd, argv, envp);
7585 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7586 /* Run "cmd" as a shell script:
7587 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7588 * "If the execve() function fails with ENOEXEC, the shell
7589 * shall execute a command equivalent to having a shell invoked
7590 * with the command name as its first operand,
7591 * with any remaining arguments passed to the new shell"
7593 * That is, do not use $SHELL, user's shell, or /bin/sh;
7594 * just call ourselves.
7596 * Note that bash reads ~80 chars of the file, and if it sees
7597 * a zero byte before it sees newline, it doesn't try to
7598 * interpret it, but fails with "cannot execute binary file"
7599 * message and exit code 126. For one, this prevents attempts
7600 * to interpret foreign ELF binaries as shell scripts.
7603 cmd = (char*) bb_busybox_exec_path;
7604 /* NB: this is only possible because all callers of shellexec()
7605 * ensure that the argv[-1] slot exists!
7608 argv[0] = (char*) "ash";
7614 * Exec a program. Never returns. If you change this routine, you may
7615 * have to change the find_command routine as well.
7616 * argv[-1] must exist and be writable! See tryexec() for why.
7618 static void shellexec(char **, const char *, int) NORETURN;
7620 shellexec(char **argv, const char *path, int idx)
7626 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7628 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7629 if (strchr(argv[0], '/') != NULL
7630 #if ENABLE_FEATURE_SH_STANDALONE
7631 || (applet_no = find_applet_by_name(argv[0])) >= 0
7634 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7635 if (applet_no >= 0) {
7636 /* We tried execing ourself, but it didn't work.
7637 * Maybe /proc/self/exe doesn't exist?
7646 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7647 if (--idx < 0 && pathopt == NULL) {
7648 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7649 if (errno != ENOENT && errno != ENOTDIR)
7656 /* Map to POSIX errors */
7668 exitstatus = exerrno;
7669 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7670 argv[0], e, suppress_int));
7671 ash_msg_and_raise(EXEXIT, "%s: %s", argv[0], errmsg(e, "not found"));
7676 printentry(struct tblentry *cmdp)
7682 idx = cmdp->param.index;
7685 name = path_advance(&path, cmdp->cmdname);
7687 } while (--idx >= 0);
7688 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7692 * Clear out command entries. The argument specifies the first entry in
7693 * PATH which has changed.
7696 clearcmdentry(int firstchange)
7698 struct tblentry **tblp;
7699 struct tblentry **pp;
7700 struct tblentry *cmdp;
7703 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7705 while ((cmdp = *pp) != NULL) {
7706 if ((cmdp->cmdtype == CMDNORMAL &&
7707 cmdp->param.index >= firstchange)
7708 || (cmdp->cmdtype == CMDBUILTIN &&
7709 builtinloc >= firstchange)
7722 * Locate a command in the command hash table. If "add" is nonzero,
7723 * add the command to the table if it is not already present. The
7724 * variable "lastcmdentry" is set to point to the address of the link
7725 * pointing to the entry, so that delete_cmd_entry can delete the
7728 * Interrupts must be off if called with add != 0.
7730 static struct tblentry **lastcmdentry;
7732 static struct tblentry *
7733 cmdlookup(const char *name, int add)
7735 unsigned int hashval;
7737 struct tblentry *cmdp;
7738 struct tblentry **pp;
7741 hashval = (unsigned char)*p << 4;
7743 hashval += (unsigned char)*p++;
7745 pp = &cmdtable[hashval % CMDTABLESIZE];
7746 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7747 if (strcmp(cmdp->cmdname, name) == 0)
7751 if (add && cmdp == NULL) {
7752 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7754 /* + 1 - already done because
7755 * tblentry::cmdname is char[1] */);
7756 /*cmdp->next = NULL; - ckzalloc did it */
7757 cmdp->cmdtype = CMDUNKNOWN;
7758 strcpy(cmdp->cmdname, name);
7765 * Delete the command entry returned on the last lookup.
7768 delete_cmd_entry(void)
7770 struct tblentry *cmdp;
7773 cmdp = *lastcmdentry;
7774 *lastcmdentry = cmdp->next;
7775 if (cmdp->cmdtype == CMDFUNCTION)
7776 freefunc(cmdp->param.func);
7782 * Add a new command entry, replacing any existing command entry for
7783 * the same name - except special builtins.
7786 addcmdentry(char *name, struct cmdentry *entry)
7788 struct tblentry *cmdp;
7790 cmdp = cmdlookup(name, 1);
7791 if (cmdp->cmdtype == CMDFUNCTION) {
7792 freefunc(cmdp->param.func);
7794 cmdp->cmdtype = entry->cmdtype;
7795 cmdp->param = entry->u;
7799 static int FAST_FUNC
7800 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7802 struct tblentry **pp;
7803 struct tblentry *cmdp;
7805 struct cmdentry entry;
7808 if (nextopt("r") != '\0') {
7813 if (*argptr == NULL) {
7814 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7815 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7816 if (cmdp->cmdtype == CMDNORMAL)
7824 while ((name = *argptr) != NULL) {
7825 cmdp = cmdlookup(name, 0);
7827 && (cmdp->cmdtype == CMDNORMAL
7828 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7832 find_command(name, &entry, DO_ERR, pathval());
7833 if (entry.cmdtype == CMDUNKNOWN)
7841 * Called when a cd is done. Marks all commands so the next time they
7842 * are executed they will be rehashed.
7847 struct tblentry **pp;
7848 struct tblentry *cmdp;
7850 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7851 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7852 if (cmdp->cmdtype == CMDNORMAL
7853 || (cmdp->cmdtype == CMDBUILTIN
7854 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7864 * Fix command hash table when PATH changed.
7865 * Called before PATH is changed. The argument is the new value of PATH;
7866 * pathval() still returns the old value at this point.
7867 * Called with interrupts off.
7869 static void FAST_FUNC
7870 changepath(const char *new)
7878 firstchange = 9999; /* assume no change */
7884 if ((*old == '\0' && *new == ':')
7885 || (*old == ':' && *new == '\0')
7889 old = new; /* ignore subsequent differences */
7893 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7900 if (builtinloc < 0 && idx_bltin >= 0)
7901 builtinloc = idx_bltin; /* zap builtins */
7902 if (builtinloc >= 0 && idx_bltin < 0)
7904 clearcmdentry(firstchange);
7905 builtinloc = idx_bltin;
7930 #if ENABLE_ASH_BASH_COMPAT
7941 typedef smallint token_id_t;
7943 /* Nth bit indicates if token marks the end of a list */
7946 /* 0 */ | (1u << TEOF)
7947 /* 1 */ | (0u << TNL)
7948 /* 2 */ | (0u << TREDIR)
7949 /* 3 */ | (0u << TWORD)
7950 /* 4 */ | (0u << TSEMI)
7951 /* 5 */ | (0u << TBACKGND)
7952 /* 6 */ | (0u << TAND)
7953 /* 7 */ | (0u << TOR)
7954 /* 8 */ | (0u << TPIPE)
7955 /* 9 */ | (0u << TLP)
7956 /* 10 */ | (1u << TRP)
7957 /* 11 */ | (1u << TENDCASE)
7958 /* 12 */ | (1u << TENDBQUOTE)
7959 /* 13 */ | (0u << TNOT)
7960 /* 14 */ | (0u << TCASE)
7961 /* 15 */ | (1u << TDO)
7962 /* 16 */ | (1u << TDONE)
7963 /* 17 */ | (1u << TELIF)
7964 /* 18 */ | (1u << TELSE)
7965 /* 19 */ | (1u << TESAC)
7966 /* 20 */ | (1u << TFI)
7967 /* 21 */ | (0u << TFOR)
7968 #if ENABLE_ASH_BASH_COMPAT
7969 /* 22 */ | (0u << TFUNCTION)
7971 /* 23 */ | (0u << TIF)
7972 /* 24 */ | (0u << TIN)
7973 /* 25 */ | (1u << TTHEN)
7974 /* 26 */ | (0u << TUNTIL)
7975 /* 27 */ | (0u << TWHILE)
7976 /* 28 */ | (0u << TBEGIN)
7977 /* 29 */ | (1u << TEND)
7978 , /* thus far 29 bits used */
7981 static const char *const tokname_array[] = {
7995 #define KWDOFFSET 13
7996 /* the following are keywords */
8006 #if ENABLE_ASH_BASH_COMPAT
8018 /* Wrapper around strcmp for qsort/bsearch/... */
8020 pstrcmp(const void *a, const void *b)
8022 return strcmp((char*)a, *(char**)b);
8025 static const char *const *
8026 findkwd(const char *s)
8028 return bsearch(s, tokname_array + KWDOFFSET,
8029 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8030 sizeof(tokname_array[0]), pstrcmp);
8034 * Locate and print what a word is...
8037 describe_command(char *command, const char *path, int describe_command_verbose)
8039 struct cmdentry entry;
8040 struct tblentry *cmdp;
8041 #if ENABLE_ASH_ALIAS
8042 const struct alias *ap;
8045 path = path ? path : pathval();
8047 if (describe_command_verbose) {
8051 /* First look at the keywords */
8052 if (findkwd(command)) {
8053 out1str(describe_command_verbose ? " is a shell keyword" : command);
8057 #if ENABLE_ASH_ALIAS
8058 /* Then look at the aliases */
8059 ap = lookupalias(command, 0);
8061 if (!describe_command_verbose) {
8066 out1fmt(" is an alias for %s", ap->val);
8070 /* Then check if it is a tracked alias */
8071 cmdp = cmdlookup(command, 0);
8073 entry.cmdtype = cmdp->cmdtype;
8074 entry.u = cmdp->param;
8076 /* Finally use brute force */
8077 find_command(command, &entry, DO_ABS, path);
8080 switch (entry.cmdtype) {
8082 int j = entry.u.index;
8088 p = path_advance(&path, command);
8092 if (describe_command_verbose) {
8094 (cmdp ? " a tracked alias for" : nullstr), p
8103 if (describe_command_verbose) {
8104 out1str(" is a shell function");
8111 if (describe_command_verbose) {
8112 out1fmt(" is a %sshell builtin",
8113 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8114 "special " : nullstr
8122 if (describe_command_verbose) {
8123 out1str(": not found\n");
8132 static int FAST_FUNC
8133 typecmd(int argc UNUSED_PARAM, char **argv)
8139 /* type -p ... ? (we don't bother checking for 'p') */
8140 if (argv[1] && argv[1][0] == '-') {
8145 err |= describe_command(argv[i++], NULL, verbose);
8150 #if ENABLE_ASH_CMDCMD
8151 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8153 parse_command_args(char **argv, const char **path)
8166 if (c == '-' && !*cp) {
8174 *path = bb_default_path;
8177 /* run 'typecmd' for other options */
8186 static int FAST_FUNC
8187 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8195 const char *path = NULL;
8197 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8198 * never reaches this function.
8201 while ((c = nextopt("pvV")) != '\0')
8203 verify |= VERIFY_VERBOSE;
8205 /*verify |= VERIFY_BRIEF*/;
8211 path = bb_default_path;
8213 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8215 if (/*verify && */ cmd)
8216 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8223 /*static int funcblocksize; // size of structures in function */
8224 /*static int funcstringsize; // size of strings in node */
8225 static void *funcblock; /* block to allocate function from */
8226 static char *funcstring_end; /* end of block to allocate strings from */
8228 /* flags in argument to evaltree */
8229 #define EV_EXIT 01 /* exit after evaluating tree */
8230 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8232 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8233 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8234 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8235 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8236 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8237 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8238 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8239 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8240 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8241 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8242 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8243 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8244 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8245 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8246 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8247 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8248 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8249 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8250 #if ENABLE_ASH_BASH_COMPAT
8251 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8253 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8254 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8255 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8256 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8257 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8258 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8259 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8260 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8261 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8264 static int calcsize(int funcblocksize, union node *n);
8267 sizenodelist(int funcblocksize, struct nodelist *lp)
8270 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8271 funcblocksize = calcsize(funcblocksize, lp->n);
8274 return funcblocksize;
8278 calcsize(int funcblocksize, union node *n)
8281 return funcblocksize;
8282 funcblocksize += nodesize[n->type];
8285 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8286 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8287 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8290 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8295 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8296 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8303 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8304 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8307 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8308 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8309 funcblocksize = calcsize(funcblocksize, n->nif.test);
8312 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8313 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8314 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8317 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8318 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8321 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8322 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8323 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8327 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8328 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8329 funcblocksize = calcsize(funcblocksize, n->narg.next);
8332 #if ENABLE_ASH_BASH_COMPAT
8339 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8340 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8344 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8345 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8349 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8350 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8353 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8356 return funcblocksize;
8360 nodeckstrdup(char *s)
8362 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8363 return strcpy(funcstring_end, s);
8366 static union node *copynode(union node *);
8368 static struct nodelist *
8369 copynodelist(struct nodelist *lp)
8371 struct nodelist *start;
8372 struct nodelist **lpp;
8377 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8378 (*lpp)->n = copynode(lp->n);
8380 lpp = &(*lpp)->next;
8387 copynode(union node *n)
8394 funcblock = (char *) funcblock + nodesize[n->type];
8398 new->ncmd.redirect = copynode(n->ncmd.redirect);
8399 new->ncmd.args = copynode(n->ncmd.args);
8400 new->ncmd.assign = copynode(n->ncmd.assign);
8403 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8404 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8409 new->nredir.redirect = copynode(n->nredir.redirect);
8410 new->nredir.n = copynode(n->nredir.n);
8417 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8418 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8421 new->nif.elsepart = copynode(n->nif.elsepart);
8422 new->nif.ifpart = copynode(n->nif.ifpart);
8423 new->nif.test = copynode(n->nif.test);
8426 new->nfor.var = nodeckstrdup(n->nfor.var);
8427 new->nfor.body = copynode(n->nfor.body);
8428 new->nfor.args = copynode(n->nfor.args);
8431 new->ncase.cases = copynode(n->ncase.cases);
8432 new->ncase.expr = copynode(n->ncase.expr);
8435 new->nclist.body = copynode(n->nclist.body);
8436 new->nclist.pattern = copynode(n->nclist.pattern);
8437 new->nclist.next = copynode(n->nclist.next);
8441 new->narg.backquote = copynodelist(n->narg.backquote);
8442 new->narg.text = nodeckstrdup(n->narg.text);
8443 new->narg.next = copynode(n->narg.next);
8446 #if ENABLE_ASH_BASH_COMPAT
8453 new->nfile.fname = copynode(n->nfile.fname);
8454 new->nfile.fd = n->nfile.fd;
8455 new->nfile.next = copynode(n->nfile.next);
8459 new->ndup.vname = copynode(n->ndup.vname);
8460 new->ndup.dupfd = n->ndup.dupfd;
8461 new->ndup.fd = n->ndup.fd;
8462 new->ndup.next = copynode(n->ndup.next);
8466 new->nhere.doc = copynode(n->nhere.doc);
8467 new->nhere.fd = n->nhere.fd;
8468 new->nhere.next = copynode(n->nhere.next);
8471 new->nnot.com = copynode(n->nnot.com);
8474 new->type = n->type;
8479 * Make a copy of a parse tree.
8481 static struct funcnode *
8482 copyfunc(union node *n)
8487 /*funcstringsize = 0;*/
8488 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8489 f = ckzalloc(blocksize /* + funcstringsize */);
8490 funcblock = (char *) f + offsetof(struct funcnode, n);
8491 funcstring_end = (char *) f + blocksize;
8493 /* f->count = 0; - ckzalloc did it */
8498 * Define a shell function.
8501 defun(union node *func)
8503 struct cmdentry entry;
8506 entry.cmdtype = CMDFUNCTION;
8507 entry.u.func = copyfunc(func);
8508 addcmdentry(func->narg.text, &entry);
8512 /* Reasons for skipping commands (see comment on breakcmd routine) */
8513 #define SKIPBREAK (1 << 0)
8514 #define SKIPCONT (1 << 1)
8515 #define SKIPFUNC (1 << 2)
8516 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8517 static int skipcount; /* number of levels to skip */
8518 static int funcnest; /* depth of function calls */
8519 static int loopnest; /* current loop nesting level */
8521 /* Forward decl way out to parsing code - dotrap needs it */
8522 static int evalstring(char *s, int flags);
8524 /* Called to execute a trap.
8525 * Single callsite - at the end of evaltree().
8526 * If we return non-zero, evaltree raises EXEXIT exception.
8528 * Perhaps we should avoid entering new trap handlers
8529 * while we are executing a trap handler. [is it a TODO?]
8536 uint8_t last_status;
8541 last_status = exitstatus;
8545 TRACE(("dotrap entered\n"));
8546 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8558 /* non-trapped SIGINT is handled separately by raise_interrupt,
8559 * don't upset it by resetting gotsig[SIGINT-1] */
8560 if (sig == SIGINT && !p)
8563 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8569 exitstatus = last_status;
8570 TRACE(("dotrap returns\n"));
8573 /* forward declarations - evaluation is fairly recursive business... */
8574 static int evalloop(union node *, int);
8575 static int evalfor(union node *, int);
8576 static int evalcase(union node *, int);
8577 static int evalsubshell(union node *, int);
8578 static void expredir(union node *);
8579 static int evalpipe(union node *, int);
8580 static int evalcommand(union node *, int);
8581 static int evalbltin(const struct builtincmd *, int, char **, int);
8582 static void prehash(union node *);
8585 * Evaluate a parse tree. The value is left in the global variable
8589 evaltree(union node *n, int flags)
8592 int (*evalfn)(union node *, int);
8596 TRACE(("evaltree(NULL) called\n"));
8599 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8606 out1fmt("Node type = %d\n", n->type);
8611 status = !evaltree(n->nnot.com, EV_TESTED);
8614 expredir(n->nredir.redirect);
8615 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8617 status = evaltree(n->nredir.n, flags & EV_TESTED);
8619 if (n->nredir.redirect)
8620 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8623 evalfn = evalcommand;
8625 if (eflag && !(flags & EV_TESTED))
8637 evalfn = evalsubshell;
8650 #error NAND + 1 != NOR
8652 #if NOR + 1 != NSEMI
8653 #error NOR + 1 != NSEMI
8655 unsigned is_or = n->type - NAND;
8658 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8660 if ((!status) == is_or || evalskip)
8666 status = evalfn(n, flags);
8670 status = evaltree(n->nif.test, EV_TESTED);
8677 if (n->nif.elsepart) {
8678 n = n->nif.elsepart;
8685 /* Not necessary. To test it:
8686 * "false; f() { qwerty; }; echo $?" should print 0.
8690 exitstatus = status;
8694 /* Order of checks below is important:
8695 * signal handlers trigger before exit caused by "set -e".
8699 if (checkexit & status)
8700 raise_exception(EXEXIT);
8701 if (flags & EV_EXIT)
8702 raise_exception(EXEXIT);
8704 TRACE(("leaving evaltree (no interrupts)\n"));
8708 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8711 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8716 int skip = evalskip;
8723 if (--skipcount <= 0) {
8734 evalloop(union node *n, int flags)
8745 i = evaltree(n->nbinary.ch1, EV_TESTED);
8747 if (skip == SKIPFUNC)
8751 if (n->type != NWHILE)
8755 status = evaltree(n->nbinary.ch2, flags);
8757 } while (!(skip & ~SKIPCONT));
8764 evalfor(union node *n, int flags)
8766 struct arglist arglist;
8769 struct stackmark smark;
8772 setstackmark(&smark);
8773 arglist.list = NULL;
8774 arglist.lastp = &arglist.list;
8775 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8776 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8778 *arglist.lastp = NULL;
8782 for (sp = arglist.list; sp; sp = sp->next) {
8783 setvar0(n->nfor.var, sp->text);
8784 status = evaltree(n->nfor.body, flags);
8785 if (skiploop() & ~SKIPCONT)
8789 popstackmark(&smark);
8795 evalcase(union node *n, int flags)
8799 struct arglist arglist;
8800 struct stackmark smark;
8803 setstackmark(&smark);
8804 arglist.list = NULL;
8805 arglist.lastp = &arglist.list;
8806 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8807 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8808 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8809 if (casematch(patp, arglist.list->text)) {
8810 /* Ensure body is non-empty as otherwise
8811 * EV_EXIT may prevent us from setting the
8814 if (evalskip == 0 && cp->nclist.body) {
8815 status = evaltree(cp->nclist.body, flags);
8822 popstackmark(&smark);
8828 * Kick off a subshell to evaluate a tree.
8831 evalsubshell(union node *n, int flags)
8834 int backgnd = (n->type == NBACKGND);
8837 expredir(n->nredir.redirect);
8838 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8841 jp = makejob(/*n,*/ 1);
8842 if (forkshell(jp, n, backgnd) == 0) {
8847 flags &= ~EV_TESTED;
8849 redirect(n->nredir.redirect, 0);
8850 evaltreenr(n->nredir.n, flags);
8856 status = waitforjob(jp);
8862 * Compute the names of the files in a redirection list.
8864 static void fixredir(union node *, const char *, int);
8866 expredir(union node *n)
8870 for (redir = n; redir; redir = redir->nfile.next) {
8874 fn.lastp = &fn.list;
8875 switch (redir->type) {
8879 #if ENABLE_ASH_BASH_COMPAT
8884 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8885 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8886 #if ENABLE_ASH_BASH_COMPAT
8890 // By the design of stack allocator, the loop of this kind:
8891 // while true; do while true; do break; done </dev/null; done
8892 // will look like a memory leak: ash plans to free expfname's
8893 // of "/dev/null" as soon as it finishes running the loop
8894 // (in this case, never).
8895 // This "fix" is wrong:
8896 if (redir->nfile.expfname)
8897 stunalloc(redir->nfile.expfname);
8898 // It results in corrupted state of stacked allocations.
8900 redir->nfile.expfname = fn.list->text;
8903 case NTOFD: /* >& */
8904 if (redir->ndup.vname) {
8905 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8906 if (fn.list == NULL)
8907 ash_msg_and_raise_error("redir error");
8908 #if ENABLE_ASH_BASH_COMPAT
8909 //FIXME: we used expandarg with different args!
8910 if (!isdigit_str9(fn.list->text)) {
8911 /* >&file, not >&fd */
8912 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8913 ash_msg_and_raise_error("redir error");
8915 goto store_expfname;
8918 fixredir(redir, fn.list->text, 1);
8926 * Evaluate a pipeline. All the processes in the pipeline are children
8927 * of the process creating the pipeline. (This differs from some versions
8928 * of the shell, which make the last process in a pipeline the parent
8932 evalpipe(union node *n, int flags)
8935 struct nodelist *lp;
8941 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8943 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8947 jp = makejob(/*n,*/ pipelen);
8949 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8953 if (pipe(pip) < 0) {
8955 ash_msg_and_raise_error("pipe call failed");
8958 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8972 evaltreenr(lp->n, flags);
8979 /* Don't want to trigger debugging */
8983 if (n->npipe.pipe_backgnd == 0) {
8984 status = waitforjob(jp);
8985 TRACE(("evalpipe: job done exit status %d\n", status));
8993 * Controls whether the shell is interactive or not.
8996 setinteractive(int on)
8998 static smallint is_interactive;
9000 if (++on == is_interactive)
9002 is_interactive = on;
9006 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9007 if (is_interactive > 1) {
9008 /* Looks like they want an interactive shell */
9009 static smallint did_banner;
9012 /* note: ash and hush share this string */
9013 out1fmt("\n\n%s %s\n"
9014 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9017 "built-in shell (ash)"
9031 setinteractive(iflag);
9033 #if ENABLE_FEATURE_EDITING_VI
9035 line_input_state->flags |= VI_MODE;
9037 line_input_state->flags &= ~VI_MODE;
9039 viflag = 0; /* forcibly keep the option off */
9043 static struct localvar *localvars;
9046 * Called after a function returns.
9047 * Interrupts must be off.
9052 struct localvar *lvp;
9055 while ((lvp = localvars) != NULL) {
9056 localvars = lvp->next;
9058 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9059 if (vp == NULL) { /* $- saved */
9060 memcpy(optlist, lvp->text, sizeof(optlist));
9061 free((char*)lvp->text);
9063 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9064 unsetvar(vp->var_text);
9067 vp->var_func(var_end(lvp->text));
9068 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9069 free((char*)vp->var_text);
9070 vp->flags = lvp->flags;
9071 vp->var_text = lvp->text;
9078 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9080 volatile struct shparam saveparam;
9081 struct localvar *volatile savelocalvars;
9082 struct jmploc *volatile savehandler;
9083 struct jmploc jmploc;
9086 saveparam = shellparam;
9087 savelocalvars = localvars;
9088 savehandler = exception_handler;
9089 e = setjmp(jmploc.loc);
9094 exception_handler = &jmploc;
9096 shellparam.malloced = 0;
9100 shellparam.nparam = argc - 1;
9101 shellparam.p = argv + 1;
9102 #if ENABLE_ASH_GETOPTS
9103 shellparam.optind = 1;
9104 shellparam.optoff = -1;
9106 evaltree(func->n.narg.next, flags & EV_TESTED);
9112 localvars = savelocalvars;
9113 freeparam(&shellparam);
9114 shellparam = saveparam;
9115 exception_handler = savehandler;
9117 evalskip &= ~SKIPFUNC;
9122 * Make a variable a local variable. When a variable is made local, it's
9123 * value and flags are saved in a localvar structure. The saved values
9124 * will be restored when the shell function returns. We handle the name
9125 * "-" as a special case: it makes changes to "set +-options" local
9126 * (options will be restored on return from the function).
9131 struct localvar *lvp;
9134 char *eq = strchr(name, '=');
9137 /* Cater for duplicate "local". Examples:
9138 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9139 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9143 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9147 * it's a duplicate "local VAR" declaration, do nothing
9154 lvp = ckzalloc(sizeof(*lvp));
9155 if (LONE_DASH(name)) {
9157 p = ckmalloc(sizeof(optlist));
9158 lvp->text = memcpy(p, optlist, sizeof(optlist));
9161 vpp = hashvar(name);
9162 vp = *findvar(vpp, name);
9164 /* variable did not exist yet */
9166 setvareq(name, VSTRFIXED);
9168 setvar(name, NULL, VSTRFIXED);
9169 vp = *vpp; /* the new variable */
9170 lvp->flags = VUNSET;
9172 lvp->text = vp->var_text;
9173 lvp->flags = vp->flags;
9174 /* make sure neither "struct var" nor string gets freed
9175 * during (un)setting:
9177 vp->flags |= VSTRFIXED|VTEXTFIXED;
9181 /* "local VAR" unsets VAR: */
9182 setvar0(name, NULL);
9186 lvp->next = localvars;
9193 * The "local" command.
9195 static int FAST_FUNC
9196 localcmd(int argc UNUSED_PARAM, char **argv)
9201 ash_msg_and_raise_error("not in a function");
9204 while ((name = *argv++) != NULL) {
9210 static int FAST_FUNC
9211 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9216 static int FAST_FUNC
9217 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9222 static int FAST_FUNC
9223 execcmd(int argc UNUSED_PARAM, char **argv)
9226 iflag = 0; /* exit on error */
9229 /* We should set up signals for "exec CMD"
9230 * the same way as for "CMD" without "exec".
9231 * But optschanged->setinteractive->setsignal
9232 * still thought we are a root shell. Therefore, for example,
9233 * SIGQUIT is still set to IGN. Fix it:
9237 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9238 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9239 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9241 shellexec(argv + 1, pathval(), 0);
9248 * The return command.
9250 static int FAST_FUNC
9251 returncmd(int argc UNUSED_PARAM, char **argv)
9254 * If called outside a function, do what ksh does;
9255 * skip the rest of the file.
9257 evalskip = SKIPFUNC;
9258 return argv[1] ? number(argv[1]) : exitstatus;
9261 /* Forward declarations for builtintab[] */
9262 static int breakcmd(int, char **) FAST_FUNC;
9263 static int dotcmd(int, char **) FAST_FUNC;
9264 static int evalcmd(int, char **, int) FAST_FUNC;
9265 static int exitcmd(int, char **) FAST_FUNC;
9266 static int exportcmd(int, char **) FAST_FUNC;
9267 #if ENABLE_ASH_GETOPTS
9268 static int getoptscmd(int, char **) FAST_FUNC;
9271 static int helpcmd(int, char **) FAST_FUNC;
9274 static int historycmd(int, char **) FAST_FUNC;
9276 #if ENABLE_FEATURE_SH_MATH
9277 static int letcmd(int, char **) FAST_FUNC;
9279 static int readcmd(int, char **) FAST_FUNC;
9280 static int setcmd(int, char **) FAST_FUNC;
9281 static int shiftcmd(int, char **) FAST_FUNC;
9282 static int timescmd(int, char **) FAST_FUNC;
9283 static int trapcmd(int, char **) FAST_FUNC;
9284 static int umaskcmd(int, char **) FAST_FUNC;
9285 static int unsetcmd(int, char **) FAST_FUNC;
9286 static int ulimitcmd(int, char **) FAST_FUNC;
9288 #define BUILTIN_NOSPEC "0"
9289 #define BUILTIN_SPECIAL "1"
9290 #define BUILTIN_REGULAR "2"
9291 #define BUILTIN_SPEC_REG "3"
9292 #define BUILTIN_ASSIGN "4"
9293 #define BUILTIN_SPEC_ASSG "5"
9294 #define BUILTIN_REG_ASSG "6"
9295 #define BUILTIN_SPEC_REG_ASSG "7"
9297 /* Stubs for calling non-FAST_FUNC's */
9298 #if ENABLE_ASH_BUILTIN_ECHO
9299 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9301 #if ENABLE_ASH_BUILTIN_PRINTF
9302 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9304 #if ENABLE_ASH_BUILTIN_TEST
9305 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9308 /* Keep these in proper order since it is searched via bsearch() */
9309 static const struct builtincmd builtintab[] = {
9310 { BUILTIN_SPEC_REG "." , dotcmd },
9311 { BUILTIN_SPEC_REG ":" , truecmd },
9312 #if ENABLE_ASH_BUILTIN_TEST
9313 { BUILTIN_REGULAR "[" , testcmd },
9314 # if ENABLE_ASH_BASH_COMPAT
9315 { BUILTIN_REGULAR "[[" , testcmd },
9318 #if ENABLE_ASH_ALIAS
9319 { BUILTIN_REG_ASSG "alias" , aliascmd },
9322 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9324 { BUILTIN_SPEC_REG "break" , breakcmd },
9325 { BUILTIN_REGULAR "cd" , cdcmd },
9326 { BUILTIN_NOSPEC "chdir" , cdcmd },
9327 #if ENABLE_ASH_CMDCMD
9328 { BUILTIN_REGULAR "command" , commandcmd },
9330 { BUILTIN_SPEC_REG "continue", breakcmd },
9331 #if ENABLE_ASH_BUILTIN_ECHO
9332 { BUILTIN_REGULAR "echo" , echocmd },
9334 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9335 { BUILTIN_SPEC_REG "exec" , execcmd },
9336 { BUILTIN_SPEC_REG "exit" , exitcmd },
9337 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9338 { BUILTIN_REGULAR "false" , falsecmd },
9340 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9342 #if ENABLE_ASH_GETOPTS
9343 { BUILTIN_REGULAR "getopts" , getoptscmd },
9345 { BUILTIN_NOSPEC "hash" , hashcmd },
9347 { BUILTIN_NOSPEC "help" , helpcmd },
9350 { BUILTIN_NOSPEC "history" , historycmd },
9353 { BUILTIN_REGULAR "jobs" , jobscmd },
9354 { BUILTIN_REGULAR "kill" , killcmd },
9356 #if ENABLE_FEATURE_SH_MATH
9357 { BUILTIN_NOSPEC "let" , letcmd },
9359 { BUILTIN_ASSIGN "local" , localcmd },
9360 #if ENABLE_ASH_BUILTIN_PRINTF
9361 { BUILTIN_REGULAR "printf" , printfcmd },
9363 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9364 { BUILTIN_REGULAR "read" , readcmd },
9365 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9366 { BUILTIN_SPEC_REG "return" , returncmd },
9367 { BUILTIN_SPEC_REG "set" , setcmd },
9368 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9369 #if ENABLE_ASH_BASH_COMPAT
9370 { BUILTIN_SPEC_REG "source" , dotcmd },
9372 #if ENABLE_ASH_BUILTIN_TEST
9373 { BUILTIN_REGULAR "test" , testcmd },
9375 { BUILTIN_SPEC_REG "times" , timescmd },
9376 { BUILTIN_SPEC_REG "trap" , trapcmd },
9377 { BUILTIN_REGULAR "true" , truecmd },
9378 { BUILTIN_NOSPEC "type" , typecmd },
9379 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9380 { BUILTIN_REGULAR "umask" , umaskcmd },
9381 #if ENABLE_ASH_ALIAS
9382 { BUILTIN_REGULAR "unalias" , unaliascmd },
9384 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9385 { BUILTIN_REGULAR "wait" , waitcmd },
9388 /* Should match the above table! */
9389 #define COMMANDCMD (builtintab + \
9391 /* [ */ 1 * ENABLE_ASH_BUILTIN_TEST + \
9392 /* [[ */ 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9393 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9394 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9395 /* break cd cddir */ 3)
9396 #define EVALCMD (COMMANDCMD + \
9397 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9398 /* continue */ 1 + \
9399 /* echo */ 1 * ENABLE_ASH_BUILTIN_ECHO + \
9401 #define EXECCMD (EVALCMD + \
9405 * Search the table of builtin commands.
9408 pstrcmp1(const void *a, const void *b)
9410 return strcmp((char*)a, *(char**)b + 1);
9412 static struct builtincmd *
9413 find_builtin(const char *name)
9415 struct builtincmd *bp;
9418 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9425 * Execute a simple command.
9428 isassignment(const char *p)
9430 const char *q = endofname(p);
9435 static int FAST_FUNC
9436 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9438 /* Preserve exitstatus of a previous possible redirection
9439 * as POSIX mandates */
9440 return back_exitstatus;
9443 evalcommand(union node *cmd, int flags)
9445 static const struct builtincmd null_bltin = {
9446 "\0\0", bltincmd /* why three NULs? */
9448 struct stackmark smark;
9450 struct arglist arglist;
9451 struct arglist varlist;
9454 const struct strlist *sp;
9455 struct cmdentry cmdentry;
9462 struct builtincmd *bcmd;
9463 smallint cmd_is_exec;
9464 smallint pseudovarflag = 0;
9466 /* First expand the arguments. */
9467 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9468 setstackmark(&smark);
9469 back_exitstatus = 0;
9471 cmdentry.cmdtype = CMDBUILTIN;
9472 cmdentry.u.cmd = &null_bltin;
9473 varlist.lastp = &varlist.list;
9474 *varlist.lastp = NULL;
9475 arglist.lastp = &arglist.list;
9476 *arglist.lastp = NULL;
9479 if (cmd->ncmd.args) {
9480 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9481 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9484 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9485 struct strlist **spp;
9487 spp = arglist.lastp;
9488 if (pseudovarflag && isassignment(argp->narg.text))
9489 expandarg(argp, &arglist, EXP_VARTILDE);
9491 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9493 for (sp = *spp; sp; sp = sp->next)
9497 /* Reserve one extra spot at the front for shellexec. */
9498 nargv = stalloc(sizeof(char *) * (argc + 2));
9500 for (sp = arglist.list; sp; sp = sp->next) {
9501 TRACE(("evalcommand arg: %s\n", sp->text));
9502 *nargv++ = sp->text;
9507 if (iflag && funcnest == 0 && argc > 0)
9508 lastarg = nargv[-1];
9511 expredir(cmd->ncmd.redirect);
9512 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9514 path = vpath.var_text;
9515 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9516 struct strlist **spp;
9519 spp = varlist.lastp;
9520 expandarg(argp, &varlist, EXP_VARTILDE);
9523 * Modify the command lookup path, if a PATH= assignment
9527 if (varcmp(p, path) == 0)
9531 /* Print the command if xflag is set. */
9534 const char *p = " %s" + 1;
9536 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9538 for (n = 0; n < 2; n++) {
9540 fdprintf(preverrout_fd, p, sp->text);
9546 safe_write(preverrout_fd, "\n", 1);
9552 /* Now locate the command. */
9554 int cmd_flag = DO_ERR;
9555 #if ENABLE_ASH_CMDCMD
9556 const char *oldpath = path + 5;
9560 find_command(argv[0], &cmdentry, cmd_flag, path);
9561 if (cmdentry.cmdtype == CMDUNKNOWN) {
9562 flush_stdout_stderr();
9567 /* implement bltin and command here */
9568 if (cmdentry.cmdtype != CMDBUILTIN)
9571 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9572 if (cmdentry.u.cmd == EXECCMD)
9574 #if ENABLE_ASH_CMDCMD
9575 if (cmdentry.u.cmd == COMMANDCMD) {
9577 nargv = parse_command_args(argv, &path);
9580 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9581 * nargv => "PROG". path is updated if -p.
9583 argc -= nargv - argv;
9585 cmd_flag |= DO_NOFUNC;
9594 exitstatus = status;
9596 /* We have a redirection error. */
9598 raise_exception(EXERROR);
9603 /* Execute the command. */
9604 switch (cmdentry.cmdtype) {
9607 #if ENABLE_FEATURE_SH_NOFORK
9608 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9609 * around run_nofork_applet() call.
9610 * (2) Should this check also be done in forkshell()?
9611 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9613 /* find_command() encodes applet_no as (-2 - applet_no) */
9614 int applet_no = (- cmdentry.u.index - 2);
9615 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9616 listsetvar(varlist.list, VEXPORT|VSTACK);
9617 /* run <applet>_main() */
9618 status = run_nofork_applet(applet_no, argv);
9622 /* Can we avoid forking off? For example, very last command
9623 * in a script or a subshell does not need forking,
9624 * we can just exec it.
9626 if (!(flags & EV_EXIT) || may_have_traps) {
9627 /* No, forking off a child is necessary */
9629 jp = makejob(/*cmd,*/ 1);
9630 if (forkshell(jp, cmd, FORK_FG) != 0) {
9632 status = waitforjob(jp);
9634 TRACE(("forked child exited with %d\n", status));
9639 /* fall through to exec'ing external program */
9641 listsetvar(varlist.list, VEXPORT|VSTACK);
9642 shellexec(argv, path, cmdentry.u.index);
9646 cmdenviron = varlist.list;
9648 struct strlist *list = cmdenviron;
9650 if (spclbltin > 0 || argc == 0) {
9652 if (cmd_is_exec && argc > 1)
9655 listsetvar(list, i);
9657 /* Tight loop with builtins only:
9658 * "while kill -0 $child; do true; done"
9659 * will never exit even if $child died, unless we do this
9660 * to reap the zombie and make kill detect that it's gone: */
9661 dowait(DOWAIT_NONBLOCK, NULL);
9663 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9664 if (exception_type == EXERROR && spclbltin <= 0) {
9669 longjmp(exception_handler->loc, 1);
9674 listsetvar(varlist.list, 0);
9675 /* See above for the rationale */
9676 dowait(DOWAIT_NONBLOCK, NULL);
9677 if (evalfun(cmdentry.u.func, argc, argv, flags))
9680 status = exitstatus;
9685 if (cmd->ncmd.redirect)
9686 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9688 /* dsl: I think this is intended to be used to support
9689 * '_' in 'vi' command mode during line editing...
9690 * However I implemented that within libedit itself.
9692 setvar0("_", lastarg);
9694 popstackmark(&smark);
9700 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9702 char *volatile savecmdname;
9703 struct jmploc *volatile savehandler;
9704 struct jmploc jmploc;
9708 savecmdname = commandname;
9709 savehandler = exception_handler;
9710 i = setjmp(jmploc.loc);
9713 exception_handler = &jmploc;
9714 commandname = argv[0];
9716 optptr = NULL; /* initialize nextopt */
9718 status = evalcmd(argc, argv, flags);
9720 status = (*cmd->builtin)(argc, argv);
9721 flush_stdout_stderr();
9722 status |= ferror(stdout);
9723 exitstatus = status;
9726 commandname = savecmdname;
9727 exception_handler = savehandler;
9733 goodname(const char *p)
9735 return endofname(p)[0] == '\0';
9740 * Search for a command. This is called before we fork so that the
9741 * location of the command will be available in the parent as well as
9742 * the child. The check for "goodname" is an overly conservative
9743 * check that the name will not be subject to expansion.
9746 prehash(union node *n)
9748 struct cmdentry entry;
9750 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9751 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9755 /* ============ Builtin commands
9757 * Builtin commands whose functions are closely tied to evaluation
9758 * are implemented here.
9762 * Handle break and continue commands. Break, continue, and return are
9763 * all handled by setting the evalskip flag. The evaluation routines
9764 * above all check this flag, and if it is set they start skipping
9765 * commands rather than executing them. The variable skipcount is
9766 * the number of loops to break/continue, or the number of function
9767 * levels to return. (The latter is always 1.) It should probably
9768 * be an error to break out of more loops than exist, but it isn't
9769 * in the standard shell so we don't make it one here.
9771 static int FAST_FUNC
9772 breakcmd(int argc UNUSED_PARAM, char **argv)
9774 int n = argv[1] ? number(argv[1]) : 1;
9777 ash_msg_and_raise_error(msg_illnum, argv[1]);
9781 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9789 * This implements the input routines used by the parser.
9793 INPUT_PUSH_FILE = 1,
9794 INPUT_NOFILE_OK = 2,
9797 static smallint checkkwd;
9798 /* values of checkkwd variable */
9799 #define CHKALIAS 0x1
9804 * Push a string back onto the input at this current parsefile level.
9805 * We handle aliases this way.
9807 #if !ENABLE_ASH_ALIAS
9808 #define pushstring(s, ap) pushstring(s)
9811 pushstring(char *s, struct alias *ap)
9818 if (g_parsefile->strpush) {
9819 sp = ckzalloc(sizeof(*sp));
9820 sp->prev = g_parsefile->strpush;
9822 sp = &(g_parsefile->basestrpush);
9824 g_parsefile->strpush = sp;
9825 sp->prev_string = g_parsefile->next_to_pgetc;
9826 sp->prev_left_in_line = g_parsefile->left_in_line;
9827 sp->unget = g_parsefile->unget;
9828 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9829 #if ENABLE_ASH_ALIAS
9832 ap->flag |= ALIASINUSE;
9836 g_parsefile->next_to_pgetc = s;
9837 g_parsefile->left_in_line = len;
9838 g_parsefile->unget = 0;
9845 struct strpush *sp = g_parsefile->strpush;
9848 #if ENABLE_ASH_ALIAS
9850 if (g_parsefile->next_to_pgetc[-1] == ' '
9851 || g_parsefile->next_to_pgetc[-1] == '\t'
9853 checkkwd |= CHKALIAS;
9855 if (sp->string != sp->ap->val) {
9858 sp->ap->flag &= ~ALIASINUSE;
9859 if (sp->ap->flag & ALIASDEAD) {
9860 unalias(sp->ap->name);
9864 g_parsefile->next_to_pgetc = sp->prev_string;
9865 g_parsefile->left_in_line = sp->prev_left_in_line;
9866 g_parsefile->unget = sp->unget;
9867 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
9868 g_parsefile->strpush = sp->prev;
9869 if (sp != &(g_parsefile->basestrpush))
9878 char *buf = g_parsefile->buf;
9880 g_parsefile->next_to_pgetc = buf;
9881 #if ENABLE_FEATURE_EDITING
9883 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9884 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9887 # if ENABLE_ASH_IDLE_TIMEOUT
9889 const char *tmout_var = lookupvar("TMOUT");
9891 timeout = atoi(tmout_var) * 1000;
9897 # if ENABLE_FEATURE_TAB_COMPLETION
9898 line_input_state->path_lookup = pathval();
9900 reinit_unicode_for_ash();
9901 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
9903 /* ^C pressed, "convert" to SIGINT */
9904 write(STDOUT_FILENO, "^C", 2);
9911 exitstatus = 128 + SIGINT;
9917 /* Ctrl+D pressed */
9920 # if ENABLE_ASH_IDLE_TIMEOUT
9921 else if (errno == EAGAIN && timeout > 0) {
9922 puts("\007timed out waiting for input: auto-logout");
9929 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9932 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9934 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9935 int flags = fcntl(0, F_GETFL);
9936 if (flags >= 0 && (flags & O_NONBLOCK)) {
9937 flags &= ~O_NONBLOCK;
9938 if (fcntl(0, F_SETFL, flags) >= 0) {
9939 out2str("sh: turning off NDELAY mode\n");
9950 * Refill the input buffer and return the next input character:
9952 * 1) If a string was pushed back on the input, pop it;
9953 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9954 * or we are reading from a string so we can't refill the buffer,
9956 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9957 * 4) Process input up to the next newline, deleting nul characters.
9959 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9960 #define pgetc_debug(...) ((void)0)
9961 static int pgetc(void);
9968 if (g_parsefile->strpush) {
9969 #if ENABLE_ASH_ALIAS
9970 if (g_parsefile->left_in_line == -1
9971 && g_parsefile->strpush->ap
9972 && g_parsefile->next_to_pgetc[-1] != ' '
9973 && g_parsefile->next_to_pgetc[-1] != '\t'
9975 pgetc_debug("preadbuffer PEOA");
9982 /* on both branches above g_parsefile->left_in_line < 0.
9983 * "pgetc" needs refilling.
9986 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9987 * pungetc() may increment it a few times.
9988 * Assuming it won't increment it to less than -90.
9990 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9991 pgetc_debug("preadbuffer PEOF1");
9992 /* even in failure keep left_in_line and next_to_pgetc
9993 * in lock step, for correct multi-layer pungetc.
9994 * left_in_line was decremented before preadbuffer(),
9995 * must inc next_to_pgetc: */
9996 g_parsefile->next_to_pgetc++;
10000 more = g_parsefile->left_in_buffer;
10002 flush_stdout_stderr();
10006 /* don't try reading again */
10007 g_parsefile->left_in_line = -99;
10008 pgetc_debug("preadbuffer PEOF2");
10009 g_parsefile->next_to_pgetc++;
10014 /* Find out where's the end of line.
10015 * Set g_parsefile->left_in_line
10016 * and g_parsefile->left_in_buffer acordingly.
10017 * NUL chars are deleted.
10019 q = g_parsefile->next_to_pgetc;
10027 memmove(q, q + 1, more);
10031 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10037 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10038 if (g_parsefile->left_in_line < 0)
10043 g_parsefile->left_in_buffer = more;
10048 out2str(g_parsefile->next_to_pgetc);
10052 pgetc_debug("preadbuffer at %d:%p'%s'",
10053 g_parsefile->left_in_line,
10054 g_parsefile->next_to_pgetc,
10055 g_parsefile->next_to_pgetc);
10056 return (unsigned char)*g_parsefile->next_to_pgetc++;
10062 g_parsefile->linno++;
10063 setprompt_if(doprompt, 2);
10068 g_parsefile->linno++;
10069 needprompt = doprompt;
10077 pgetc_debug("pgetc at %d:%p'%s'",
10078 g_parsefile->left_in_line,
10079 g_parsefile->next_to_pgetc,
10080 g_parsefile->next_to_pgetc);
10081 if (g_parsefile->unget)
10082 return g_parsefile->lastc[--g_parsefile->unget];
10084 if (--g_parsefile->left_in_line >= 0)
10085 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10089 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10090 g_parsefile->lastc[0] = c;
10095 #if ENABLE_ASH_ALIAS
10097 pgetc_without_PEOA(void)
10101 pgetc_debug("pgetc at %d:%p'%s'",
10102 g_parsefile->left_in_line,
10103 g_parsefile->next_to_pgetc,
10104 g_parsefile->next_to_pgetc);
10106 } while (c == PEOA);
10110 # define pgetc_without_PEOA() pgetc()
10114 * Read a line from the script.
10117 pfgets(char *line, int len)
10123 while (--nleft > 0) {
10124 c = pgetc_without_PEOA();
10139 * Undo a call to pgetc. Only two characters may be pushed back.
10140 * PEOF may be pushed back.
10145 g_parsefile->unget++;
10148 /* This one eats backslash+newline */
10154 while ((c = pgetc()) == '\\') {
10155 if (pgetc() != '\n') {
10167 * To handle the "." command, a stack of input files is used. Pushfile
10168 * adds a new entry to the stack and popfile restores the previous level.
10173 struct parsefile *pf;
10175 pf = ckzalloc(sizeof(*pf));
10176 pf->prev = g_parsefile;
10178 /*pf->strpush = NULL; - ckzalloc did it */
10179 /*pf->basestrpush.prev = NULL;*/
10187 struct parsefile *pf = g_parsefile;
10193 if (pf->pf_fd >= 0)
10196 while (pf->strpush)
10198 g_parsefile = pf->prev;
10204 * Return to top level.
10209 while (g_parsefile != &basepf)
10214 * Close the file(s) that the shell is reading commands from. Called
10215 * after a fork is done.
10221 if (g_parsefile->pf_fd > 0) {
10222 close(g_parsefile->pf_fd);
10223 g_parsefile->pf_fd = 0;
10228 * Like setinputfile, but takes an open file descriptor. Call this with
10232 setinputfd(int fd, int push)
10236 g_parsefile->buf = NULL;
10238 g_parsefile->pf_fd = fd;
10239 if (g_parsefile->buf == NULL)
10240 g_parsefile->buf = ckmalloc(IBUFSIZ);
10241 g_parsefile->left_in_buffer = 0;
10242 g_parsefile->left_in_line = 0;
10243 g_parsefile->linno = 1;
10247 * Set the input to take input from a file. If push is set, push the
10248 * old input onto the stack first.
10251 setinputfile(const char *fname, int flags)
10256 fd = open(fname, O_RDONLY);
10258 if (flags & INPUT_NOFILE_OK)
10261 ash_msg_and_raise_error("can't open '%s'", fname);
10266 close_on_exec_on(fd);
10267 setinputfd(fd, flags & INPUT_PUSH_FILE);
10274 * Like setinputfile, but takes input from a string.
10277 setinputstring(char *string)
10281 g_parsefile->next_to_pgetc = string;
10282 g_parsefile->left_in_line = strlen(string);
10283 g_parsefile->buf = NULL;
10284 g_parsefile->linno = 1;
10290 * Routines to check for mail.
10293 #if ENABLE_ASH_MAIL
10295 /* Hash of mtimes of mailboxes */
10296 static unsigned mailtime_hash;
10297 /* Set if MAIL or MAILPATH is changed. */
10298 static smallint mail_var_path_changed;
10301 * Print appropriate message(s) if mail has arrived.
10302 * If mail_var_path_changed is set,
10303 * then the value of MAIL has mail_var_path_changed,
10304 * so we just update the values.
10313 struct stackmark smark;
10316 setstackmark(&smark);
10317 mpath = mpathset() ? mpathval() : mailval();
10320 p = path_advance(&mpath, nullstr);
10325 for (q = p; *q; q++)
10331 q[-1] = '\0'; /* delete trailing '/' */
10332 if (stat(p, &statb) < 0) {
10335 /* Very simplistic "hash": just a sum of all mtimes */
10336 new_hash += (unsigned)statb.st_mtime;
10338 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10339 if (mailtime_hash != 0)
10340 out2str("you have mail\n");
10341 mailtime_hash = new_hash;
10343 mail_var_path_changed = 0;
10344 popstackmark(&smark);
10347 static void FAST_FUNC
10348 changemail(const char *val UNUSED_PARAM)
10350 mail_var_path_changed = 1;
10353 #endif /* ASH_MAIL */
10356 /* ============ ??? */
10359 * Set the shell parameters.
10362 setparam(char **argv)
10368 for (nparam = 0; argv[nparam]; nparam++)
10370 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10372 *ap++ = ckstrdup(*argv++);
10375 freeparam(&shellparam);
10376 shellparam.malloced = 1;
10377 shellparam.nparam = nparam;
10378 shellparam.p = newparam;
10379 #if ENABLE_ASH_GETOPTS
10380 shellparam.optind = 1;
10381 shellparam.optoff = -1;
10386 * Process shell options. The global variable argptr contains a pointer
10387 * to the argument list; we advance it past the options.
10389 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10390 * For a non-interactive shell, an error condition encountered
10391 * by a special built-in ... shall cause the shell to write a diagnostic message
10392 * to standard error and exit as shown in the following table:
10393 * Error Special Built-In
10395 * Utility syntax error (option or operand error) Shall exit
10397 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10398 * we see that bash does not do that (set "finishes" with error code 1 instead,
10399 * and shell continues), and people rely on this behavior!
10401 * set -o barfoo 2>/dev/null
10404 * Oh well. Let's mimic that.
10407 plus_minus_o(char *name, int val)
10412 for (i = 0; i < NOPTS; i++) {
10413 if (strcmp(name, optnames(i)) == 0) {
10418 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10421 for (i = 0; i < NOPTS; i++) {
10423 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10425 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10431 setoption(int flag, int val)
10435 for (i = 0; i < NOPTS; i++) {
10436 if (optletters(i) == flag) {
10441 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10445 options(int cmdline)
10453 while ((p = *argptr) != NULL) {
10455 if (c != '-' && c != '+')
10458 val = 0; /* val = 0 if c == '+' */
10461 if (p[0] == '\0' || LONE_DASH(p)) {
10463 /* "-" means turn off -x and -v */
10466 /* "--" means reset params */
10467 else if (*argptr == NULL)
10470 break; /* "-" or "--" terminates options */
10473 /* first char was + or - */
10474 while ((c = *p++) != '\0') {
10475 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10476 if (c == 'c' && cmdline) {
10477 minusc = p; /* command is after shell args */
10478 } else if (c == 'o') {
10479 if (plus_minus_o(*argptr, val)) {
10480 /* it already printed err message */
10481 return 1; /* error */
10485 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10487 /* bash does not accept +-login, we also won't */
10488 } else if (cmdline && val && (c == '-')) { /* long options */
10489 if (strcmp(p, "login") == 0)
10501 * The shift builtin command.
10503 static int FAST_FUNC
10504 shiftcmd(int argc UNUSED_PARAM, char **argv)
10511 n = number(argv[1]);
10512 if (n > shellparam.nparam)
10513 n = 0; /* bash compat, was = shellparam.nparam; */
10515 shellparam.nparam -= n;
10516 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10517 if (shellparam.malloced)
10520 ap2 = shellparam.p;
10521 while ((*ap2++ = *ap1++) != NULL)
10523 #if ENABLE_ASH_GETOPTS
10524 shellparam.optind = 1;
10525 shellparam.optoff = -1;
10532 * POSIX requires that 'set' (but not export or readonly) output the
10533 * variables in lexicographic order - by the locale's collating order (sigh).
10534 * Maybe we could keep them in an ordered balanced binary tree
10535 * instead of hashed lists.
10536 * For now just roll 'em through qsort for printing...
10539 showvars(const char *sep_prefix, int on, int off)
10542 char **ep, **epend;
10544 ep = listvars(on, off, &epend);
10545 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10547 sep = *sep_prefix ? " " : sep_prefix;
10549 for (; ep < epend; ep++) {
10553 p = strchrnul(*ep, '=');
10556 q = single_quote(++p);
10557 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10563 * The set command builtin.
10565 static int FAST_FUNC
10566 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10571 return showvars(nullstr, 0, VUNSET);
10574 retval = options(/*cmdline:*/ 0);
10575 if (retval == 0) { /* if no parse error... */
10577 if (*argptr != NULL) {
10585 #if ENABLE_ASH_RANDOM_SUPPORT
10586 static void FAST_FUNC
10587 change_random(const char *value)
10591 if (value == NULL) {
10592 /* "get", generate */
10593 t = next_random(&random_gen);
10594 /* set without recursion */
10595 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10596 vrandom.flags &= ~VNOFUNC;
10599 t = strtoul(value, NULL, 10);
10600 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10605 #if ENABLE_ASH_GETOPTS
10607 getopts(char *optstr, char *optvar, char **optfirst)
10614 int ind = shellparam.optind;
10615 int off = shellparam.optoff;
10619 shellparam.optind = -1;
10620 optnext = optfirst + ind - 1;
10622 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10625 p = optnext[-1] + off;
10626 if (p == NULL || *p == '\0') {
10627 /* Current word is done, advance */
10629 if (p == NULL || *p != '-' || *++p == '\0') {
10636 if (LONE_DASH(p)) /* check for "--" */
10641 for (q = optstr; *q != c;) {
10643 if (optstr[0] == ':') {
10645 /*sbuf[1] = '\0'; - already is */
10646 setvar0("OPTARG", sbuf);
10648 fprintf(stderr, "Illegal option -%c\n", c);
10649 unsetvar("OPTARG");
10659 if (*p == '\0' && (p = *optnext) == NULL) {
10660 if (optstr[0] == ':') {
10662 /*sbuf[1] = '\0'; - already is */
10663 setvar0("OPTARG", sbuf);
10666 fprintf(stderr, "No arg for -%c option\n", c);
10667 unsetvar("OPTARG");
10675 setvar0("OPTARG", p);
10678 setvar0("OPTARG", nullstr);
10680 ind = optnext - optfirst + 1;
10681 setvar("OPTIND", itoa(ind), VNOFUNC);
10683 /*sbuf[1] = '\0'; - already is */
10684 setvar0(optvar, sbuf);
10686 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10687 shellparam.optind = ind;
10693 * The getopts builtin. Shellparam.optnext points to the next argument
10694 * to be processed. Shellparam.optptr points to the next character to
10695 * be processed in the current argument. If shellparam.optnext is NULL,
10696 * then it's the first time getopts has been called.
10698 static int FAST_FUNC
10699 getoptscmd(int argc, char **argv)
10704 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10706 optbase = shellparam.p;
10707 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10708 shellparam.optind = 1;
10709 shellparam.optoff = -1;
10712 optbase = &argv[3];
10713 if ((unsigned)shellparam.optind > argc - 2) {
10714 shellparam.optind = 1;
10715 shellparam.optoff = -1;
10719 return getopts(argv[1], argv[2], optbase);
10721 #endif /* ASH_GETOPTS */
10724 /* ============ Shell parser */
10727 struct heredoc *next; /* next here document in list */
10728 union node *here; /* redirection node */
10729 char *eofmark; /* string indicating end of input */
10730 smallint striptabs; /* if set, strip leading tabs */
10733 static smallint tokpushback; /* last token pushed back */
10734 static smallint quoteflag; /* set if (part of) last token was quoted */
10735 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10736 static struct heredoc *heredoclist; /* list of here documents to read */
10737 static char *wordtext; /* text of last word returned by readtoken */
10738 static struct nodelist *backquotelist;
10739 static union node *redirnode;
10740 static struct heredoc *heredoc;
10742 static const char *
10743 tokname(char *buf, int tok)
10746 return tokname_array[tok];
10747 sprintf(buf, "\"%s\"", tokname_array[tok]);
10751 /* raise_error_unexpected_syntax:
10752 * Called when an unexpected token is read during the parse. The argument
10753 * is the token that is expected, or -1 if more than one type of token can
10754 * occur at this point.
10756 static void raise_error_unexpected_syntax(int) NORETURN;
10758 raise_error_unexpected_syntax(int token)
10764 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10766 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10767 raise_error_syntax(msg);
10771 #define EOFMARKLEN 79
10773 /* parsing is heavily cross-recursive, need these forward decls */
10774 static union node *andor(void);
10775 static union node *pipeline(void);
10776 static union node *parse_command(void);
10777 static void parseheredoc(void);
10778 static int peektoken(void);
10779 static int readtoken(void);
10781 static union node *
10784 union node *n1, *n2, *n3;
10789 switch (peektoken()) {
10797 if (!n1 && (nlflag & 1))
10803 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10804 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10810 if (tok == TBACKGND) {
10811 if (n2->type == NPIPE) {
10812 n2->npipe.pipe_backgnd = 1;
10814 if (n2->type != NREDIR) {
10815 n3 = stzalloc(sizeof(struct nredir));
10817 /*n3->nredir.redirect = NULL; - stzalloc did it */
10820 n2->type = NBACKGND;
10826 n3 = stzalloc(sizeof(struct nbinary));
10828 n3->nbinary.ch1 = n1;
10829 n3->nbinary.ch2 = n2;
10842 raise_error_unexpected_syntax(-1);
10849 static union node *
10852 union node *n1, *n2, *n3;
10860 } else if (t == TOR) {
10866 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10868 n3 = stzalloc(sizeof(struct nbinary));
10870 n3->nbinary.ch1 = n1;
10871 n3->nbinary.ch2 = n2;
10876 static union node *
10879 union node *n1, *n2, *pipenode;
10880 struct nodelist *lp, *prev;
10884 TRACE(("pipeline: entered\n"));
10885 if (readtoken() == TNOT) {
10887 checkkwd = CHKKWD | CHKALIAS;
10890 n1 = parse_command();
10891 if (readtoken() == TPIPE) {
10892 pipenode = stzalloc(sizeof(struct npipe));
10893 pipenode->type = NPIPE;
10894 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10895 lp = stzalloc(sizeof(struct nodelist));
10896 pipenode->npipe.cmdlist = lp;
10900 lp = stzalloc(sizeof(struct nodelist));
10901 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10902 lp->n = parse_command();
10904 } while (readtoken() == TPIPE);
10910 n2 = stzalloc(sizeof(struct nnot));
10918 static union node *
10923 n = stzalloc(sizeof(struct narg));
10925 /*n->narg.next = NULL; - stzalloc did it */
10926 n->narg.text = wordtext;
10927 n->narg.backquote = backquotelist;
10932 fixredir(union node *n, const char *text, int err)
10936 TRACE(("Fix redir %s %d\n", text, err));
10938 n->ndup.vname = NULL;
10940 fd = bb_strtou(text, NULL, 10);
10941 if (!errno && fd >= 0)
10942 n->ndup.dupfd = fd;
10943 else if (LONE_DASH(text))
10944 n->ndup.dupfd = -1;
10947 raise_error_syntax("bad fd number");
10948 n->ndup.vname = makename();
10953 * Returns true if the text contains nothing to expand (no dollar signs
10957 noexpand(const char *text)
10961 while ((c = *text++) != '\0') {
10962 if (c == CTLQUOTEMARK)
10966 else if (SIT(c, BASESYNTAX) == CCTL)
10975 union node *n = redirnode;
10977 if (readtoken() != TWORD)
10978 raise_error_unexpected_syntax(-1);
10979 if (n->type == NHERE) {
10980 struct heredoc *here = heredoc;
10984 if (quoteflag == 0)
10986 TRACE(("Here document %d\n", n->type));
10987 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10988 raise_error_syntax("illegal eof marker for << redirection");
10989 rmescapes(wordtext, 0);
10990 here->eofmark = wordtext;
10992 if (heredoclist == NULL)
10993 heredoclist = here;
10995 for (p = heredoclist; p->next; p = p->next)
10999 } else if (n->type == NTOFD || n->type == NFROMFD) {
11000 fixredir(n, wordtext, 0);
11002 n->nfile.fname = makename();
11006 static union node *
11009 union node *args, **app;
11010 union node *n = NULL;
11011 union node *vars, **vpp;
11012 union node **rpp, *redir;
11014 #if ENABLE_ASH_BASH_COMPAT
11015 smallint double_brackets_flag = 0;
11016 smallint function_flag = 0;
11026 savecheckkwd = CHKALIAS;
11029 checkkwd = savecheckkwd;
11032 #if ENABLE_ASH_BASH_COMPAT
11034 if (peektoken() != TWORD)
11035 raise_error_unexpected_syntax(TWORD);
11038 case TAND: /* "&&" */
11039 case TOR: /* "||" */
11040 if (!double_brackets_flag) {
11044 wordtext = (char *) (t == TAND ? "-a" : "-o");
11047 n = stzalloc(sizeof(struct narg));
11049 /*n->narg.next = NULL; - stzalloc did it */
11050 n->narg.text = wordtext;
11051 #if ENABLE_ASH_BASH_COMPAT
11052 if (strcmp("[[", wordtext) == 0)
11053 double_brackets_flag = 1;
11054 else if (strcmp("]]", wordtext) == 0)
11055 double_brackets_flag = 0;
11057 n->narg.backquote = backquotelist;
11058 if (savecheckkwd && isassignment(wordtext)) {
11060 vpp = &n->narg.next;
11063 app = &n->narg.next;
11066 #if ENABLE_ASH_BASH_COMPAT
11067 if (function_flag) {
11068 checkkwd = CHKNL | CHKKWD;
11069 switch (peektoken()) {
11081 if (strcmp("[[", wordtext) == 0)
11085 raise_error_unexpected_syntax(-1);
11091 *rpp = n = redirnode;
11092 rpp = &n->nfile.next;
11093 parsefname(); /* read name of redirection file */
11096 IF_ASH_BASH_COMPAT(do_func:)
11097 if (args && app == &args->narg.next
11100 struct builtincmd *bcmd;
11103 /* We have a function */
11104 if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
11105 raise_error_unexpected_syntax(TRP);
11106 name = n->narg.text;
11107 if (!goodname(name)
11108 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11110 raise_error_syntax("bad function name");
11113 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11114 n->narg.next = parse_command();
11117 IF_ASH_BASH_COMPAT(function_flag = 0;)
11128 n = stzalloc(sizeof(struct ncmd));
11130 n->ncmd.args = args;
11131 n->ncmd.assign = vars;
11132 n->ncmd.redirect = redir;
11136 static union node *
11137 parse_command(void)
11139 union node *n1, *n2;
11140 union node *ap, **app;
11141 union node *cp, **cpp;
11142 union node *redir, **rpp;
11149 switch (readtoken()) {
11151 raise_error_unexpected_syntax(-1);
11154 n1 = stzalloc(sizeof(struct nif));
11156 n1->nif.test = list(0);
11157 if (readtoken() != TTHEN)
11158 raise_error_unexpected_syntax(TTHEN);
11159 n1->nif.ifpart = list(0);
11161 while (readtoken() == TELIF) {
11162 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11163 n2 = n2->nif.elsepart;
11165 n2->nif.test = list(0);
11166 if (readtoken() != TTHEN)
11167 raise_error_unexpected_syntax(TTHEN);
11168 n2->nif.ifpart = list(0);
11170 if (lasttoken == TELSE)
11171 n2->nif.elsepart = list(0);
11173 n2->nif.elsepart = NULL;
11181 n1 = stzalloc(sizeof(struct nbinary));
11182 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11183 n1->nbinary.ch1 = list(0);
11186 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11187 got == TWORD ? wordtext : ""));
11188 raise_error_unexpected_syntax(TDO);
11190 n1->nbinary.ch2 = list(0);
11195 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11196 raise_error_syntax("bad for loop variable");
11197 n1 = stzalloc(sizeof(struct nfor));
11199 n1->nfor.var = wordtext;
11200 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11201 if (readtoken() == TIN) {
11203 while (readtoken() == TWORD) {
11204 n2 = stzalloc(sizeof(struct narg));
11206 /*n2->narg.next = NULL; - stzalloc did it */
11207 n2->narg.text = wordtext;
11208 n2->narg.backquote = backquotelist;
11210 app = &n2->narg.next;
11213 n1->nfor.args = ap;
11214 if (lasttoken != TNL && lasttoken != TSEMI)
11215 raise_error_unexpected_syntax(-1);
11217 n2 = stzalloc(sizeof(struct narg));
11219 /*n2->narg.next = NULL; - stzalloc did it */
11220 n2->narg.text = (char *)dolatstr;
11221 /*n2->narg.backquote = NULL;*/
11222 n1->nfor.args = n2;
11224 * Newline or semicolon here is optional (but note
11225 * that the original Bourne shell only allowed NL).
11227 if (lasttoken != TSEMI)
11230 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11231 if (readtoken() != TDO)
11232 raise_error_unexpected_syntax(TDO);
11233 n1->nfor.body = list(0);
11237 n1 = stzalloc(sizeof(struct ncase));
11239 if (readtoken() != TWORD)
11240 raise_error_unexpected_syntax(TWORD);
11241 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11243 /*n2->narg.next = NULL; - stzalloc did it */
11244 n2->narg.text = wordtext;
11245 n2->narg.backquote = backquotelist;
11246 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11247 if (readtoken() != TIN)
11248 raise_error_unexpected_syntax(TIN);
11249 cpp = &n1->ncase.cases;
11251 checkkwd = CHKNL | CHKKWD;
11253 while (t != TESAC) {
11254 if (lasttoken == TLP)
11256 *cpp = cp = stzalloc(sizeof(struct nclist));
11258 app = &cp->nclist.pattern;
11260 *app = ap = stzalloc(sizeof(struct narg));
11262 /*ap->narg.next = NULL; - stzalloc did it */
11263 ap->narg.text = wordtext;
11264 ap->narg.backquote = backquotelist;
11265 if (readtoken() != TPIPE)
11267 app = &ap->narg.next;
11270 //ap->narg.next = NULL;
11271 if (lasttoken != TRP)
11272 raise_error_unexpected_syntax(TRP);
11273 cp->nclist.body = list(2);
11275 cpp = &cp->nclist.next;
11277 checkkwd = CHKNL | CHKKWD;
11281 raise_error_unexpected_syntax(TENDCASE);
11288 n1 = stzalloc(sizeof(struct nredir));
11289 n1->type = NSUBSHELL;
11290 n1->nredir.n = list(0);
11291 /*n1->nredir.redirect = NULL; - stzalloc did it */
11298 IF_ASH_BASH_COMPAT(case TFUNCTION:)
11302 return simplecmd();
11305 if (readtoken() != t)
11306 raise_error_unexpected_syntax(t);
11309 /* Now check for redirection which may follow command */
11310 checkkwd = CHKKWD | CHKALIAS;
11312 while (readtoken() == TREDIR) {
11313 *rpp = n2 = redirnode;
11314 rpp = &n2->nfile.next;
11320 if (n1->type != NSUBSHELL) {
11321 n2 = stzalloc(sizeof(struct nredir));
11326 n1->nredir.redirect = redir;
11331 #if ENABLE_ASH_BASH_COMPAT
11333 decode_dollar_squote(void)
11335 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11341 p = strchr(C_escapes, c);
11346 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11350 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11352 } else if (c == 'x') { /* \xHH */
11356 } while (isxdigit(c) && --cnt);
11358 if (cnt == 3) { /* \x but next char is "bad" */
11362 } else { /* simple seq like \\ or \t */
11367 c = bb_process_escape_sequence((void*)&p);
11368 } else { /* unrecognized "\z": print both chars unless ' or " */
11369 if (c != '\'' && c != '"') {
11371 c |= 0x100; /* "please encode \, then me" */
11379 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11380 * is not NULL, read a here document. In the latter case, eofmark is the
11381 * word which marks the end of the document and striptabs is true if
11382 * leading tabs should be stripped from the document. The argument c
11383 * is the first character of the input token or document.
11385 * Because C does not have internal subroutines, I have simulated them
11386 * using goto's to implement the subroutine linkage. The following macros
11387 * will run code that appears at the end of readtoken1.
11389 #define CHECKEND() {goto checkend; checkend_return:;}
11390 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11391 #define PARSESUB() {goto parsesub; parsesub_return:;}
11392 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11393 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11394 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11396 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11398 /* NB: syntax parameter fits into smallint */
11399 /* c parameter is an unsigned char or PEOF or PEOA */
11402 char line[EOFMARKLEN + 1];
11403 struct nodelist *bqlist;
11407 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11408 #if ENABLE_ASH_EXPAND_PRMT
11409 smallint pssyntax; /* we are expanding a prompt string */
11411 int varnest; /* levels of variables expansion */
11412 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11413 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11414 int dqvarnest; /* levels of variables expansion within double quotes */
11416 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11418 startlinno = g_parsefile->linno;
11421 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11422 #if ENABLE_ASH_EXPAND_PRMT
11423 pssyntax = (syntax == PSSYNTAX);
11427 dblquote = (syntax == DQSYNTAX);
11429 IF_FEATURE_SH_MATH(arinest = 0;)
11430 IF_FEATURE_SH_MATH(parenlevel = 0;)
11433 STARTSTACKSTR(out);
11435 /* For each line, until end of word */
11436 CHECKEND(); /* set c to PEOF if at end of here document */
11437 for (;;) { /* until end of line or end of word */
11438 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11439 switch (SIT(c, syntax)) {
11440 case CNL: /* '\n' */
11441 if (syntax == BASESYNTAX)
11442 goto endword; /* exit outer loop */
11446 goto loop; /* continue outer loop */
11451 #if ENABLE_ASH_BASH_COMPAT
11452 if (c == '\\' && bash_dollar_squote) {
11453 c = decode_dollar_squote();
11455 /* skip $'\000', $'\x00' (like bash) */
11459 /* Unknown escape. Encode as '\z' */
11460 c = (unsigned char)c;
11461 if (eofmark == NULL || dblquote)
11462 USTPUTC(CTLESC, out);
11463 USTPUTC('\\', out);
11467 if (eofmark == NULL || dblquote)
11468 USTPUTC(CTLESC, out);
11471 case CBACK: /* backslash */
11472 c = pgetc_without_PEOA();
11474 USTPUTC(CTLESC, out);
11475 USTPUTC('\\', out);
11477 } else if (c == '\n') {
11480 #if ENABLE_ASH_EXPAND_PRMT
11481 if (c == '$' && pssyntax) {
11482 USTPUTC(CTLESC, out);
11483 USTPUTC('\\', out);
11486 /* Backslash is retained if we are in "str" and next char isn't special */
11491 && (c != '"' || eofmark != NULL)
11493 USTPUTC('\\', out);
11495 USTPUTC(CTLESC, out);
11503 if (eofmark == NULL) {
11504 USTPUTC(CTLQUOTEMARK, out);
11512 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11513 if (eofmark != NULL && varnest == 0) {
11516 if (dqvarnest == 0) {
11517 syntax = BASESYNTAX;
11524 case CVAR: /* '$' */
11525 PARSESUB(); /* parse substitution */
11527 case CENDVAR: /* '}' */
11530 if (dqvarnest > 0) {
11537 #if ENABLE_FEATURE_SH_MATH
11538 case CLP: /* '(' in arithmetic */
11542 case CRP: /* ')' in arithmetic */
11543 if (parenlevel > 0) {
11546 if (pgetc_eatbnl() == ')') {
11548 if (--arinest == 0) {
11549 syntax = prevsyntax;
11553 * unbalanced parens
11554 * (don't 2nd guess - no error)
11562 case CBQUOTE: /* '`' */
11566 goto endword; /* exit outer loop */
11570 if (varnest == 0) {
11571 #if ENABLE_ASH_BASH_COMPAT
11573 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11574 if (pgetc() == '>')
11575 c = 0x100 + '>'; /* flag &> */
11579 goto endword; /* exit outer loop */
11581 IF_ASH_ALIAS(if (c != PEOA))
11588 #if ENABLE_FEATURE_SH_MATH
11589 if (syntax == ARISYNTAX)
11590 raise_error_syntax("missing '))'");
11592 if (syntax != BASESYNTAX && eofmark == NULL)
11593 raise_error_syntax("unterminated quoted string");
11594 if (varnest != 0) {
11595 startlinno = g_parsefile->linno;
11597 raise_error_syntax("missing '}'");
11599 USTPUTC('\0', out);
11600 len = out - (char *)stackblock();
11601 out = stackblock();
11602 if (eofmark == NULL) {
11603 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11606 if (isdigit_str9(out)) {
11607 PARSEREDIR(); /* passed as params: out, c */
11608 lasttoken = TREDIR;
11611 /* else: non-number X seen, interpret it
11612 * as "NNNX>file" = "NNNX >file" */
11616 quoteflag = quotef;
11617 backquotelist = bqlist;
11618 grabstackblock(len);
11622 /* end of readtoken routine */
11625 * Check to see whether we are at the end of the here document. When this
11626 * is called, c is set to the first character of the next input line. If
11627 * we are at the end of the here document, this routine sets the c to PEOF.
11631 #if ENABLE_ASH_ALIAS
11633 c = pgetc_without_PEOA();
11636 while (c == '\t') {
11637 c = pgetc_without_PEOA();
11640 if (c == *eofmark) {
11641 if (pfgets(line, sizeof(line)) != NULL) {
11646 for (q = eofmark + 1;; p++, q++) {
11650 if (!*q || cc != *q)
11657 pushstring(line, NULL);
11662 goto checkend_return;
11666 * Parse a redirection operator. The variable "out" points to a string
11667 * specifying the fd to be redirected. The variable "c" contains the
11668 * first character of the redirection operator.
11671 /* out is already checked to be a valid number or "" */
11672 int fd = (*out == '\0' ? -1 : atoi(out));
11675 np = stzalloc(sizeof(struct nfile));
11680 np->type = NAPPEND;
11682 np->type = NCLOBBER;
11685 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11691 #if ENABLE_ASH_BASH_COMPAT
11692 else if (c == 0x100 + '>') { /* this flags &> redirection */
11694 pgetc(); /* this is '>', no need to check */
11698 else { /* c == '<' */
11699 /*np->nfile.fd = 0; - stzalloc did it */
11703 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11704 np = stzalloc(sizeof(struct nhere));
11705 /*np->nfile.fd = 0; - stzalloc did it */
11708 heredoc = stzalloc(sizeof(struct heredoc));
11709 heredoc->here = np;
11712 heredoc->striptabs = 1;
11714 /*heredoc->striptabs = 0; - stzalloc did it */
11720 np->type = NFROMFD;
11724 np->type = NFROMTO;
11736 goto parseredir_return;
11740 * Parse a substitution. At this point, we have read the dollar sign
11741 * and nothing else.
11744 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11745 * (assuming ascii char codes, as the original implementation did) */
11746 #define is_special(c) \
11747 (((unsigned)(c) - 33 < 32) \
11748 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11750 unsigned char subtype;
11753 c = pgetc_eatbnl();
11754 if (c > 255 /* PEOA or PEOF */
11755 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11757 #if ENABLE_ASH_BASH_COMPAT
11758 if (syntax != DQSYNTAX && c == '\'')
11759 bash_dollar_squote = 1;
11764 } else if (c == '(') {
11765 /* $(command) or $((arith)) */
11766 if (pgetc_eatbnl() == '(') {
11767 #if ENABLE_FEATURE_SH_MATH
11770 raise_error_syntax("you disabled math support for $((arith)) syntax");
11777 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11778 USTPUTC(CTLVAR, out);
11779 typeloc = out - (char *)stackblock();
11781 subtype = VSNORMAL;
11783 c = pgetc_eatbnl();
11788 /* $[{[#]]NAME[}] */
11791 c = pgetc_eatbnl();
11792 } while (is_in_name(c));
11793 } else if (isdigit(c)) {
11794 /* $[{[#]]NUM[}] */
11797 c = pgetc_eatbnl();
11798 } while (isdigit(c));
11799 } else if (is_special(c)) {
11800 /* $[{[#]]<specialchar>[}] */
11803 c = pgetc_eatbnl();
11804 if (!subtype && cc == '#') {
11805 subtype = VSLENGTH;
11806 if (c == '_' || isalnum(c))
11809 c = pgetc_eatbnl();
11810 if (cc == '}' || c != '}') {
11821 if (c != '}' && subtype == VSLENGTH) {
11822 /* ${#VAR didn't end with } */
11826 if (subtype == 0) {
11827 static const char types[] ALIGN1 = "}-+?=";
11828 /* ${VAR...} but not $VAR or ${#VAR} */
11829 /* c == first char after VAR */
11832 c = pgetc_eatbnl();
11833 #if ENABLE_ASH_BASH_COMPAT
11834 /* This check is only needed to not misinterpret
11835 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11838 if (!strchr(types, c)) {
11839 subtype = VSSUBSTR;
11841 break; /* "goto badsub" is bigger (!) */
11847 const char *p = strchr(types, c);
11850 subtype |= p - types + VSNORMAL;
11856 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11857 c = pgetc_eatbnl();
11863 #if ENABLE_ASH_BASH_COMPAT
11865 /* ${v/[/]pattern/repl} */
11866 //TODO: encode pattern and repl separately.
11867 // Currently ${v/$var_with_slash/repl} is horribly broken
11868 subtype = VSREPLACE;
11869 c = pgetc_eatbnl();
11872 subtype++; /* VSREPLACEALL */
11880 ((unsigned char *)stackblock())[typeloc] = subtype;
11881 if (subtype != VSNORMAL) {
11888 goto parsesub_return;
11892 * Called to parse command substitutions. Newstyle is set if the command
11893 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11894 * list of commands (passed by reference), and savelen is the number of
11895 * characters on the top of the stack which must be preserved.
11898 struct nodelist **nlpp;
11902 smallint saveprompt = 0;
11905 savelen = out - (char *)stackblock();
11908 * FIXME: this can allocate very large block on stack and SEGV.
11910 * echo "..<100kbytes>..`true` $(true) `true` ..."
11911 * allocates 100kb for every command subst. With about
11912 * a hundred command substitutions stack overflows.
11913 * With larger prepended string, SEGV happens sooner.
11915 str = alloca(savelen);
11916 memcpy(str, stackblock(), savelen);
11920 /* We must read until the closing backquote, giving special
11921 * treatment to some slashes, and then push the string and
11922 * reread it as input, interpreting it normally.
11928 STARTSTACKSTR(pout);
11932 setprompt_if(needprompt, 2);
11943 * If eating a newline, avoid putting
11944 * the newline into the new character
11945 * stream (via the STPUTC after the
11950 if (pc != '\\' && pc != '`' && pc != '$'
11951 && (!dblquote || pc != '"')
11953 STPUTC('\\', pout);
11955 if (pc <= 255 /* not PEOA or PEOF */) {
11961 IF_ASH_ALIAS(case PEOA:)
11962 startlinno = g_parsefile->linno;
11963 raise_error_syntax("EOF in backquote substitution");
11975 STPUTC('\0', pout);
11976 psavelen = pout - (char *)stackblock();
11977 if (psavelen > 0) {
11978 pstr = grabstackstr(pout);
11979 setinputstring(pstr);
11984 nlpp = &(*nlpp)->next;
11985 *nlpp = stzalloc(sizeof(**nlpp));
11986 /* (*nlpp)->next = NULL; - stzalloc did it */
11989 saveprompt = doprompt;
11996 doprompt = saveprompt;
11997 else if (readtoken() != TRP)
11998 raise_error_unexpected_syntax(TRP);
12003 * Start reading from old file again, ignoring any pushed back
12004 * tokens left from the backquote parsing
12009 while (stackblocksize() <= savelen)
12011 STARTSTACKSTR(out);
12013 memcpy(out, str, savelen);
12014 STADJUST(savelen, out);
12016 USTPUTC(CTLBACKQ, out);
12018 goto parsebackq_oldreturn;
12019 goto parsebackq_newreturn;
12022 #if ENABLE_FEATURE_SH_MATH
12024 * Parse an arithmetic expansion (indicate start of one and set state)
12027 if (++arinest == 1) {
12028 prevsyntax = syntax;
12029 syntax = ARISYNTAX;
12031 USTPUTC(CTLARI, out);
12032 goto parsearith_return;
12035 } /* end of readtoken */
12038 * Read the next input token.
12039 * If the token is a word, we set backquotelist to the list of cmds in
12040 * backquotes. We set quoteflag to true if any part of the word was
12042 * If the token is TREDIR, then we set redirnode to a structure containing
12044 * In all cases, the variable startlinno is set to the number of the line
12045 * on which the token starts.
12047 * [Change comment: here documents and internal procedures]
12048 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12049 * word parsing code into a separate routine. In this case, readtoken
12050 * doesn't need to have any internal procedures, but parseword does.
12051 * We could also make parseoperator in essence the main routine, and
12052 * have parseword (readtoken1?) handle both words and redirection.]
12054 #define NEW_xxreadtoken
12055 #ifdef NEW_xxreadtoken
12056 /* singles must be first! */
12057 static const char xxreadtoken_chars[7] ALIGN1 = {
12058 '\n', '(', ')', /* singles */
12059 '&', '|', ';', /* doubles */
12063 #define xxreadtoken_singles 3
12064 #define xxreadtoken_doubles 3
12066 static const char xxreadtoken_tokens[] ALIGN1 = {
12067 TNL, TLP, TRP, /* only single occurrence allowed */
12068 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12069 TEOF, /* corresponds to trailing nul */
12070 TAND, TOR, TENDCASE /* if double occurrence */
12082 setprompt_if(needprompt, 2);
12083 startlinno = g_parsefile->linno;
12084 for (;;) { /* until token or start of word found */
12086 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12090 while ((c = pgetc()) != '\n' && c != PEOF)
12093 } else if (c == '\\') {
12094 if (pgetc() != '\n') {
12096 break; /* return readtoken1(...) */
12102 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12108 p = strchr(xxreadtoken_chars, c);
12110 break; /* return readtoken1(...) */
12112 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12114 if (cc == c) { /* double occurrence? */
12115 p += xxreadtoken_doubles + 1;
12118 #if ENABLE_ASH_BASH_COMPAT
12119 if (c == '&' && cc == '>') /* &> */
12120 break; /* return readtoken1(...) */
12125 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12130 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12132 #else /* old xxreadtoken */
12133 #define RETURN(token) return lasttoken = token
12143 setprompt_if(needprompt, 2);
12144 startlinno = g_parsefile->linno;
12145 for (;;) { /* until token or start of word found */
12148 case ' ': case '\t':
12149 IF_ASH_ALIAS(case PEOA:)
12152 while ((c = pgetc()) != '\n' && c != PEOF)
12157 if (pgetc() == '\n') {
12169 if (pgetc() == '&')
12174 if (pgetc() == '|')
12179 if (pgetc() == ';')
12192 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12195 #endif /* old xxreadtoken */
12201 int kwd = checkkwd;
12203 smallint alreadyseen = tokpushback;
12206 #if ENABLE_ASH_ALIAS
12222 if (t != TWORD || quoteflag) {
12227 * check for keywords
12229 if (kwd & CHKKWD) {
12230 const char *const *pp;
12232 pp = findkwd(wordtext);
12234 lasttoken = t = pp - tokname_array;
12235 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12240 if (checkkwd & CHKALIAS) {
12241 #if ENABLE_ASH_ALIAS
12243 ap = lookupalias(wordtext, 1);
12246 pushstring(ap->val, ap);
12256 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12258 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12274 * Read and parse a command. Returns NODE_EOF on end of file.
12275 * (NULL is a valid parse tree indicating a blank line.)
12277 static union node *
12278 parsecmd(int interact)
12283 doprompt = interact;
12284 setprompt_if(doprompt, doprompt);
12290 * Input any here documents.
12295 struct heredoc *here;
12298 here = heredoclist;
12299 heredoclist = NULL;
12302 setprompt_if(needprompt, 2);
12303 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12304 here->eofmark, here->striptabs);
12305 n = stzalloc(sizeof(struct narg));
12306 n->narg.type = NARG;
12307 /*n->narg.next = NULL; - stzalloc did it */
12308 n->narg.text = wordtext;
12309 n->narg.backquote = backquotelist;
12310 here->here->nhere.doc = n;
12317 * called by editline -- any expansions to the prompt should be added here.
12319 #if ENABLE_ASH_EXPAND_PRMT
12320 static const char *
12321 expandstr(const char *ps)
12326 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12327 * and token processing _can_ alter it (delete NULs etc). */
12328 setinputstring((char *)ps);
12330 saveprompt = doprompt;
12332 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12333 doprompt = saveprompt;
12337 n.narg.type = NARG;
12338 n.narg.next = NULL;
12339 n.narg.text = wordtext;
12340 n.narg.backquote = backquotelist;
12342 expandarg(&n, NULL, EXP_QUOTED);
12343 return stackblock();
12348 * Execute a command or commands contained in a string.
12351 evalstring(char *s, int flags)
12353 struct jmploc *volatile savehandler;
12354 struct jmploc jmploc;
12358 struct stackmark smark;
12363 setstackmark(&smark);
12366 /* On exception inside execution loop, we must popfile().
12367 * Try interactively:
12369 * command eval "a=b" # throws "is read only" error
12370 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12371 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12373 savehandler = exception_handler;
12374 ex = setjmp(jmploc.loc);
12377 exception_handler = &jmploc;
12379 while ((n = parsecmd(0)) != NODE_EOF) {
12382 i = evaltree(n, flags);
12385 popstackmark(&smark);
12390 popstackmark(&smark);
12394 exception_handler = savehandler;
12396 longjmp(exception_handler->loc, ex);
12402 * The eval command.
12404 static int FAST_FUNC
12405 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12414 STARTSTACKSTR(concat);
12416 concat = stack_putstr(p, concat);
12420 STPUTC(' ', concat);
12422 STPUTC('\0', concat);
12423 p = grabstackstr(concat);
12425 return evalstring(p, flags & EV_TESTED);
12431 * Read and execute commands.
12432 * "Top" is nonzero for the top level command loop;
12433 * it turns on prompting if the shell is interactive.
12439 struct stackmark smark;
12444 TRACE(("cmdloop(%d) called\n", top));
12448 setstackmark(&smark);
12451 showjobs(SHOW_CHANGED|SHOW_STDERR);
12454 if (iflag && top) {
12458 n = parsecmd(inter);
12460 if (DEBUG > 2 && debug && (n != NODE_EOF))
12463 if (n == NODE_EOF) {
12464 if (!top || numeof >= 50)
12466 if (!stoppedjobs()) {
12469 out2str("\nUse \"exit\" to leave shell.\n");
12472 } else if (nflag == 0) {
12475 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12478 i = evaltree(n, 0);
12482 popstackmark(&smark);
12486 evalskip &= ~SKIPFUNC;
12494 * Take commands from a file. To be compatible we should do a path
12495 * search for the file, which is necessary to find sub-commands.
12498 find_dot_file(char *name)
12501 const char *path = pathval();
12504 /* don't try this for absolute or relative paths */
12505 if (strchr(name, '/'))
12508 /* IIRC standards do not say whether . is to be searched.
12509 * And it is even smaller this way, making it unconditional for now:
12511 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12516 while ((fullname = path_advance(&path, name)) != NULL) {
12518 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12520 * Don't bother freeing here, since it will
12521 * be freed by the caller.
12525 if (fullname != name)
12526 stunalloc(fullname);
12529 /* not found in the PATH */
12530 ash_msg_and_raise_error("%s: not found", name);
12534 static int FAST_FUNC
12535 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12537 /* "false; . empty_file; echo $?" should print 0, not 1: */
12541 struct strlist *sp;
12542 volatile struct shparam saveparam;
12544 for (sp = cmdenviron; sp; sp = sp->next)
12545 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12547 nextopt(nullstr); /* handle possible "--" */
12551 /* bash says: "bash: .: filename argument required" */
12552 return 2; /* bash compat */
12555 /* This aborts if file isn't found, which is POSIXly correct.
12556 * bash returns exitcode 1 instead.
12558 fullname = find_dot_file(argv[0]);
12560 if (argv[0]) { /* . FILE ARGS, ARGS exist */
12562 saveparam = shellparam;
12563 shellparam.malloced = 0;
12567 shellparam.nparam = argc;
12568 shellparam.p = argv;
12571 /* This aborts if file can't be opened, which is POSIXly correct.
12572 * bash returns exitcode 1 instead.
12574 setinputfile(fullname, INPUT_PUSH_FILE);
12575 commandname = fullname;
12576 status = cmdloop(0);
12580 freeparam(&shellparam);
12581 shellparam = saveparam;
12587 static int FAST_FUNC
12588 exitcmd(int argc UNUSED_PARAM, char **argv)
12593 exitstatus = number(argv[1]);
12594 raise_exception(EXEXIT);
12599 * Read a file containing shell functions.
12602 readcmdfile(char *name)
12604 setinputfile(name, INPUT_PUSH_FILE);
12610 /* ============ find_command inplementation */
12613 * Resolve a command name. If you change this routine, you may have to
12614 * change the shellexec routine as well.
12617 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12619 struct tblentry *cmdp;
12626 struct builtincmd *bcmd;
12628 /* If name contains a slash, don't use PATH or hash table */
12629 if (strchr(name, '/') != NULL) {
12630 entry->u.index = -1;
12631 if (act & DO_ABS) {
12632 while (stat(name, &statb) < 0) {
12634 if (errno == EINTR)
12637 entry->cmdtype = CMDUNKNOWN;
12641 entry->cmdtype = CMDNORMAL;
12645 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12647 updatetbl = (path == pathval());
12650 if (strstr(path, "%builtin") != NULL)
12651 act |= DO_ALTBLTIN;
12654 /* If name is in the table, check answer will be ok */
12655 cmdp = cmdlookup(name, 0);
12656 if (cmdp != NULL) {
12659 switch (cmdp->cmdtype) {
12677 } else if (cmdp->rehash == 0)
12678 /* if not invalidated by cd, we're done */
12682 /* If %builtin not in path, check for builtin next */
12683 bcmd = find_builtin(name);
12685 if (IS_BUILTIN_REGULAR(bcmd))
12686 goto builtin_success;
12687 if (act & DO_ALTPATH) {
12688 if (!(act & DO_ALTBLTIN))
12689 goto builtin_success;
12690 } else if (builtinloc <= 0) {
12691 goto builtin_success;
12695 #if ENABLE_FEATURE_SH_STANDALONE
12697 int applet_no = find_applet_by_name(name);
12698 if (applet_no >= 0) {
12699 entry->cmdtype = CMDNORMAL;
12700 entry->u.index = -2 - applet_no;
12706 /* We have to search path. */
12707 prev = -1; /* where to start */
12708 if (cmdp && cmdp->rehash) { /* doing a rehash */
12709 if (cmdp->cmdtype == CMDBUILTIN)
12712 prev = cmdp->param.index;
12718 while ((fullname = path_advance(&path, name)) != NULL) {
12719 stunalloc(fullname);
12720 /* NB: code below will still use fullname
12721 * despite it being "unallocated" */
12724 if (prefix(pathopt, "builtin")) {
12726 goto builtin_success;
12729 if ((act & DO_NOFUNC)
12730 || !prefix(pathopt, "func")
12731 ) { /* ignore unimplemented options */
12735 /* if rehash, don't redo absolute path names */
12736 if (fullname[0] == '/' && idx <= prev) {
12739 TRACE(("searchexec \"%s\": no change\n", name));
12742 while (stat(fullname, &statb) < 0) {
12744 if (errno == EINTR)
12747 if (errno != ENOENT && errno != ENOTDIR)
12751 e = EACCES; /* if we fail, this will be the error */
12752 if (!S_ISREG(statb.st_mode))
12754 if (pathopt) { /* this is a %func directory */
12755 stalloc(strlen(fullname) + 1);
12756 /* NB: stalloc will return space pointed by fullname
12757 * (because we don't have any intervening allocations
12758 * between stunalloc above and this stalloc) */
12759 readcmdfile(fullname);
12760 cmdp = cmdlookup(name, 0);
12761 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12762 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12763 stunalloc(fullname);
12766 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12768 entry->cmdtype = CMDNORMAL;
12769 entry->u.index = idx;
12773 cmdp = cmdlookup(name, 1);
12774 cmdp->cmdtype = CMDNORMAL;
12775 cmdp->param.index = idx;
12780 /* We failed. If there was an entry for this command, delete it */
12781 if (cmdp && updatetbl)
12782 delete_cmd_entry();
12784 ash_msg("%s: %s", name, errmsg(e, "not found"));
12785 entry->cmdtype = CMDUNKNOWN;
12790 entry->cmdtype = CMDBUILTIN;
12791 entry->u.cmd = bcmd;
12795 cmdp = cmdlookup(name, 1);
12796 cmdp->cmdtype = CMDBUILTIN;
12797 cmdp->param.cmd = bcmd;
12801 entry->cmdtype = cmdp->cmdtype;
12802 entry->u = cmdp->param;
12807 * The trap builtin.
12809 static int FAST_FUNC
12810 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12814 int signo, exitcode;
12819 for (signo = 0; signo < NSIG; signo++) {
12820 char *tr = trap_ptr[signo];
12822 /* note: bash adds "SIG", but only if invoked
12823 * as "bash". If called as "sh", or if set -o posix,
12824 * then it prints short signal names.
12825 * We are printing short names: */
12826 out1fmt("trap -- %s %s\n",
12828 get_signame(signo));
12829 /* trap_ptr != trap only if we are in special-cased `trap` code.
12830 * In this case, we will exit very soon, no need to free(). */
12831 /* if (trap_ptr != trap && tp[0]) */
12836 if (trap_ptr != trap) {
12849 signo = get_signum(*ap);
12851 /* Mimic bash message exactly */
12852 ash_msg("%s: invalid signal specification", *ap);
12858 if (LONE_DASH(action))
12861 if (action[0]) /* not NULL and not "" and not "-" */
12862 may_have_traps = 1;
12863 action = ckstrdup(action);
12867 trap[signo] = action;
12878 /* ============ Builtins */
12880 #if ENABLE_ASH_HELP
12881 static int FAST_FUNC
12882 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12888 "Built-in commands:\n"
12889 "------------------\n");
12890 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12891 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12892 builtintab[i].name + 1);
12898 # if ENABLE_FEATURE_SH_STANDALONE
12900 const char *a = applet_names;
12902 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12907 while (*a++ != '\0')
12912 newline_and_flush(stdout);
12913 return EXIT_SUCCESS;
12918 static int FAST_FUNC
12919 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12921 show_history(line_input_state);
12922 return EXIT_SUCCESS;
12927 * The export and readonly commands.
12929 static int FAST_FUNC
12930 exportcmd(int argc UNUSED_PARAM, char **argv)
12940 /* "readonly" in bash accepts, but ignores -n.
12941 * We do the same: it saves a conditional in nextopt's param.
12944 while ((opt = nextopt("np")) != '\0') {
12946 flag_off = VEXPORT;
12949 if (argv[0][0] == 'r') {
12951 flag_off = 0; /* readonly ignores -n */
12953 flag_off = ~flag_off;
12955 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12961 p = strchr(name, '=');
12965 vp = *findvar(hashvar(name), name);
12967 vp->flags = ((vp->flags | flag) & flag_off);
12971 setvar(name, p, (flag & flag_off));
12972 } while ((name = *++aptr) != NULL);
12977 /* No arguments. Show the list of exported or readonly vars.
12980 showvars(argv[0], flag, 0);
12985 * Delete a function if it exists.
12988 unsetfunc(const char *name)
12990 struct tblentry *cmdp;
12992 cmdp = cmdlookup(name, 0);
12993 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12994 delete_cmd_entry();
12998 * The unset builtin command. We unset the function before we unset the
12999 * variable to allow a function to be unset when there is a readonly variable
13000 * with the same name.
13002 static int FAST_FUNC
13003 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13010 while ((i = nextopt("vf")) != 0) {
13014 for (ap = argptr; *ap; ap++) {
13027 static const unsigned char timescmd_str[] ALIGN1 = {
13028 ' ', offsetof(struct tms, tms_utime),
13029 '\n', offsetof(struct tms, tms_stime),
13030 ' ', offsetof(struct tms, tms_cutime),
13031 '\n', offsetof(struct tms, tms_cstime),
13034 static int FAST_FUNC
13035 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13037 unsigned long clk_tck, s, t;
13038 const unsigned char *p;
13041 clk_tck = bb_clk_tck();
13046 t = *(clock_t *)(((char *) &buf) + p[1]);
13049 out1fmt("%lum%lu.%03lus%c",
13051 (t * 1000) / clk_tck,
13059 #if ENABLE_FEATURE_SH_MATH
13061 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13062 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13064 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13066 static int FAST_FUNC
13067 letcmd(int argc UNUSED_PARAM, char **argv)
13073 ash_msg_and_raise_error("expression expected");
13075 i = ash_arith(*argv);
13083 * The read builtin. Options:
13084 * -r Do not interpret '\' specially
13085 * -s Turn off echo (tty only)
13086 * -n NCHARS Read NCHARS max
13087 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13088 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13089 * -u FD Read from given FD instead of fd 0
13090 * This uses unbuffered input, which may be avoidable in some cases.
13091 * TODO: bash also has:
13092 * -a ARRAY Read into array[0],[1],etc
13093 * -d DELIM End on DELIM char, not newline
13094 * -e Use line editing (tty only)
13096 static int FAST_FUNC
13097 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13099 char *opt_n = NULL;
13100 char *opt_p = NULL;
13101 char *opt_t = NULL;
13102 char *opt_u = NULL;
13103 int read_flags = 0;
13107 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13116 read_flags |= BUILTIN_READ_SILENT;
13122 read_flags |= BUILTIN_READ_RAW;
13132 /* "read -s" needs to save/restore termios, can't allow ^C
13133 * to jump out of it.
13136 r = shell_builtin_read(setvar0,
13138 bltinlookup("IFS"), /* can be NULL */
13147 if ((uintptr_t)r > 1)
13148 ash_msg_and_raise_error(r);
13150 return (uintptr_t)r;
13153 static int FAST_FUNC
13154 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13156 static const char permuser[3] ALIGN1 = "ogu";
13159 int symbolic_mode = 0;
13161 while (nextopt("S") != '\0') {
13170 if (*argptr == NULL) {
13171 if (symbolic_mode) {
13172 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13179 *p++ = permuser[i];
13181 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13182 if (!(mask & 0400)) *p++ = 'r';
13183 if (!(mask & 0200)) *p++ = 'w';
13184 if (!(mask & 0100)) *p++ = 'x';
13192 out1fmt("%04o\n", mask);
13195 char *modestr = *argptr;
13196 /* numeric umasks are taken as-is */
13197 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13198 if (!isdigit(modestr[0]))
13200 mask = bb_parse_mode(modestr, mask);
13201 if ((unsigned)mask > 0777) {
13202 ash_msg_and_raise_error("illegal mode: %s", modestr);
13204 if (!isdigit(modestr[0]))
13211 static int FAST_FUNC
13212 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13214 return shell_builtin_ulimit(argv);
13217 /* ============ main() and helpers */
13220 * Called to exit the shell.
13229 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13230 save_history(line_input_state);
13232 status = exitstatus;
13233 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13234 if (setjmp(loc.loc)) {
13235 if (exception_type == EXEXIT)
13236 status = exitstatus;
13239 exception_handler = &loc;
13245 /*free(p); - we'll exit soon */
13248 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13249 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13252 flush_stdout_stderr();
13260 /* we will never free this */
13261 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13263 sigmode[SIGCHLD - 1] = S_DFL;
13264 setsignal(SIGCHLD);
13266 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13267 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13269 signal(SIGHUP, SIG_DFL);
13274 struct stat st1, st2;
13277 for (envp = environ; envp && *envp; envp++) {
13278 p = endofname(*envp);
13279 if (p != *envp && *p == '=') {
13280 setvareq(*envp, VEXPORT|VTEXTFIXED);
13284 setvareq((char*)defoptindvar, VTEXTFIXED);
13286 setvar0("PPID", utoa(getppid()));
13287 #if ENABLE_ASH_BASH_COMPAT
13288 p = lookupvar("SHLVL");
13289 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13290 if (!lookupvar("HOSTNAME")) {
13291 struct utsname uts;
13293 setvar0("HOSTNAME", uts.nodename);
13296 p = lookupvar("PWD");
13298 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13299 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13309 //usage:#define ash_trivial_usage
13310 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13311 //usage:#define ash_full_usage "\n\n"
13312 //usage: "Unix shell interpreter"
13315 * Process the shell command line arguments.
13318 procargs(char **argv)
13321 const char *xminusc;
13326 /* if (xargv[0]) - mmm, this is always true! */
13328 for (i = 0; i < NOPTS; i++)
13331 if (options(/*cmdline:*/ 1)) {
13332 /* it already printed err message */
13333 raise_exception(EXERROR);
13337 if (*xargv == NULL) {
13339 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13342 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13346 for (i = 0; i < NOPTS; i++)
13347 if (optlist[i] == 2)
13352 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13357 } else if (!sflag) {
13358 setinputfile(*xargv, 0);
13361 commandname = arg0;
13364 shellparam.p = xargv;
13365 #if ENABLE_ASH_GETOPTS
13366 shellparam.optind = 1;
13367 shellparam.optoff = -1;
13369 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13371 shellparam.nparam++;
13378 * Read /etc/profile, ~/.profile, $ENV.
13381 read_profile(const char *name)
13383 name = expandstr(name);
13384 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13391 * This routine is called when an error or an interrupt occurs in an
13392 * interactive shell and control is returned to the main command loop.
13393 * (In dash, this function is auto-generated by build machinery).
13402 /* from expand.c: */
13405 /* from input.c: */
13406 g_parsefile->left_in_buffer = 0;
13407 g_parsefile->left_in_line = 0; /* clear input buffer */
13410 /* from redir.c: */
13412 popredir(/*drop:*/ 0, /*restore:*/ 0);
13416 static short profile_buf[16384];
13417 extern int etext();
13421 * Main routine. We initialize things, parse the arguments, execute
13422 * profiles if we're a login shell, and then call cmdloop to execute
13423 * commands. The setjmp call sets up the location to jump to when an
13424 * exception occurs. When an exception occurs the variable "state"
13425 * is used to figure out how far we had gotten.
13427 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13428 int ash_main(int argc UNUSED_PARAM, char **argv)
13430 volatile smallint state;
13431 struct jmploc jmploc;
13432 struct stackmark smark;
13434 /* Initialize global data */
13438 #if ENABLE_ASH_ALIAS
13444 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13447 #if ENABLE_FEATURE_EDITING
13448 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13451 if (setjmp(jmploc.loc)) {
13457 e = exception_type;
13459 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13463 newline_and_flush(stderr);
13466 popstackmark(&smark);
13467 FORCE_INT_ON; /* enable interrupts */
13476 exception_handler = &jmploc;
13477 rootpid = getpid();
13480 setstackmark(&smark);
13483 TRACE(("Shell args: "));
13484 trace_puts_args(argv);
13487 if (argv[0] && argv[0][0] == '-')
13493 read_profile("/etc/profile");
13496 hp = lookupvar("HOME");
13498 read_profile("$HOME/.profile");
13504 getuid() == geteuid() && getgid() == getegid() &&
13508 const char *shinit = lookupvar("ENV");
13509 if (shinit != NULL && *shinit != '\0')
13510 read_profile(shinit);
13512 popstackmark(&smark);
13516 /* evalstring pushes parsefile stack.
13517 * Ensure we don't falsely claim that 0 (stdin)
13518 * is one of stacked source fds.
13519 * Testcase: ash -c 'exec 1>&0' must not complain. */
13520 // if (!sflag) g_parsefile->pf_fd = -1;
13521 // ^^ not necessary since now we special-case fd 0
13522 // in is_hidden_fd() to not be considered "hidden fd"
13523 evalstring(minusc, 0);
13526 if (sflag || minusc == NULL) {
13527 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13529 const char *hp = lookupvar("HISTFILE");
13531 hp = lookupvar("HOME");
13533 hp = concat_path_file(hp, ".ash_history");
13534 setvar0("HISTFILE", hp);
13536 hp = lookupvar("HISTFILE");
13540 line_input_state->hist_file = hp;
13541 # if ENABLE_FEATURE_SH_HISTFILESIZE
13542 hp = lookupvar("HISTFILESIZE");
13543 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13547 state4: /* XXX ??? - why isn't this before the "if" statement */
13555 extern void _mcleanup(void);
13559 TRACE(("End of main reached\n"));
13566 * Copyright (c) 1989, 1991, 1993, 1994
13567 * The Regents of the University of California. All rights reserved.
13569 * This code is derived from software contributed to Berkeley by
13570 * Kenneth Almquist.
13572 * Redistribution and use in source and binary forms, with or without
13573 * modification, are permitted provided that the following conditions
13575 * 1. Redistributions of source code must retain the above copyright
13576 * notice, this list of conditions and the following disclaimer.
13577 * 2. Redistributions in binary form must reproduce the above copyright
13578 * notice, this list of conditions and the following disclaimer in the
13579 * documentation and/or other materials provided with the distribution.
13580 * 3. Neither the name of the University nor the names of its contributors
13581 * may be used to endorse or promote products derived from this software
13582 * without specific prior written permission.
13584 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13585 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13586 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13587 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13588 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13589 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13590 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13591 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13592 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13593 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF