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.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_BASH_SOURCE_CURDIR
55 //config: bool "'source' and '.' builtins search current directory after $PATH"
56 //config: default n # do not encourage non-standard behavior
57 //config: depends on ASH_BASH_COMPAT
59 //config: This is not compliant with standards. Avoid if possible.
61 //config:config ASH_BASH_NOT_FOUND_HOOK
62 //config: bool "command_not_found_handle hook support"
64 //config: depends on ASH_BASH_COMPAT
66 //config: Enable support for the 'command_not_found_handle' hook function,
67 //config: from GNU bash, which allows for alternative command not found
70 //config:config ASH_JOB_CONTROL
71 //config: bool "Job control"
73 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
75 //config:config ASH_ALIAS
76 //config: bool "Alias support"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config:config ASH_RANDOM_SUPPORT
81 //config: bool "Pseudorandom generator and $RANDOM variable"
83 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
85 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
86 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
87 //config: You can reset the generator by using a specified start value.
88 //config: After "unset RANDOM" the generator will switch off and this
89 //config: variable will no longer have special treatment.
91 //config:config ASH_EXPAND_PRMT
92 //config: bool "Expand prompt string"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: $PS# may contain volatile content, such as backquote commands.
97 //config: This option recreates the prompt string from the environment
98 //config: variable each time it is displayed.
100 //config:config ASH_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable $TMOUT"
103 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_MAIL
108 //config: bool "Check for new mail in interactive shell"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config: Enable "check for new mail" function:
113 //config: if set, $MAIL file and $MAILPATH list of files
114 //config: are checked for mtime changes, and "you have mail"
115 //config: message is printed if change is detected.
117 //config:config ASH_ECHO
118 //config: bool "echo builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_PRINTF
123 //config: bool "printf builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_TEST
128 //config: bool "test builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config:config ASH_HELP
133 //config: bool "help builtin"
135 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
137 //config:config ASH_GETOPTS
138 //config: bool "getopts builtin"
140 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
142 //config:config ASH_CMDCMD
143 //config: bool "command builtin"
145 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
147 //config: Enable support for the 'command' builtin, which allows
148 //config: you to run the specified command or builtin,
149 //config: even when there is a function with the same name.
151 //config:endif # ash options
153 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
154 // APPLET_ODDNAME:name main location suid_type help
155 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
156 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
158 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
159 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
160 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
161 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
164 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
165 * DEBUG=2 to compile in and turn on debugging.
166 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
167 * debugging info is written to ./trace, quit signal generates core dump.
170 /* Tweak debug output verbosity here */
174 #define DEBUG_INTONOFF 0
178 #define JOBS ENABLE_ASH_JOB_CONTROL
182 #include <sys/times.h>
183 #include <sys/utsname.h> /* for setting $HOSTNAME */
184 #include "busybox.h" /* for applet_names */
186 /* So far, all bash compat is controlled by one config option */
187 /* Separate defines document which part of code implements what */
188 /* function keyword */
189 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
190 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
192 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
193 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
195 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
196 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
197 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
198 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
199 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
200 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
202 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
203 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
204 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
205 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
206 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
207 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
208 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
209 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
211 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
212 /* Bionic at least up to version 24 has no glob() */
213 # undef ENABLE_ASH_INTERNAL_GLOB
214 # define ENABLE_ASH_INTERNAL_GLOB 1
217 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
218 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
219 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
220 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
221 # error glob() should unbackslash them and match. uClibc does not unbackslash,
222 # error fails to match dirname, subsequently not expanding <pattern> in it.
224 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
225 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
228 #if !ENABLE_ASH_INTERNAL_GLOB
233 #include "shell_common.h"
234 #if ENABLE_FEATURE_SH_MATH
237 typedef long arith_t;
238 # define ARITH_FMT "%ld"
240 #if ENABLE_ASH_RANDOM_SUPPORT
243 # define CLEAR_RANDOM_T(rnd) ((void)0)
246 #include "NUM_APPLETS.h"
248 /* STANDALONE does not make sense, and won't compile */
249 # undef CONFIG_FEATURE_SH_STANDALONE
250 # undef ENABLE_FEATURE_SH_STANDALONE
251 # undef IF_FEATURE_SH_STANDALONE
252 # undef IF_NOT_FEATURE_SH_STANDALONE
253 # define ENABLE_FEATURE_SH_STANDALONE 0
254 # define IF_FEATURE_SH_STANDALONE(...)
255 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
258 #ifndef F_DUPFD_CLOEXEC
259 # define F_DUPFD_CLOEXEC F_DUPFD
265 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
269 # error "Do not even bother, ash will not run on NOMMU machine"
272 /* We use a trick to have more optimized code (fewer pointer reloads):
273 * ash.c: extern struct globals *const ash_ptr_to_globals;
274 * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
275 * This way, compiler in ash.c knows the pointer can not change.
277 * However, this may break on weird arches or toolchains. In this case,
278 * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
281 #ifndef BB_GLOBAL_CONST
282 # define BB_GLOBAL_CONST const
286 /* ============ Hash table sizes. Configurable. */
290 #define CMDTABLESIZE 31 /* should be prime */
293 /* ============ Shell options */
295 static const char *const optletters_optnames[] = {
319 #define optletters(n) optletters_optnames[n][0]
320 #define optnames(n) (optletters_optnames[n] + 1)
322 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
325 /* ============ Misc data */
327 #define msg_illnum "Illegal number: %s"
330 * We enclose jmp_buf in a structure so that we can declare pointers to
331 * jump locations. The global variable handler contains the location to
332 * jump to when an exception occurs, and the global variable exception_type
333 * contains a code identifying the exception. To implement nested
334 * exception handlers, the user should save the value of handler on entry
335 * to an inner scope, set handler to point to a jmploc structure for the
336 * inner scope, and restore handler on exit from the scope.
342 struct globals_misc {
343 uint8_t exitstatus; /* exit status of last command */
344 uint8_t back_exitstatus;/* exit status of backquoted command */
345 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
346 int rootpid; /* pid of main shell */
347 /* shell level: 0 for the main shell, 1 for its children, and so on */
349 #define rootshell (!shlvl)
352 char *minusc; /* argument to -c option */
354 char *curdir; // = nullstr; /* current working directory */
355 char *physdir; // = nullstr; /* physical working directory */
357 char *arg0; /* value of $0 */
359 struct jmploc *exception_handler;
361 volatile int suppress_int; /* counter */
362 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
363 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
364 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
365 smallint exception_type; /* kind of exception (0..5) */
367 #define EXINT 0 /* SIGINT received */
368 #define EXERROR 1 /* a generic error */
369 #define EXEXIT 4 /* exit the shell */
371 char nullstr[1]; /* zero length string */
374 #define eflag optlist[0]
375 #define fflag optlist[1]
376 #define Iflag optlist[2]
377 #define iflag optlist[3]
378 #define mflag optlist[4]
379 #define nflag optlist[5]
380 #define sflag optlist[6]
381 #define xflag optlist[7]
382 #define vflag optlist[8]
383 #define Cflag optlist[9]
384 #define aflag optlist[10]
385 #define bflag optlist[11]
386 #define uflag optlist[12]
387 #define viflag optlist[13]
389 # define pipefail optlist[14]
394 # define nolog optlist[14 + BASH_PIPEFAIL]
395 # define debug optlist[15 + BASH_PIPEFAIL]
398 /* trap handler commands */
400 * Sigmode records the current value of the signal handlers for the various
401 * modes. A value of zero means that the current handler is not known.
402 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
404 char sigmode[NSIG - 1];
405 #define S_DFL 1 /* default signal handling (SIG_DFL) */
406 #define S_CATCH 2 /* signal is caught */
407 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
408 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
410 /* indicates specified signal received */
411 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
412 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
414 char **trap_ptr; /* used only by "trap hack" */
416 /* Rarely referenced stuff */
417 #if ENABLE_ASH_RANDOM_SUPPORT
420 pid_t backgndpid; /* pid of last background process */
422 extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
423 #define G_misc (*ash_ptr_to_globals_misc)
424 #define exitstatus (G_misc.exitstatus )
425 #define back_exitstatus (G_misc.back_exitstatus )
426 #define job_warning (G_misc.job_warning)
427 #define rootpid (G_misc.rootpid )
428 #define shlvl (G_misc.shlvl )
429 #define errlinno (G_misc.errlinno )
430 #define minusc (G_misc.minusc )
431 #define curdir (G_misc.curdir )
432 #define physdir (G_misc.physdir )
433 #define arg0 (G_misc.arg0 )
434 #define exception_handler (G_misc.exception_handler)
435 #define exception_type (G_misc.exception_type )
436 #define suppress_int (G_misc.suppress_int )
437 #define pending_int (G_misc.pending_int )
438 #define got_sigchld (G_misc.got_sigchld )
439 #define pending_sig (G_misc.pending_sig )
440 #define nullstr (G_misc.nullstr )
441 #define optlist (G_misc.optlist )
442 #define sigmode (G_misc.sigmode )
443 #define gotsig (G_misc.gotsig )
444 #define may_have_traps (G_misc.may_have_traps )
445 #define trap (G_misc.trap )
446 #define trap_ptr (G_misc.trap_ptr )
447 #define random_gen (G_misc.random_gen )
448 #define backgndpid (G_misc.backgndpid )
449 #define INIT_G_misc() do { \
450 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
458 /* ============ DEBUG */
460 static void trace_printf(const char *fmt, ...);
461 static void trace_vprintf(const char *fmt, va_list va);
462 # define TRACE(param) trace_printf param
463 # define TRACEV(param) trace_vprintf param
464 # define close(fd) do { \
466 if (close(dfd) < 0) \
467 bb_error_msg("bug on %d: closing %d(0x%x)", \
468 __LINE__, dfd, dfd); \
471 # define TRACE(param)
472 # define TRACEV(param)
476 /* ============ Utility functions */
477 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
478 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
481 isdigit_str9(const char *str)
483 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
484 while (--maxlen && isdigit(*str))
486 return (*str == '\0');
490 var_end(const char *var)
499 /* ============ Interrupts / exceptions */
501 static void exitshell(void) NORETURN;
504 * These macros allow the user to suspend the handling of interrupt signals
505 * over a period of time. This is similar to SIGHOLD or to sigblock, but
506 * much more efficient and portable. (But hacking the kernel is so much
507 * more fun than worrying about efficiency and portability. :-))
510 # define INT_OFF do { \
511 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
516 # define INT_OFF do { \
523 * Called to raise an exception. Since C doesn't include exceptions, we
524 * just do a longjmp to the exception handler. The type of exception is
525 * stored in the global variable "exception_type".
527 static void raise_exception(int) NORETURN;
529 raise_exception(int e)
532 if (exception_handler == NULL)
537 longjmp(exception_handler->loc, 1);
540 #define raise_exception(e) do { \
541 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
542 raise_exception(e); \
547 * Called when a SIGINT is received. (If the user specifies
548 * that SIGINT is to be trapped or ignored using the trap builtin, then
549 * this routine is not called.) Suppressint is nonzero when interrupts
550 * are held using the INT_OFF macro. (The test for iflag is just
551 * defensive programming.)
553 static void raise_interrupt(void) NORETURN;
555 raise_interrupt(void)
558 /* Signal is not automatically unmasked after it is raised,
559 * do it ourself - unmask all signals */
560 sigprocmask_allsigs(SIG_UNBLOCK);
561 /* pending_sig = 0; - now done in signal_handler() */
563 if (!(rootshell && iflag)) {
564 /* Kill ourself with SIGINT */
565 signal(SIGINT, SIG_DFL);
568 /* bash: ^C even on empty command line sets $? */
569 exitstatus = SIGINT + 128;
570 raise_exception(EXINT);
574 #define raise_interrupt() do { \
575 TRACE(("raising interrupt on line %d\n", __LINE__)); \
580 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
584 if (--suppress_int == 0 && pending_int) {
589 # define INT_ON do { \
590 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
594 # define INT_ON int_on()
596 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
604 #define FORCE_INT_ON force_int_on()
606 #define SAVE_INT(v) ((v) = suppress_int)
608 #define RESTORE_INT(v) do { \
610 suppress_int = (v); \
611 if (suppress_int == 0 && pending_int) \
616 /* ============ Stdout/stderr output */
619 outstr(const char *p, FILE *file)
627 flush_stdout_stderr(void)
634 /* Was called outcslow(c,FILE*), but c was always '\n' */
636 newline_and_flush(FILE *dest)
644 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
646 out1fmt(const char *fmt, ...)
653 r = vprintf(fmt, ap);
659 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
661 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
668 ret = vsnprintf(outbuf, length, fmt, ap);
675 out1str(const char *p)
681 out2str(const char *p)
684 flush_stdout_stderr();
688 /* ============ Parser structures */
690 /* control characters in argument strings */
691 #define CTL_FIRST CTLESC
692 #define CTLESC ((unsigned char)'\201') /* escape next character */
693 #define CTLVAR ((unsigned char)'\202') /* variable defn */
694 #define CTLENDVAR ((unsigned char)'\203')
695 #define CTLBACKQ ((unsigned char)'\204')
696 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
697 #define CTLENDARI ((unsigned char)'\207')
698 #define CTLQUOTEMARK ((unsigned char)'\210')
699 #define CTL_LAST CTLQUOTEMARK
701 /* variable substitution byte (follows CTLVAR) */
702 #define VSTYPE 0x0f /* type of variable substitution */
703 #define VSNUL 0x10 /* colon--treat the empty string as unset */
705 /* values of VSTYPE field */
706 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
707 #define VSMINUS 0x2 /* ${var-text} */
708 #define VSPLUS 0x3 /* ${var+text} */
709 #define VSQUESTION 0x4 /* ${var?message} */
710 #define VSASSIGN 0x5 /* ${var=text} */
711 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
712 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
713 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
714 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
715 #define VSLENGTH 0xa /* ${#var} */
717 #define VSSUBSTR 0xc /* ${var:position:length} */
719 #if BASH_PATTERN_SUBST
720 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
721 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
724 static const char dolatstr[] ALIGN1 = {
725 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
727 #define DOLATSTRLEN 6
746 #if BASH_REDIR_OUTPUT
763 smallint type; /* Nxxxx */
767 union node *redirect;
772 smallint pipe_backgnd;
773 struct nodelist *cmdlist;
780 union node *redirect;
793 union node *elsepart;
829 struct nodelist *backquote;
832 /* nfile and ndup layout must match!
833 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
834 * that it is actually NTO2 (>&file), and change its type.
851 char *_unused_expfname;
870 struct nredir nredir;
871 struct nbinary nbinary;
875 struct nclist nclist;
876 struct ndefun ndefun;
885 * NODE_EOF is returned by parsecmd when it encounters an end of file.
886 * It must be distinct from NULL.
888 #define NODE_EOF ((union node *) -1L)
891 struct nodelist *next;
904 freefunc(struct funcnode *f)
906 if (f && --f->count < 0)
911 /* ============ Debugging output */
915 static FILE *tracefile;
918 trace_printf(const char *fmt, ...)
925 fprintf(tracefile, "%u ", (int) time(NULL));
927 fprintf(tracefile, "[%u] ", (int) getpid());
929 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
931 vfprintf(tracefile, fmt, va);
936 trace_vprintf(const char *fmt, va_list va)
940 vfprintf(tracefile, fmt, va);
941 fprintf(tracefile, "\n");
945 trace_puts(const char *s)
953 trace_puts_quoted(char *s)
960 putc('"', tracefile);
961 for (p = s; *p; p++) {
962 switch ((unsigned char)*p) {
963 case '\n': c = 'n'; goto backslash;
964 case '\t': c = 't'; goto backslash;
965 case '\r': c = 'r'; goto backslash;
966 case '\"': c = '\"'; goto backslash;
967 case '\\': c = '\\'; goto backslash;
968 case CTLESC: c = 'e'; goto backslash;
969 case CTLVAR: c = 'v'; goto backslash;
970 case CTLBACKQ: c = 'q'; goto backslash;
972 putc('\\', tracefile);
976 if (*p >= ' ' && *p <= '~')
979 putc('\\', tracefile);
980 putc((*p >> 6) & 03, tracefile);
981 putc((*p >> 3) & 07, tracefile);
982 putc(*p & 07, tracefile);
987 putc('"', tracefile);
991 trace_puts_args(char **ap)
998 trace_puts_quoted(*ap);
1000 putc('\n', tracefile);
1003 putc(' ', tracefile);
1018 /* leave open because libedit might be using it */
1021 strcpy(s, "./trace");
1023 if (!freopen(s, "a", tracefile)) {
1024 fprintf(stderr, "Can't re-open %s\n", s);
1029 tracefile = fopen(s, "a");
1030 if (tracefile == NULL) {
1031 fprintf(stderr, "Can't open %s\n", s);
1037 flags = fcntl(fileno(tracefile), F_GETFL);
1039 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1041 setlinebuf(tracefile);
1042 fputs("\nTracing started.\n", tracefile);
1046 indent(int amount, char *pfx, FILE *fp)
1050 for (i = 0; i < amount; i++) {
1051 if (pfx && i == amount - 1)
1057 /* little circular references here... */
1058 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1061 sharg(union node *arg, FILE *fp)
1064 struct nodelist *bqlist;
1065 unsigned char subtype;
1067 if (arg->type != NARG) {
1068 out1fmt("<node type %d>\n", arg->type);
1071 bqlist = arg->narg.backquote;
1072 for (p = arg->narg.text; *p; p++) {
1073 switch ((unsigned char)*p) {
1082 if (subtype == VSLENGTH)
1090 if (subtype & VSNUL)
1093 switch (subtype & VSTYPE) {
1119 case VSTRIMRIGHTMAX:
1126 out1fmt("<subtype %d>", subtype);
1135 shtree(bqlist->n, -1, NULL, fp);
1146 shcmd(union node *cmd, FILE *fp)
1154 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1160 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1164 switch (np->nfile.type) {
1165 case NTO: s = ">>"+1; dftfd = 1; break;
1166 case NCLOBBER: s = ">|"; dftfd = 1; break;
1167 case NAPPEND: s = ">>"; dftfd = 1; break;
1168 #if BASH_REDIR_OUTPUT
1171 case NTOFD: s = ">&"; dftfd = 1; break;
1172 case NFROM: s = "<"; break;
1173 case NFROMFD: s = "<&"; break;
1174 case NFROMTO: s = "<>"; break;
1175 default: s = "*error*"; break;
1177 if (np->nfile.fd != dftfd)
1178 fprintf(fp, "%d", np->nfile.fd);
1180 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1181 fprintf(fp, "%d", np->ndup.dupfd);
1183 sharg(np->nfile.fname, fp);
1190 shtree(union node *n, int ind, char *pfx, FILE *fp)
1192 struct nodelist *lp;
1198 indent(ind, pfx, fp);
1200 if (n == NODE_EOF) {
1215 shtree(n->nbinary.ch1, ind, NULL, fp);
1218 shtree(n->nbinary.ch2, ind, NULL, fp);
1226 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1227 shtree(lp->n, 0, NULL, fp);
1231 if (n->npipe.pipe_backgnd)
1237 fprintf(fp, "<node type %d>", n->type);
1245 showtree(union node *n)
1247 trace_puts("showtree called\n");
1248 shtree(n, 1, NULL, stderr);
1254 /* ============ Parser data */
1257 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1260 struct strlist *next;
1267 struct strpush *prev; /* preceding string on stack */
1269 int prev_left_in_line;
1270 #if ENABLE_ASH_ALIAS
1271 struct alias *ap; /* if push was associated with an alias */
1273 char *string; /* remember the string since it may change */
1275 /* Remember last two characters for pungetc. */
1278 /* Number of outstanding calls to pungetc. */
1283 * The parsefile structure pointed to by the global variable parsefile
1284 * contains information about the current file being read.
1287 struct parsefile *prev; /* preceding file on stack */
1288 int linno; /* current line */
1289 int pf_fd; /* file descriptor (or -1 if string) */
1290 int left_in_line; /* number of chars left in this line */
1291 int left_in_buffer; /* number of chars left in this buffer past the line */
1292 char *next_to_pgetc; /* next char in buffer */
1293 char *buf; /* input buffer */
1294 struct strpush *strpush; /* for pushing strings at this level */
1295 struct strpush basestrpush; /* so pushing one is fast */
1297 /* Remember last two characters for pungetc. */
1300 /* Number of outstanding calls to pungetc. */
1304 static struct parsefile basepf; /* top level input file */
1305 static struct parsefile *g_parsefile = &basepf; /* current input file */
1306 static char *commandname; /* currently executing command */
1309 /* ============ Message printing */
1312 ash_vmsg(const char *msg, va_list ap)
1314 fprintf(stderr, "%s: ", arg0);
1316 if (strcmp(arg0, commandname))
1317 fprintf(stderr, "%s: ", commandname);
1318 if (!iflag || g_parsefile->pf_fd > 0)
1319 fprintf(stderr, "line %d: ", errlinno);
1321 vfprintf(stderr, msg, ap);
1322 newline_and_flush(stderr);
1326 * Exverror is called to raise the error exception. If the second argument
1327 * is not NULL then error prints an error message using printf style
1328 * formatting. It then raises the error exception.
1330 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1332 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1336 TRACE(("ash_vmsg_and_raise(%d):", cond));
1339 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1344 flush_stdout_stderr();
1345 raise_exception(cond);
1349 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1351 ash_msg_and_raise_error(const char *msg, ...)
1358 ash_vmsg_and_raise(EXERROR, msg, ap);
1364 * 'fmt' must be a string literal.
1366 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1368 static void raise_error_syntax(const char *) NORETURN;
1370 raise_error_syntax(const char *msg)
1372 errlinno = g_parsefile->linno;
1373 ash_msg_and_raise_error("syntax error: %s", msg);
1377 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1379 ash_msg_and_raise(int cond, const char *msg, ...)
1384 ash_vmsg_and_raise(cond, msg, ap);
1390 * error/warning routines for external builtins
1393 ash_msg(const char *fmt, ...)
1403 * Return a string describing an error. The returned string may be a
1404 * pointer to a static buffer that will be overwritten on the next call.
1405 * Action describes the operation that got the error.
1408 errmsg(int e, const char *em)
1410 if (e == ENOENT || e == ENOTDIR) {
1417 /* ============ Memory allocation */
1420 /* I consider these wrappers nearly useless:
1421 * ok, they return you to nearest exception handler, but
1422 * how much memory do you leak in the process, making
1423 * memory starvation worse?
1426 ckrealloc(void * p, size_t nbytes)
1428 p = realloc(p, nbytes);
1430 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1435 ckmalloc(size_t nbytes)
1437 return ckrealloc(NULL, nbytes);
1441 ckzalloc(size_t nbytes)
1443 return memset(ckmalloc(nbytes), 0, nbytes);
1447 ckstrdup(const char *s)
1449 char *p = strdup(s);
1451 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1455 /* Using bbox equivalents. They exit if out of memory */
1456 # define ckrealloc xrealloc
1457 # define ckmalloc xmalloc
1458 # define ckzalloc xzalloc
1459 # define ckstrdup xstrdup
1463 * It appears that grabstackstr() will barf with such alignments
1464 * because stalloc() will return a string allocated in a new stackblock.
1466 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1468 /* Most machines require the value returned from malloc to be aligned
1469 * in some way. The following macro will get this right
1470 * on many machines. */
1471 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1472 /* Minimum size of a block */
1473 MINSIZE = SHELL_ALIGN(504),
1476 struct stack_block {
1477 struct stack_block *prev;
1478 char space[MINSIZE];
1482 struct stack_block *stackp;
1488 struct globals_memstack {
1489 struct stack_block *g_stackp; // = &stackbase;
1490 char *g_stacknxt; // = stackbase.space;
1491 char *sstrend; // = stackbase.space + MINSIZE;
1492 size_t g_stacknleft; // = MINSIZE;
1493 struct stack_block stackbase;
1495 extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
1496 #define G_memstack (*ash_ptr_to_globals_memstack)
1497 #define g_stackp (G_memstack.g_stackp )
1498 #define g_stacknxt (G_memstack.g_stacknxt )
1499 #define sstrend (G_memstack.sstrend )
1500 #define g_stacknleft (G_memstack.g_stacknleft)
1501 #define stackbase (G_memstack.stackbase )
1502 #define INIT_G_memstack() do { \
1503 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1505 g_stackp = &stackbase; \
1506 g_stacknxt = stackbase.space; \
1507 g_stacknleft = MINSIZE; \
1508 sstrend = stackbase.space + MINSIZE; \
1512 #define stackblock() ((void *)g_stacknxt)
1513 #define stackblocksize() g_stacknleft
1516 * Parse trees for commands are allocated in lifo order, so we use a stack
1517 * to make this more efficient, and also to avoid all sorts of exception
1518 * handling code to handle interrupts in the middle of a parse.
1520 * The size 504 was chosen because the Ultrix malloc handles that size
1524 stalloc(size_t nbytes)
1529 aligned = SHELL_ALIGN(nbytes);
1530 if (aligned > g_stacknleft) {
1533 struct stack_block *sp;
1535 blocksize = aligned;
1536 if (blocksize < MINSIZE)
1537 blocksize = MINSIZE;
1538 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1539 if (len < blocksize)
1540 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1543 sp->prev = g_stackp;
1544 g_stacknxt = sp->space;
1545 g_stacknleft = blocksize;
1546 sstrend = g_stacknxt + blocksize;
1551 g_stacknxt += aligned;
1552 g_stacknleft -= aligned;
1557 stzalloc(size_t nbytes)
1559 return memset(stalloc(nbytes), 0, nbytes);
1566 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1567 write(STDERR_FILENO, "stunalloc\n", 10);
1571 g_stacknleft += g_stacknxt - (char *)p;
1576 * Like strdup but works with the ash stack.
1579 sstrdup(const char *p)
1581 size_t len = strlen(p) + 1;
1582 return memcpy(stalloc(len), p, len);
1585 static ALWAYS_INLINE void
1586 grabstackblock(size_t len)
1592 pushstackmark(struct stackmark *mark, size_t len)
1594 mark->stackp = g_stackp;
1595 mark->stacknxt = g_stacknxt;
1596 mark->stacknleft = g_stacknleft;
1597 grabstackblock(len);
1601 setstackmark(struct stackmark *mark)
1603 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1607 popstackmark(struct stackmark *mark)
1609 struct stack_block *sp;
1615 while (g_stackp != mark->stackp) {
1617 g_stackp = sp->prev;
1620 g_stacknxt = mark->stacknxt;
1621 g_stacknleft = mark->stacknleft;
1622 sstrend = mark->stacknxt + mark->stacknleft;
1627 * When the parser reads in a string, it wants to stick the string on the
1628 * stack and only adjust the stack pointer when it knows how big the
1629 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1630 * of space on top of the stack and stackblocklen returns the length of
1631 * this block. Growstackblock will grow this space by at least one byte,
1632 * possibly moving it (like realloc). Grabstackblock actually allocates the
1633 * part of the block that has been used.
1636 growstackblock(void)
1640 newlen = g_stacknleft * 2;
1641 if (newlen < g_stacknleft)
1642 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1646 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1647 struct stack_block *sp;
1648 struct stack_block *prevstackp;
1653 prevstackp = sp->prev;
1654 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1655 sp = ckrealloc(sp, grosslen);
1656 sp->prev = prevstackp;
1658 g_stacknxt = sp->space;
1659 g_stacknleft = newlen;
1660 sstrend = sp->space + newlen;
1663 char *oldspace = g_stacknxt;
1664 size_t oldlen = g_stacknleft;
1665 char *p = stalloc(newlen);
1667 /* free the space we just allocated */
1668 g_stacknxt = memcpy(p, oldspace, oldlen);
1669 g_stacknleft += newlen;
1674 * The following routines are somewhat easier to use than the above.
1675 * The user declares a variable of type STACKSTR, which may be declared
1676 * to be a register. The macro STARTSTACKSTR initializes things. Then
1677 * the user uses the macro STPUTC to add characters to the string. In
1678 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1679 * grown as necessary. When the user is done, she can just leave the
1680 * string there and refer to it using stackblock(). Or she can allocate
1681 * the space for it using grabstackstr(). If it is necessary to allow
1682 * someone else to use the stack temporarily and then continue to grow
1683 * the string, the user should use grabstack to allocate the space, and
1684 * then call ungrabstr(p) to return to the previous mode of operation.
1686 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1687 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1688 * is space for at least one character.
1693 size_t len = stackblocksize();
1695 return (char *)stackblock() + len;
1699 * Called from CHECKSTRSPACE.
1702 makestrspace(size_t newlen, char *p)
1704 size_t len = p - g_stacknxt;
1710 size = stackblocksize();
1712 if (nleft >= newlen)
1716 return (char *)stackblock() + len;
1720 stack_nputstr(const char *s, size_t n, char *p)
1722 p = makestrspace(n, p);
1723 p = (char *)mempcpy(p, s, n);
1728 stack_putstr(const char *s, char *p)
1730 return stack_nputstr(s, strlen(s), p);
1734 _STPUTC(int c, char *p)
1742 #define STARTSTACKSTR(p) ((p) = stackblock())
1743 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1744 #define CHECKSTRSPACE(n, p) do { \
1747 size_t m = sstrend - q; \
1749 (p) = makestrspace(l, q); \
1751 #define USTPUTC(c, p) (*(p)++ = (c))
1752 #define STACKSTRNUL(p) do { \
1753 if ((p) == sstrend) \
1754 (p) = growstackstr(); \
1757 #define STUNPUTC(p) (--(p))
1758 #define STTOPC(p) ((p)[-1])
1759 #define STADJUST(amount, p) ((p) += (amount))
1761 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1762 #define ungrabstackstr(s, p) stunalloc(s)
1763 #define stackstrend() ((void *)sstrend)
1766 /* ============ String helpers */
1769 * prefix -- see if pfx is a prefix of string.
1772 prefix(const char *string, const char *pfx)
1775 if (*pfx++ != *string++)
1778 return (char *) string;
1782 * Check for a valid number. This should be elsewhere.
1785 is_number(const char *p)
1790 } while (*++p != '\0');
1795 * Convert a string of digits to an integer, printing an error message on
1799 number(const char *s)
1802 ash_msg_and_raise_error(msg_illnum, s);
1807 * Produce a single quoted string suitable as input to the shell.
1808 * The return string is allocated on the stack.
1811 single_quote(const char *s)
1821 len = strchrnul(s, '\'') - s;
1823 q = p = makestrspace(len + 3, p);
1826 q = (char *)mempcpy(q, s, len);
1835 do len++; while (*++s == '\'');
1837 q = p = makestrspace(len + 3, p);
1840 q = (char *)mempcpy(q, s - len, len);
1848 return stackblock();
1852 * Produce a possibly single quoted string suitable as input to the shell.
1853 * If quoting was done, the return string is allocated on the stack,
1854 * otherwise a pointer to the original string is returned.
1857 maybe_single_quote(const char *s)
1862 /* Assuming ACSII */
1863 /* quote ctrl_chars space !"#$%&'()* */
1867 if (*p >= ';' && *p <= '?')
1876 /* quote {|}~ DEL and high bytes */
1879 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1880 /* TODO: maybe avoid quoting % */
1886 return single_quote(s);
1890 /* ============ nextopt */
1892 static char **argptr; /* argument list for builtin commands */
1893 static char *optionarg; /* set by nextopt (like getopt) */
1894 static char *optptr; /* used by nextopt */
1897 * XXX - should get rid of. Have all builtins use getopt(3).
1898 * The library getopt must have the BSD extension static variable
1899 * "optreset", otherwise it can't be used within the shell safely.
1901 * Standard option processing (a la getopt) for builtin routines.
1902 * The only argument that is passed to nextopt is the option string;
1903 * the other arguments are unnecessary. It returns the character,
1904 * or '\0' on end of input.
1907 nextopt(const char *optstring)
1914 if (p == NULL || *p == '\0') {
1915 /* We ate entire "-param", take next one */
1921 if (*++p == '\0') /* just "-" ? */
1924 if (LONE_DASH(p)) /* "--" ? */
1926 /* p => next "-param" */
1928 /* p => some option char in the middle of a "-param" */
1930 for (q = optstring; *q != c;) {
1932 ash_msg_and_raise_error("illegal option -%c", c);
1940 ash_msg_and_raise_error("no arg for -%c option", c);
1950 /* ============ Shell variables */
1953 int nparam; /* # of positional parameters (without $0) */
1954 #if ENABLE_ASH_GETOPTS
1955 int optind; /* next parameter to be processed by getopts */
1956 int optoff; /* used by getopts */
1958 unsigned char malloced; /* if parameter list dynamically allocated */
1959 char **p; /* parameter list */
1963 * Free the list of positional parameters.
1966 freeparam(volatile struct shparam *param)
1968 if (param->malloced) {
1970 ap = ap1 = param->p;
1977 #if ENABLE_ASH_GETOPTS
1978 static void FAST_FUNC getoptsreset(const char *value);
1982 struct var *next; /* next entry in hash list */
1983 int flags; /* flags are defined above */
1984 const char *var_text; /* name=value */
1985 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1986 /* the variable gets set/unset */
1990 struct localvar *next; /* next local variable in list */
1991 struct var *vp; /* the variable that was made local */
1992 int flags; /* saved flags */
1993 const char *text; /* saved text */
1997 #define VEXPORT 0x01 /* variable is exported */
1998 #define VREADONLY 0x02 /* variable cannot be modified */
1999 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2000 #define VTEXTFIXED 0x08 /* text is statically allocated */
2001 #define VSTACK 0x10 /* text is allocated on the stack */
2002 #define VUNSET 0x20 /* the variable is not set */
2003 #define VNOFUNC 0x40 /* don't call the callback function */
2004 #define VNOSET 0x80 /* do not set variable - just readonly test */
2005 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2006 #if ENABLE_ASH_RANDOM_SUPPORT
2007 # define VDYNAMIC 0x200 /* dynamic variable */
2013 /* Need to be before varinit_data[] */
2014 #if ENABLE_LOCALE_SUPPORT
2015 static void FAST_FUNC
2016 change_lc_all(const char *value)
2018 if (value && *value != '\0')
2019 setlocale(LC_ALL, value);
2021 static void FAST_FUNC
2022 change_lc_ctype(const char *value)
2024 if (value && *value != '\0')
2025 setlocale(LC_CTYPE, value);
2029 static void chkmail(void);
2030 static void changemail(const char *var_value) FAST_FUNC;
2032 # define chkmail() ((void)0)
2034 static void changepath(const char *) FAST_FUNC;
2035 #if ENABLE_ASH_RANDOM_SUPPORT
2036 static void change_random(const char *) FAST_FUNC;
2039 static const struct {
2041 const char *var_text;
2042 void (*var_func)(const char *) FAST_FUNC;
2043 } varinit_data[] = {
2045 * Note: VEXPORT would not work correctly here for NOFORK applets:
2046 * some environment strings may be constant.
2048 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2050 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2051 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2053 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2054 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2055 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2056 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2057 #if ENABLE_ASH_GETOPTS
2058 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2060 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2061 #if ENABLE_ASH_RANDOM_SUPPORT
2062 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2064 #if ENABLE_LOCALE_SUPPORT
2065 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2066 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2068 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2069 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2075 struct globals_var {
2076 struct shparam shellparam; /* $@ current positional parameters */
2077 struct redirtab *redirlist;
2078 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2079 struct var *vartab[VTABSIZE];
2080 struct var varinit[ARRAY_SIZE(varinit_data)];
2082 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2084 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2085 #define G_var (*ash_ptr_to_globals_var)
2086 #define shellparam (G_var.shellparam )
2087 //#define redirlist (G_var.redirlist )
2088 #define preverrout_fd (G_var.preverrout_fd)
2089 #define vartab (G_var.vartab )
2090 #define varinit (G_var.varinit )
2091 #define lineno (G_var.lineno )
2092 #define linenovar (G_var.linenovar )
2093 #define vifs varinit[0]
2095 # define vmail (&vifs)[1]
2096 # define vmpath (&vmail)[1]
2097 # define vpath (&vmpath)[1]
2099 # define vpath (&vifs)[1]
2101 #define vps1 (&vpath)[1]
2102 #define vps2 (&vps1)[1]
2103 #define vps4 (&vps2)[1]
2104 #if ENABLE_ASH_GETOPTS
2105 # define voptind (&vps4)[1]
2106 # define vlineno (&voptind)[1]
2107 # if ENABLE_ASH_RANDOM_SUPPORT
2108 # define vrandom (&vlineno)[1]
2111 # define vlineno (&vps4)[1]
2112 # if ENABLE_ASH_RANDOM_SUPPORT
2113 # define vrandom (&vlineno)[1]
2116 #define INIT_G_var() do { \
2118 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2120 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2121 varinit[i].flags = varinit_data[i].flags; \
2122 varinit[i].var_text = varinit_data[i].var_text; \
2123 varinit[i].var_func = varinit_data[i].var_func; \
2125 strcpy(linenovar, "LINENO="); \
2126 vlineno.var_text = linenovar; \
2130 * The following macros access the values of the above variables.
2131 * They have to skip over the name. They return the null string
2132 * for unset variables.
2134 #define ifsval() (vifs.var_text + 4)
2135 #define ifsset() ((vifs.flags & VUNSET) == 0)
2137 # define mailval() (vmail.var_text + 5)
2138 # define mpathval() (vmpath.var_text + 9)
2139 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2141 #define pathval() (vpath.var_text + 5)
2142 #define ps1val() (vps1.var_text + 4)
2143 #define ps2val() (vps2.var_text + 4)
2144 #define ps4val() (vps4.var_text + 4)
2145 #if ENABLE_ASH_GETOPTS
2146 # define optindval() (voptind.var_text + 7)
2149 #if ENABLE_ASH_GETOPTS
2150 static void FAST_FUNC
2151 getoptsreset(const char *value)
2153 shellparam.optind = 1;
2154 if (is_number(value))
2155 shellparam.optind = number(value) ?: 1;
2156 shellparam.optoff = -1;
2161 * Compares two strings up to the first = or '\0'. The first
2162 * string must be terminated by '='; the second may be terminated by
2163 * either '=' or '\0'.
2166 varcmp(const char *p, const char *q)
2170 while ((c = *p) == (d = *q)) {
2171 if (c == '\0' || c == '=')
2185 * Find the appropriate entry in the hash table from the name.
2187 static struct var **
2188 hashvar(const char *p)
2192 hashval = ((unsigned char) *p) << 4;
2193 while (*p && *p != '=')
2194 hashval += (unsigned char) *p++;
2195 return &vartab[hashval % VTABSIZE];
2199 vpcmp(const void *a, const void *b)
2201 return varcmp(*(const char **)a, *(const char **)b);
2205 * This routine initializes the builtin variables.
2215 * PS1 depends on uid
2217 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2218 vps1.var_text = "PS1=\\w \\$ ";
2221 vps1.var_text = "PS1=# ";
2224 end = vp + ARRAY_SIZE(varinit);
2226 vpp = hashvar(vp->var_text);
2229 } while (++vp < end);
2232 static struct var **
2233 findvar(struct var **vpp, const char *name)
2235 for (; *vpp; vpp = &(*vpp)->next) {
2236 if (varcmp((*vpp)->var_text, name) == 0) {
2244 * Find the value of a variable. Returns NULL if not set.
2246 static const char* FAST_FUNC
2247 lookupvar(const char *name)
2251 v = *findvar(hashvar(name), name);
2253 #if ENABLE_ASH_RANDOM_SUPPORT
2255 * Dynamic variables are implemented roughly the same way they are
2256 * in bash. Namely, they're "special" so long as they aren't unset.
2257 * As soon as they're unset, they're no longer dynamic, and dynamic
2258 * lookup will no longer happen at that point. -- PFM.
2260 if (v->flags & VDYNAMIC)
2263 if (!(v->flags & VUNSET)) {
2264 if (v == &vlineno && v->var_text == linenovar) {
2265 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2267 return var_end(v->var_text);
2273 #if ENABLE_UNICODE_SUPPORT
2275 reinit_unicode_for_ash(void)
2277 /* Unicode support should be activated even if LANG is set
2278 * _during_ shell execution, not only if it was set when
2279 * shell was started. Therefore, re-check LANG every time:
2281 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2282 || ENABLE_UNICODE_USING_LOCALE
2284 const char *s = lookupvar("LC_ALL");
2285 if (!s) s = lookupvar("LC_CTYPE");
2286 if (!s) s = lookupvar("LANG");
2291 # define reinit_unicode_for_ash() ((void)0)
2295 * Search the environment of a builtin command.
2297 static ALWAYS_INLINE const char *
2298 bltinlookup(const char *name)
2300 return lookupvar(name);
2304 * Same as setvar except that the variable and value are passed in
2305 * the first argument as name=value. Since the first argument will
2306 * be actually stored in the table, it should not be a string that
2308 * Called with interrupts off.
2311 setvareq(char *s, int flags)
2313 struct var *vp, **vpp;
2316 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2317 vpp = findvar(vpp, s);
2320 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2323 if (flags & VNOSAVE)
2327 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2333 if (vp->var_func && !(flags & VNOFUNC))
2334 vp->var_func(var_end(s));
2336 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2337 free((char*)vp->var_text);
2339 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2343 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2348 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2350 /* variable s is not found */
2353 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2355 vp = ckzalloc(sizeof(*vp));
2357 /*vp->func = NULL; - ckzalloc did it */
2360 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2370 * Set the value of a variable. The flags argument is ored with the
2371 * flags of the variable. If val is NULL, the variable is unset.
2374 setvar(const char *name, const char *val, int flags)
2383 q = endofname(name);
2384 p = strchrnul(q, '=');
2386 if (!namelen || p != q)
2387 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2392 vallen = strlen(val);
2396 nameeq = ckmalloc(namelen + vallen + 2);
2397 p = mempcpy(nameeq, name, namelen);
2400 p = mempcpy(p, val, vallen);
2403 vp = setvareq(nameeq, flags | VNOSAVE);
2409 static void FAST_FUNC
2410 setvar0(const char *name, const char *val)
2412 setvar(name, val, 0);
2416 * Unset the specified variable.
2419 unsetvar(const char *s)
2425 * Process a linked list of variable assignments.
2428 listsetvar(struct strlist *list_set_var, int flags)
2430 struct strlist *lp = list_set_var;
2436 setvareq(lp->text, flags);
2443 * Generate a list of variables satisfying the given conditions.
2445 #if !ENABLE_FEATURE_SH_NOFORK
2446 # define listvars(on, off, lp, end) listvars(on, off, end)
2449 listvars(int on, int off, struct strlist *lp, char ***end)
2460 for (vp = *vpp; vp; vp = vp->next) {
2461 if ((vp->flags & mask) == on) {
2462 #if ENABLE_FEATURE_SH_NOFORK
2463 /* If variable with the same name is both
2464 * exported and temporarily set for a command:
2467 * then "ZVAR=6" will be both in vartab and
2468 * lp lists. Do not pass it twice to printenv.
2470 struct strlist *lp1 = lp;
2472 if (strcmp(lp1->text, vp->var_text) == 0)
2477 if (ep == stackstrend())
2478 ep = growstackstr();
2479 *ep++ = (char*)vp->var_text;
2480 #if ENABLE_FEATURE_SH_NOFORK
2485 } while (++vpp < vartab + VTABSIZE);
2487 #if ENABLE_FEATURE_SH_NOFORK
2489 if (ep == stackstrend())
2490 ep = growstackstr();
2496 if (ep == stackstrend())
2497 ep = growstackstr();
2501 return grabstackstr(ep);
2505 /* ============ Path search helper
2507 * The variable path (passed by reference) should be set to the start
2508 * of the path before the first call; path_advance will update
2509 * this value as it proceeds. Successive calls to path_advance will return
2510 * the possible path expansions in sequence. If an option (indicated by
2511 * a percent sign) appears in the path entry then the global variable
2512 * pathopt will be set to point to it; otherwise pathopt will be set to
2515 static const char *pathopt; /* set by path_advance */
2518 path_advance(const char **path, const char *name)
2528 for (p = start; *p && *p != ':' && *p != '%'; p++)
2530 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2531 while (stackblocksize() < len)
2535 q = mempcpy(q, start, p - start);
2542 while (*p && *p != ':')
2549 return stalloc(len);
2553 /* ============ Prompt */
2555 static smallint doprompt; /* if set, prompt the user */
2556 static smallint needprompt; /* true if interactive and at start of line */
2558 #if ENABLE_FEATURE_EDITING
2559 static line_input_t *line_input_state;
2560 static const char *cmdedit_prompt;
2562 putprompt(const char *s)
2564 if (ENABLE_ASH_EXPAND_PRMT) {
2565 free((char*)cmdedit_prompt);
2566 cmdedit_prompt = ckstrdup(s);
2573 putprompt(const char *s)
2579 /* expandstr() needs parsing machinery, so it is far away ahead... */
2580 static const char *expandstr(const char *ps, int syntax_type);
2581 /* Values for syntax param */
2582 #define BASESYNTAX 0 /* not in quotes */
2583 #define DQSYNTAX 1 /* in double quotes */
2584 #define SQSYNTAX 2 /* in single quotes */
2585 #define ARISYNTAX 3 /* in arithmetic */
2586 #if ENABLE_ASH_EXPAND_PRMT
2587 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2589 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2592 * called by editline -- any expansions to the prompt should be added here.
2595 setprompt_if(smallint do_set, int whichprompt)
2598 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2605 switch (whichprompt) {
2615 #if ENABLE_ASH_EXPAND_PRMT
2616 pushstackmark(&smark, stackblocksize());
2617 putprompt(expandstr(prompt, PSSYNTAX));
2618 popstackmark(&smark);
2625 /* ============ The cd and pwd commands */
2627 #define CD_PHYSICAL 1
2637 while ((i = nextopt("LP")) != '\0') {
2639 flags ^= CD_PHYSICAL;
2648 * Update curdir (the name of the current directory) in response to a
2652 updatepwd(const char *dir)
2659 cdcomppath = sstrdup(dir);
2662 if (curdir == nullstr)
2664 new = stack_putstr(curdir, new);
2666 new = makestrspace(strlen(dir) + 2, new);
2667 lim = (char *)stackblock() + 1;
2671 if (new > lim && *lim == '/')
2676 if (dir[1] == '/' && dir[2] != '/') {
2682 p = strtok(cdcomppath, "/");
2686 if (p[1] == '.' && p[2] == '\0') {
2698 new = stack_putstr(p, new);
2701 p = strtok(NULL, "/");
2706 return stackblock();
2710 * Find out what the current directory is. If we already know the current
2711 * directory, this routine returns immediately.
2716 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2717 return dir ? dir : nullstr;
2721 setpwd(const char *val, int setold)
2725 oldcur = dir = curdir;
2728 setvar("OLDPWD", oldcur, VEXPORT);
2731 if (physdir != nullstr) {
2732 if (physdir != oldcur)
2736 if (oldcur == val || !val) {
2742 dir = ckstrdup(val);
2743 if (oldcur != dir && oldcur != nullstr) {
2748 setvar("PWD", dir, VEXPORT);
2751 static void hashcd(void);
2754 * Actually do the chdir. We also call hashcd to let other routines
2755 * know that the current directory has changed.
2758 docd(const char *dest, int flags)
2760 const char *dir = NULL;
2763 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2766 if (!(flags & CD_PHYSICAL)) {
2767 dir = updatepwd(dest);
2781 static int FAST_FUNC
2782 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2794 dest = bltinlookup("HOME");
2795 else if (LONE_DASH(dest)) {
2796 dest = bltinlookup("OLDPWD");
2818 path = bltinlookup("CDPATH");
2821 p = path_advance(&path, dest);
2822 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2826 if (!docd(p, flags))
2837 ash_msg_and_raise_perror("can't cd to %s", dest);
2840 if (flags & CD_PRINT)
2841 out1fmt("%s\n", curdir);
2845 static int FAST_FUNC
2846 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2849 const char *dir = curdir;
2853 if (physdir == nullstr)
2857 out1fmt("%s\n", dir);
2862 /* ============ ... */
2865 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2867 /* Syntax classes */
2868 #define CWORD 0 /* character is nothing special */
2869 #define CNL 1 /* newline character */
2870 #define CBACK 2 /* a backslash character */
2871 #define CSQUOTE 3 /* single quote */
2872 #define CDQUOTE 4 /* double quote */
2873 #define CENDQUOTE 5 /* a terminating quote */
2874 #define CBQUOTE 6 /* backwards single quote */
2875 #define CVAR 7 /* a dollar sign */
2876 #define CENDVAR 8 /* a '}' character */
2877 #define CLP 9 /* a left paren in arithmetic */
2878 #define CRP 10 /* a right paren in arithmetic */
2879 #define CENDFILE 11 /* end of file */
2880 #define CCTL 12 /* like CWORD, except it must be escaped */
2881 #define CSPCL 13 /* these terminate a word */
2882 #define CIGN 14 /* character should be ignored */
2885 #if ENABLE_ASH_ALIAS
2889 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2891 #if ENABLE_FEATURE_SH_MATH
2892 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2894 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2896 static const uint16_t S_I_T[] ALIGN2 = {
2897 #if ENABLE_ASH_ALIAS
2898 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2900 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2901 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2902 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2903 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2904 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2905 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2906 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2907 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2908 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2909 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2910 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2911 #if !USE_SIT_FUNCTION
2912 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2913 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2914 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2918 /* Constants below must match table above */
2920 #if ENABLE_ASH_ALIAS
2921 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2923 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2924 CNL_CNL_CNL_CNL , /* 2 */
2925 CWORD_CCTL_CCTL_CWORD , /* 3 */
2926 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2927 CVAR_CVAR_CWORD_CVAR , /* 5 */
2928 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2929 CSPCL_CWORD_CWORD_CLP , /* 7 */
2930 CSPCL_CWORD_CWORD_CRP , /* 8 */
2931 CBACK_CBACK_CCTL_CBACK , /* 9 */
2932 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2933 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2934 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2935 CWORD_CWORD_CWORD_CWORD , /* 13 */
2936 CCTL_CCTL_CCTL_CCTL , /* 14 */
2939 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2940 * caller must ensure proper cast on it if c is *char_ptr!
2942 #if USE_SIT_FUNCTION
2945 SIT(int c, int syntax)
2947 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2948 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2950 * This causes '/' to be prepended with CTLESC in dquoted string,
2951 * making "./file"* treated incorrectly because we feed
2952 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2953 * The "homegrown" glob implementation is okay with that,
2954 * but glibc one isn't. With '/' always treated as CWORD,
2957 # if ENABLE_ASH_ALIAS
2958 static const uint8_t syntax_index_table[] ALIGN1 = {
2959 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2960 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2961 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2965 static const uint8_t syntax_index_table[] ALIGN1 = {
2966 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2967 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2968 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2977 # if ENABLE_ASH_ALIAS
2983 /* Cast is purely for paranoia here,
2984 * just in case someone passed signed char to us */
2985 if ((unsigned char)c >= CTL_FIRST
2986 && (unsigned char)c <= CTL_LAST
2990 s = strchrnul(spec_symbls, c);
2993 indx = syntax_index_table[s - spec_symbls];
2995 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2998 #else /* !USE_SIT_FUNCTION */
3000 static const uint8_t syntax_index_table[] ALIGN1 = {
3001 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3002 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3012 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3013 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3035 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3036 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3037 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3038 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3039 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3040 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3041 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3042 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3043 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3044 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3045 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3046 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3047 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3048 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3049 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3050 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3051 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3052 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3053 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3054 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3055 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3056 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3057 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3058 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3059 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3060 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3061 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3062 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3063 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3064 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3065 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3066 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3067 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3068 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3069 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3070 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3071 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3072 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3073 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3074 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3075 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3076 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3077 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3078 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3079 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3080 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3081 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3082 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3083 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3084 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3085 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3086 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3087 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3088 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3089 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3090 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3091 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3092 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3093 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3094 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3095 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3096 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3097 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3098 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3099 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3100 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3101 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3102 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3103 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3104 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3105 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3106 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3109 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3110 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3111 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3112 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3113 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3114 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3115 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3116 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3117 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3118 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3119 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3120 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3121 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3122 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3123 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3124 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3125 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3126 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3127 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3128 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3129 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3130 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3131 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3133 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3134 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3135 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3136 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3137 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3138 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3139 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3140 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3173 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3174 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3175 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3176 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3177 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3178 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3179 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3180 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3181 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3182 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3183 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3184 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3185 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3186 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3187 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3188 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3189 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3190 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3191 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3192 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3193 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3194 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3195 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3259 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3260 # if ENABLE_ASH_ALIAS
3261 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3266 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3267 #else /* debug version, caught one signed char bug */
3268 # define SIT(c, syntax) \
3270 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3271 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3272 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3273 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3274 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3278 #endif /* !USE_SIT_FUNCTION */
3281 /* ============ Alias handling */
3283 #if ENABLE_ASH_ALIAS
3285 #define ALIASINUSE 1
3296 static struct alias **atab; // [ATABSIZE];
3297 #define INIT_G_alias() do { \
3298 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3302 static struct alias **
3303 __lookupalias(const char *name)
3305 unsigned int hashval;
3312 ch = (unsigned char)*p;
3316 ch = (unsigned char)*++p;
3318 app = &atab[hashval % ATABSIZE];
3320 for (; *app; app = &(*app)->next) {
3321 if (strcmp(name, (*app)->name) == 0) {
3329 static struct alias *
3330 lookupalias(const char *name, int check)
3332 struct alias *ap = *__lookupalias(name);
3334 if (check && ap && (ap->flag & ALIASINUSE))
3339 static struct alias *
3340 freealias(struct alias *ap)
3344 if (ap->flag & ALIASINUSE) {
3345 ap->flag |= ALIASDEAD;
3357 setalias(const char *name, const char *val)
3359 struct alias *ap, **app;
3361 app = __lookupalias(name);
3365 if (!(ap->flag & ALIASINUSE)) {
3368 ap->val = ckstrdup(val);
3369 ap->flag &= ~ALIASDEAD;
3372 ap = ckzalloc(sizeof(struct alias));
3373 ap->name = ckstrdup(name);
3374 ap->val = ckstrdup(val);
3375 /*ap->flag = 0; - ckzalloc did it */
3376 /*ap->next = NULL;*/
3383 unalias(const char *name)
3387 app = __lookupalias(name);
3391 *app = freealias(*app);
3402 struct alias *ap, **app;
3406 for (i = 0; i < ATABSIZE; i++) {
3408 for (ap = *app; ap; ap = *app) {
3409 *app = freealias(*app);
3419 printalias(const struct alias *ap)
3421 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3425 * TODO - sort output
3427 static int FAST_FUNC
3428 aliascmd(int argc UNUSED_PARAM, char **argv)
3437 for (i = 0; i < ATABSIZE; i++) {
3438 for (ap = atab[i]; ap; ap = ap->next) {
3444 while ((n = *++argv) != NULL) {
3445 v = strchr(n+1, '=');
3446 if (v == NULL) { /* n+1: funny ksh stuff */
3447 ap = *__lookupalias(n);
3449 fprintf(stderr, "%s: %s not found\n", "alias", n);
3462 static int FAST_FUNC
3463 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3467 while (nextopt("a") != '\0') {
3471 for (i = 0; *argptr; argptr++) {
3472 if (unalias(*argptr)) {
3473 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3481 #endif /* ASH_ALIAS */
3484 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3487 #define FORK_NOJOB 2
3489 /* mode flags for showjob(s) */
3490 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3491 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3492 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3493 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3496 * A job structure contains information about a job. A job is either a
3497 * single process or a set of processes contained in a pipeline. In the
3498 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3502 pid_t ps_pid; /* process id */
3503 int ps_status; /* last process status from wait() */
3504 char *ps_cmd; /* text of command being run */
3508 struct procstat ps0; /* status of process */
3509 struct procstat *ps; /* status or processes when more than one */
3511 int stopstatus; /* status of a stopped job */
3513 unsigned nprocs; /* number of processes */
3515 #define JOBRUNNING 0 /* at least one proc running */
3516 #define JOBSTOPPED 1 /* all procs are stopped */
3517 #define JOBDONE 2 /* all procs are completed */
3521 sigint: 1, /* job was killed by SIGINT */
3522 jobctl: 1, /* job running under job control */
3524 waited: 1, /* true if this entry has been waited for */
3525 used: 1, /* true if this entry is in used */
3526 changed: 1; /* true if status has changed */
3527 struct job *prev_job; /* previous job */
3530 static struct job *makejob(/*union node *,*/ int);
3531 static int forkshell(struct job *, union node *, int);
3532 static int waitforjob(struct job *);
3535 enum { doing_jobctl = 0 };
3536 #define setjobctl(on) do {} while (0)
3538 static smallint doing_jobctl; //references:8
3539 static void setjobctl(int);
3546 ignoresig(int signo)
3548 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3549 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3550 /* No, need to do it */
3551 signal(signo, SIG_IGN);
3553 sigmode[signo - 1] = S_HARD_IGN;
3557 * Only one usage site - in setsignal()
3560 signal_handler(int signo)
3562 if (signo == SIGCHLD) {
3568 gotsig[signo - 1] = 1;
3569 pending_sig = signo;
3571 if (signo == SIGINT && !trap[SIGINT]) {
3572 if (!suppress_int) {
3574 raise_interrupt(); /* does not return */
3581 * Set the signal handler for the specified signal. The routine figures
3582 * out what it should be set to.
3585 setsignal(int signo)
3588 char cur_act, new_act;
3589 struct sigaction act;
3593 if (t != NULL) { /* trap for this sig is set */
3595 if (t[0] == '\0') /* trap is "": ignore this sig */
3599 if (rootshell && new_act == S_DFL) {
3602 if (iflag || minusc || sflag == 0)
3611 * "In all cases, bash ignores SIGQUIT. Non-builtin
3612 * commands run by bash have signal handlers
3613 * set to the values inherited by the shell
3614 * from its parent". */
3630 /* if !rootshell, we reset SIGQUIT to DFL,
3631 * whereas we have to restore it to what shell got on entry.
3632 * This is handled by the fact that if signal was IGNored on entry,
3633 * then cur_act is S_HARD_IGN and we never change its sigaction
3637 if (signo == SIGCHLD)
3640 t = &sigmode[signo - 1];
3643 /* current setting is not yet known */
3644 if (sigaction(signo, NULL, &act)) {
3645 /* pretend it worked; maybe we should give a warning,
3646 * but other shells don't. We don't alter sigmode,
3647 * so we retry every time.
3648 * btw, in Linux it never fails. --vda */
3651 if (act.sa_handler == SIG_IGN) {
3652 cur_act = S_HARD_IGN;
3654 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3656 cur_act = S_IGN; /* don't hard ignore these */
3659 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3660 /* installing SIG_DFL over SIG_DFL is a no-op */
3661 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3666 if (cur_act == S_HARD_IGN || cur_act == new_act)
3671 act.sa_handler = SIG_DFL;
3674 act.sa_handler = signal_handler;
3677 act.sa_handler = SIG_IGN;
3680 /* flags and mask matter only if !DFL and !IGN, but we do it
3681 * for all cases for more deterministic behavior:
3683 act.sa_flags = 0; //TODO: why not SA_RESTART?
3684 sigfillset(&act.sa_mask);
3686 sigaction_set(signo, &act);
3689 /* mode flags for set_curjob */
3690 #define CUR_DELETE 2
3691 #define CUR_RUNNING 1
3692 #define CUR_STOPPED 0
3695 /* pgrp of shell on invocation */
3696 static int initialpgrp; //references:2
3697 static int ttyfd = -1; //5
3700 static struct job *jobtab; //5
3702 static unsigned njobs; //4
3704 static struct job *curjob; //lots
3705 /* number of presumed living untracked jobs */
3706 static int jobless; //4
3709 /* Bash has a feature: it restores termios after a successful wait for
3710 * a foreground job which had at least one stopped or sigkilled member.
3711 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3712 * properly restoring tty state. Should we do this too?
3713 * A reproducer: ^Z an interactive python:
3716 * Python 2.7.12 (...)
3718 * { python leaves tty in -icanon -echo state. We do survive that... }
3719 * [1]+ Stopped python
3720 * { ...however, next program (python #2) does not survive it well: }
3722 * Python 2.7.12 (...)
3723 * >>> Traceback (most recent call last):
3724 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3725 * File "<stdin>", line 1, in <module>
3726 * NameError: name 'qwerty' is not defined
3728 * The implementation below is modeled on bash code and seems to work.
3729 * However, I'm not sure we should do this. For one: what if I'd fg
3730 * the stopped python instead? It'll be confused by "restored" tty state.
3732 static struct termios shell_tty_info;
3736 if (rootshell && ttyfd >= 0)
3737 tcgetattr(ttyfd, &shell_tty_info);
3742 /* if (rootshell) - caller ensures this */
3744 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3747 job_signal_status(struct job *jp)
3751 struct procstat *ps = jp->ps;
3752 for (i = 0; i < jp->nprocs; i++) {
3753 status = ps[i].ps_status;
3754 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3760 restore_tty_if_stopped_or_signaled(struct job *jp)
3762 //TODO: check what happens if we come from waitforjob() in expbackq()
3764 int s = job_signal_status(jp);
3765 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3770 # define get_tty_state() ((void)0)
3771 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3775 set_curjob(struct job *jp, unsigned mode)
3778 struct job **jpp, **curp;
3780 /* first remove from list */
3781 jpp = curp = &curjob;
3786 jpp = &jp1->prev_job;
3788 *jpp = jp1->prev_job;
3790 /* Then re-insert in correct position */
3798 /* job being deleted */
3801 /* newly created job or backgrounded job,
3802 * put after all stopped jobs.
3807 if (!jp1 || jp1->state != JOBSTOPPED)
3810 jpp = &jp1->prev_job;
3816 /* newly stopped job - becomes curjob */
3817 jp->prev_job = *jpp;
3825 jobno(const struct job *jp)
3827 return jp - jobtab + 1;
3832 * Convert a job name to a job structure.
3835 #define getjob(name, getctl) getjob(name)
3838 getjob(const char *name, int getctl)
3842 const char *err_msg = "%s: no such job";
3846 char *(*match)(const char *, const char *);
3861 if (c == '+' || c == '%') {
3863 err_msg = "No current job";
3869 err_msg = "No previous job";
3879 if (num > 0 && num <= njobs) {
3880 jp = jobtab + num - 1;
3895 if (match(jp->ps[0].ps_cmd, p)) {
3899 err_msg = "%s: ambiguous";
3909 err_msg = "job %s not created under job control";
3910 if (getctl && jp->jobctl == 0)
3915 ash_msg_and_raise_error(err_msg, name);
3919 * Mark a job structure as unused.
3922 freejob(struct job *jp)
3924 struct procstat *ps;
3928 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3929 if (ps->ps_cmd != nullstr)
3932 if (jp->ps != &jp->ps0)
3935 set_curjob(jp, CUR_DELETE);
3941 xtcsetpgrp(int fd, pid_t pgrp)
3943 if (tcsetpgrp(fd, pgrp))
3944 ash_msg_and_raise_perror("can't set tty process group");
3948 * Turn job control on and off.
3950 * Note: This code assumes that the third arg to ioctl is a character
3951 * pointer, which is true on Berkeley systems but not System V. Since
3952 * System V doesn't have job control yet, this isn't a problem now.
3954 * Called with interrupts off.
3962 if (on == doing_jobctl || rootshell == 0)
3966 ofd = fd = open(_PATH_TTY, O_RDWR);
3968 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3969 * That sometimes helps to acquire controlling tty.
3970 * Obviously, a workaround for bugs when someone
3971 * failed to provide a controlling tty to bash! :) */
3977 /* fd is a tty at this point */
3978 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
3979 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3982 goto out; /* F_DUPFD failed */
3983 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
3984 close_on_exec_on(fd);
3985 while (1) { /* while we are in the background */
3986 pgrp = tcgetpgrp(fd);
3989 ash_msg("can't access tty; job control turned off");
3993 if (pgrp == getpgrp())
4004 xtcsetpgrp(fd, pgrp);
4006 /* turning job control off */
4009 /* was xtcsetpgrp, but this can make exiting ash
4010 * loop forever if pty is already deleted */
4011 tcsetpgrp(fd, pgrp);
4025 static int FAST_FUNC
4026 killcmd(int argc, char **argv)
4028 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4031 if (argv[i][0] == '%') {
4033 * "kill %N" - job kill
4034 * Converting to pgrp / pid kill
4040 jp = getjob(argv[i], 0);
4042 * In jobs started under job control, we signal
4043 * entire process group by kill -PGRP_ID.
4044 * This happens, f.e., in interactive shell.
4046 * Otherwise, we signal each child via
4047 * kill PID1 PID2 PID3.
4049 * sh -c 'sleep 1|sleep 1 & kill %1'
4050 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4051 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4053 n = jp->nprocs; /* can't be 0 (I hope) */
4056 dst = alloca(n * sizeof(int)*4);
4058 for (j = 0; j < n; j++) {
4059 struct procstat *ps = &jp->ps[j];
4060 /* Skip non-running and not-stopped members
4061 * (i.e. dead members) of the job
4063 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4066 * kill_main has matching code to expect
4067 * leading space. Needed to not confuse
4068 * negative pids with "kill -SIGNAL_NO" syntax
4070 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4074 } while (argv[++i]);
4076 return kill_main(argc, argv);
4080 showpipe(struct job *jp /*, FILE *out*/)
4082 struct procstat *ps;
4083 struct procstat *psend;
4085 psend = jp->ps + jp->nprocs;
4086 for (ps = jp->ps + 1; ps < psend; ps++)
4087 printf(" | %s", ps->ps_cmd);
4088 newline_and_flush(stdout);
4089 flush_stdout_stderr();
4094 restartjob(struct job *jp, int mode)
4096 struct procstat *ps;
4102 if (jp->state == JOBDONE)
4104 jp->state = JOBRUNNING;
4105 pgid = jp->ps[0].ps_pid;
4106 if (mode == FORK_FG) {
4108 xtcsetpgrp(ttyfd, pgid);
4110 killpg(pgid, SIGCONT);
4114 if (WIFSTOPPED(ps->ps_status)) {
4120 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4125 static int FAST_FUNC
4126 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4132 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4136 jp = getjob(*argv, 1);
4137 if (mode == FORK_BG) {
4138 set_curjob(jp, CUR_RUNNING);
4139 printf("[%d] ", jobno(jp));
4141 out1str(jp->ps[0].ps_cmd);
4142 showpipe(jp /*, stdout*/);
4143 retval = restartjob(jp, mode);
4144 } while (*argv && *++argv);
4150 sprint_status48(char *s, int status, int sigonly)
4156 if (!WIFEXITED(status)) {
4158 if (WIFSTOPPED(status))
4159 st = WSTOPSIG(status);
4162 st = WTERMSIG(status);
4164 if (st == SIGINT || st == SIGPIPE)
4167 if (WIFSTOPPED(status))
4172 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4173 col = fmtstr(s, 32, strsignal(st));
4174 if (WCOREDUMP(status)) {
4175 strcpy(s + col, " (core dumped)");
4176 col += sizeof(" (core dumped)")-1;
4178 } else if (!sigonly) {
4179 st = WEXITSTATUS(status);
4180 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4187 wait_block_or_sig(int *status)
4194 /* Poll all children for changes in their state */
4196 /* if job control is active, accept stopped processes too */
4197 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4199 break; /* Error (e.g. EINTR, ECHILD) or pid */
4201 /* Children exist, but none are ready. Sleep until interesting signal */
4204 sigprocmask(SIG_SETMASK, &mask, &mask);
4205 while (!got_sigchld && !pending_sig)
4207 sigprocmask(SIG_SETMASK, &mask, NULL);
4208 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4209 while (!got_sigchld && !pending_sig)
4213 /* If it was SIGCHLD, poll children again */
4214 } while (got_sigchld);
4219 #define DOWAIT_NONBLOCK 0
4220 #define DOWAIT_BLOCK 1
4221 #define DOWAIT_BLOCK_OR_SIG 2
4224 dowait(int block, struct job *job)
4229 struct job *thisjob = NULL;
4231 TRACE(("dowait(0x%x) called\n", block));
4233 /* It's wrong to call waitpid() outside of INT_OFF region:
4234 * signal can arrive just after syscall return and handler can
4235 * longjmp away, losing stop/exit notification processing.
4236 * Thus, for "jobs" builtin, and for waiting for a fg job,
4237 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4239 * However, for "wait" builtin it is wrong to simply call waitpid()
4240 * in INT_OFF region: "wait" needs to wait for any running job
4241 * to change state, but should exit on any trap too.
4242 * In INT_OFF region, a signal just before syscall entry can set
4243 * pending_sig variables, but we can't check them, and we would
4244 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4246 * Because of this, we run inside INT_OFF, but use a special routine
4247 * which combines waitpid() and sigsuspend().
4248 * This is the reason why we need to have a handler for SIGCHLD:
4249 * SIG_DFL handler does not wake sigsuspend().
4252 if (block == DOWAIT_BLOCK_OR_SIG) {
4253 pid = wait_block_or_sig(&status);
4256 if (block == DOWAIT_NONBLOCK)
4257 wait_flags = WNOHANG;
4258 /* if job control is active, accept stopped processes too */
4260 wait_flags |= WUNTRACED;
4261 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4262 pid = waitpid(-1, &status, wait_flags);
4264 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4265 pid, status, errno, strerror(errno)));
4270 for (jp = curjob; jp; jp = jp->prev_job) {
4272 struct procstat *ps;
4273 struct procstat *psend;
4274 if (jp->state == JOBDONE)
4278 psend = ps + jp->nprocs;
4280 if (ps->ps_pid == pid) {
4281 TRACE(("Job %d: changing status of proc %d "
4282 "from 0x%x to 0x%x\n",
4283 jobno(jp), pid, ps->ps_status, status));
4284 ps->ps_status = status;
4287 if (ps->ps_status == -1)
4288 jobstate = JOBRUNNING;
4290 if (jobstate == JOBRUNNING)
4292 if (WIFSTOPPED(ps->ps_status)) {
4293 jp->stopstatus = ps->ps_status;
4294 jobstate = JOBSTOPPED;
4297 } while (++ps < psend);
4301 /* Found the job where one of its processes changed its state.
4302 * Is there at least one live and running process in this job? */
4303 if (jobstate != JOBRUNNING) {
4304 /* No. All live processes in the job are stopped
4305 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4307 thisjob->changed = 1;
4308 if (thisjob->state != jobstate) {
4309 TRACE(("Job %d: changing state from %d to %d\n",
4310 jobno(thisjob), thisjob->state, jobstate));
4311 thisjob->state = jobstate;
4313 if (jobstate == JOBSTOPPED)
4314 set_curjob(thisjob, CUR_STOPPED);
4320 /* The process wasn't found in job list */
4322 if (!WIFSTOPPED(status))
4328 if (thisjob && thisjob == job) {
4332 len = sprint_status48(s, status, 1);
4344 showjob(struct job *jp, int mode)
4346 struct procstat *ps;
4347 struct procstat *psend;
4350 char s[16 + 16 + 48];
4351 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4355 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4356 /* just output process (group) id of pipeline */
4357 fprintf(out, "%d\n", ps->ps_pid);
4361 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4366 else if (curjob && jp == curjob->prev_job)
4369 if (mode & SHOW_PIDS)
4370 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4372 psend = ps + jp->nprocs;
4374 if (jp->state == JOBRUNNING) {
4375 strcpy(s + col, "Running");
4376 col += sizeof("Running") - 1;
4378 int status = psend[-1].ps_status;
4379 if (jp->state == JOBSTOPPED)
4380 status = jp->stopstatus;
4381 col += sprint_status48(s + col, status, 0);
4383 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4385 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4386 * or prints several "PID | <cmdN>" lines,
4387 * depending on SHOW_PIDS bit.
4388 * We do not print status of individual processes
4389 * between PID and <cmdN>. bash does it, but not very well:
4390 * first line shows overall job status, not process status,
4391 * making it impossible to know 1st process status.
4395 /* for each process */
4398 if (mode & SHOW_PIDS)
4399 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4401 fprintf(out, "%s%*c%s%s",
4403 33 - col >= 0 ? 33 - col : 0, ' ',
4404 ps == jp->ps ? "" : "| ",
4407 } while (++ps != psend);
4408 newline_and_flush(out);
4412 if (jp->state == JOBDONE) {
4413 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4419 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4420 * statuses have changed since the last call to showjobs.
4427 TRACE(("showjobs(0x%x) called\n", mode));
4429 /* Handle all finished jobs */
4430 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4433 for (jp = curjob; jp; jp = jp->prev_job) {
4434 if (!(mode & SHOW_CHANGED) || jp->changed) {
4440 static int FAST_FUNC
4441 jobscmd(int argc UNUSED_PARAM, char **argv)
4446 while ((m = nextopt("lp")) != '\0') {
4450 mode |= SHOW_ONLY_PGID;
4456 showjob(getjob(*argv, 0), mode);
4466 /* Called only on finished or stopped jobs (no members are running) */
4468 getstatus(struct job *job)
4472 struct procstat *ps;
4474 /* Fetch last member's status */
4475 ps = job->ps + job->nprocs - 1;
4476 status = ps->ps_status;
4478 /* "set -o pipefail" mode: use last _nonzero_ status */
4479 while (status == 0 && --ps >= job->ps)
4480 status = ps->ps_status;
4483 retval = WEXITSTATUS(status);
4484 if (!WIFEXITED(status)) {
4486 retval = WSTOPSIG(status);
4487 if (!WIFSTOPPED(status))
4490 /* XXX: limits number of signals */
4491 retval = WTERMSIG(status);
4493 if (retval == SIGINT)
4499 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4500 jobno(job), job->nprocs, status, retval));
4504 static int FAST_FUNC
4505 waitcmd(int argc UNUSED_PARAM, char **argv)
4516 /* wait for all jobs */
4520 if (!jp) /* no running procs */
4522 if (jp->state == JOBRUNNING)
4528 * "When bash is waiting for an asynchronous command via
4529 * the wait builtin, the reception of a signal for which a trap
4530 * has been set will cause the wait builtin to return immediately
4531 * with an exit status greater than 128, immediately after which
4532 * the trap is executed."
4534 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4535 /* if child sends us a signal *and immediately exits*,
4536 * dowait() returns pid > 0. Check this case,
4537 * not "if (dowait() < 0)"!
4546 if (**argv != '%') {
4547 pid_t pid = number(*argv);
4552 if (job->ps[job->nprocs - 1].ps_pid == pid)
4554 job = job->prev_job;
4557 job = getjob(*argv, 0);
4559 /* loop until process terminated or stopped */
4560 while (job->state == JOBRUNNING) {
4561 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4566 retval = getstatus(job);
4573 retval = 128 + pending_sig;
4582 struct job *jp, *jq;
4584 len = njobs * sizeof(*jp);
4586 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4588 offset = (char *)jp - (char *)jq;
4590 /* Relocate pointers */
4593 jq = (struct job *)((char *)jq + l);
4597 #define joff(p) ((struct job *)((char *)(p) + l))
4598 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4599 if (joff(jp)->ps == &jq->ps0)
4600 jmove(joff(jp)->ps);
4601 if (joff(jp)->prev_job)
4602 jmove(joff(jp)->prev_job);
4612 jp = (struct job *)((char *)jp + len);
4616 } while (--jq >= jp);
4621 * Return a new job structure.
4622 * Called with interrupts off.
4625 makejob(/*union node *node,*/ int nprocs)
4630 for (i = njobs, jp = jobtab; ; jp++) {
4637 if (jp->state != JOBDONE || !jp->waited)
4646 memset(jp, 0, sizeof(*jp));
4648 /* jp->jobctl is a bitfield.
4649 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4653 jp->prev_job = curjob;
4658 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4660 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4667 * Return a string identifying a command (to be printed by the
4670 static char *cmdnextc;
4673 cmdputs(const char *s)
4675 static const char vstype[VSTYPE + 1][3] = {
4676 "", "}", "-", "+", "?", "=",
4677 "%", "%%", "#", "##"
4678 IF_BASH_SUBSTR(, ":")
4679 IF_BASH_PATTERN_SUBST(, "/", "//")
4682 const char *p, *str;
4686 unsigned char subtype = 0;
4690 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4692 while ((c = *p++) != '\0') {
4700 if ((subtype & VSTYPE) == VSLENGTH)
4706 str = "\"}" + !(quoted & 1);
4713 #if ENABLE_FEATURE_SH_MATH
4728 if ((subtype & VSTYPE) != VSNORMAL)
4730 str = vstype[subtype & VSTYPE];
4731 if (subtype & VSNUL)
4740 /* These can only happen inside quotes */
4746 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4757 while ((c = *str++) != '\0') {
4760 } /* while *p++ not NUL */
4763 USTPUTC('"', nextc);
4769 /* cmdtxt() and cmdlist() call each other */
4770 static void cmdtxt(union node *n);
4773 cmdlist(union node *np, int sep)
4775 for (; np; np = np->narg.next) {
4779 if (sep && np->narg.next)
4785 cmdtxt(union node *n)
4788 struct nodelist *lp;
4799 lp = n->npipe.cmdlist;
4817 cmdtxt(n->nbinary.ch1);
4833 cmdtxt(n->nif.test);
4835 if (n->nif.elsepart) {
4836 cmdtxt(n->nif.ifpart);
4838 n = n->nif.elsepart;
4856 cmdtxt(n->nbinary.ch1);
4866 cmdputs(n->nfor.var);
4868 cmdlist(n->nfor.args, 1);
4873 cmdputs(n->ndefun.text);
4877 cmdlist(n->ncmd.args, 1);
4878 cmdlist(n->ncmd.redirect, 0);
4891 cmdputs(n->ncase.expr->narg.text);
4893 for (np = n->ncase.cases; np; np = np->nclist.next) {
4894 cmdtxt(np->nclist.pattern);
4896 cmdtxt(np->nclist.body);
4910 #if BASH_REDIR_OUTPUT
4925 cmdputs(utoa(n->nfile.fd));
4927 if (n->type == NTOFD || n->type == NFROMFD) {
4928 if (n->ndup.dupfd >= 0)
4929 cmdputs(utoa(n->ndup.dupfd));
4940 commandtext(union node *n)
4944 STARTSTACKSTR(cmdnextc);
4946 name = stackblock();
4947 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4948 return ckstrdup(name);
4953 * Fork off a subshell. If we are doing job control, give the subshell its
4954 * own process group. Jp is a job structure that the job is to be added to.
4955 * N is the command that will be evaluated by the child. Both jp and n may
4956 * be NULL. The mode parameter can be one of the following:
4957 * FORK_FG - Fork off a foreground process.
4958 * FORK_BG - Fork off a background process.
4959 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4960 * process group even if job control is on.
4962 * When job control is turned off, background processes have their standard
4963 * input redirected to /dev/null (except for the second and later processes
4966 * Called with interrupts off.
4969 * Clear traps on a fork.
4977 for (tp = trap; tp < &trap[NSIG]; tp++) {
4978 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4979 if (trap_ptr == trap)
4981 /* else: it "belongs" to trap_ptr vector, don't free */
4983 if ((tp - trap) != 0)
4984 setsignal(tp - trap);
4991 /* Lives far away from here, needed for forkchild */
4992 static void closescript(void);
4994 /* Called after fork(), in child */
4995 /* jp and n are NULL when called by openhere() for heredoc support */
4996 static NOINLINE void
4997 forkchild(struct job *jp, union node *n, int mode)
5001 TRACE(("Child shell %d\n", getpid()));
5005 /* man bash: "Non-builtin commands run by bash have signal handlers
5006 * set to the values inherited by the shell from its parent".
5007 * Do we do it correctly? */
5011 if (mode == FORK_NOJOB /* is it `xxx` ? */
5012 && n && n->type == NCMD /* is it single cmd? */
5013 /* && n->ncmd.args->type == NARG - always true? */
5014 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5015 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5016 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5018 TRACE(("Trap hack\n"));
5019 /* Awful hack for `trap` or $(trap).
5021 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5022 * contains an example where "trap" is executed in a subshell:
5024 * save_traps=$(trap)
5026 * eval "$save_traps"
5028 * Standard does not say that "trap" in subshell shall print
5029 * parent shell's traps. It only says that its output
5030 * must have suitable form, but then, in the above example
5031 * (which is not supposed to be normative), it implies that.
5033 * bash (and probably other shell) does implement it
5034 * (traps are reset to defaults, but "trap" still shows them),
5035 * but as a result, "trap" logic is hopelessly messed up:
5038 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5039 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5040 * # true | trap <--- trap is in subshell - no output (ditto)
5041 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5042 * trap -- 'echo Ho' SIGWINCH
5043 * # echo `(trap)` <--- in subshell in subshell - output
5044 * trap -- 'echo Ho' SIGWINCH
5045 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5046 * trap -- 'echo Ho' SIGWINCH
5048 * The rules when to forget and when to not forget traps
5049 * get really complex and nonsensical.
5051 * Our solution: ONLY bare $(trap) or `trap` is special.
5053 /* Save trap handler strings for trap builtin to print */
5054 trap_ptr = xmemdup(trap, sizeof(trap));
5055 /* Fall through into clearing traps */
5059 /* do job control only in root shell */
5061 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5064 if (jp->nprocs == 0)
5067 pgrp = jp->ps[0].ps_pid;
5068 /* this can fail because we are doing it in the parent also */
5070 if (mode == FORK_FG)
5071 xtcsetpgrp(ttyfd, pgrp);
5076 if (mode == FORK_BG) {
5077 /* man bash: "When job control is not in effect,
5078 * asynchronous commands ignore SIGINT and SIGQUIT" */
5081 if (jp->nprocs == 0) {
5083 if (open(bb_dev_null, O_RDONLY) != 0)
5084 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5088 if (iflag) { /* why if iflag only? */
5093 * "In all cases, bash ignores SIGQUIT. Non-builtin
5094 * commands run by bash have signal handlers
5095 * set to the values inherited by the shell
5097 * Take care of the second rule: */
5101 if (n && n->type == NCMD
5102 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5104 TRACE(("Job hack\n"));
5105 /* "jobs": we do not want to clear job list for it,
5106 * instead we remove only _its_ own_ job from job list.
5107 * This makes "jobs .... | cat" more useful.
5113 for (jp = curjob; jp; jp = jp->prev_job)
5118 /* Called after fork(), in parent */
5120 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5123 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5125 TRACE(("In parent shell: child = %d\n", pid));
5127 /* jp is NULL when called by openhere() for heredoc support */
5128 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5134 if (mode != FORK_NOJOB && jp->jobctl) {
5137 if (jp->nprocs == 0)
5140 pgrp = jp->ps[0].ps_pid;
5141 /* This can fail because we are doing it in the child also */
5145 if (mode == FORK_BG) {
5146 backgndpid = pid; /* set $! */
5147 set_curjob(jp, CUR_RUNNING);
5150 struct procstat *ps = &jp->ps[jp->nprocs++];
5153 ps->ps_cmd = nullstr;
5155 if (doing_jobctl && n)
5156 ps->ps_cmd = commandtext(n);
5161 /* jp and n are NULL when called by openhere() for heredoc support */
5163 forkshell(struct job *jp, union node *n, int mode)
5167 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5170 TRACE(("Fork failed, errno=%d", errno));
5173 ash_msg_and_raise_perror("can't fork");
5176 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5177 forkchild(jp, n, mode);
5179 forkparent(jp, n, mode, pid);
5185 * Wait for job to finish.
5187 * Under job control we have the problem that while a child process
5188 * is running interrupts generated by the user are sent to the child
5189 * but not to the shell. This means that an infinite loop started by
5190 * an interactive user may be hard to kill. With job control turned off,
5191 * an interactive user may place an interactive program inside a loop.
5192 * If the interactive program catches interrupts, the user doesn't want
5193 * these interrupts to also abort the loop. The approach we take here
5194 * is to have the shell ignore interrupt signals while waiting for a
5195 * foreground process to terminate, and then send itself an interrupt
5196 * signal if the child process was terminated by an interrupt signal.
5197 * Unfortunately, some programs want to do a bit of cleanup and then
5198 * exit on interrupt; unless these processes terminate themselves by
5199 * sending a signal to themselves (instead of calling exit) they will
5200 * confuse this approach.
5202 * Called with interrupts off.
5205 waitforjob(struct job *jp)
5209 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5212 while (jp->state == JOBRUNNING) {
5213 /* In non-interactive shells, we _can_ get
5214 * a keyboard signal here and be EINTRed,
5215 * but we just loop back, waiting for command to complete.
5218 * "If bash is waiting for a command to complete and receives
5219 * a signal for which a trap has been set, the trap
5220 * will not be executed until the command completes."
5222 * Reality is that even if trap is not set, bash
5223 * will not act on the signal until command completes.
5224 * Try this. sleep5intoff.c:
5225 * #include <signal.h>
5226 * #include <unistd.h>
5229 * sigemptyset(&set);
5230 * sigaddset(&set, SIGINT);
5231 * sigaddset(&set, SIGQUIT);
5232 * sigprocmask(SIG_BLOCK, &set, NULL);
5236 * $ bash -c './sleep5intoff; echo hi'
5237 * ^C^C^C^C <--- pressing ^C once a second
5239 * $ bash -c './sleep5intoff; echo hi'
5240 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5243 dowait(DOWAIT_BLOCK, jp);
5250 xtcsetpgrp(ttyfd, rootpid);
5251 restore_tty_if_stopped_or_signaled(jp);
5254 * This is truly gross.
5255 * If we're doing job control, then we did a TIOCSPGRP which
5256 * caused us (the shell) to no longer be in the controlling
5257 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5258 * intuit from the subprocess exit status whether a SIGINT
5259 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5261 if (jp->sigint) /* TODO: do the same with all signals */
5262 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5264 if (jp->state == JOBDONE)
5271 * return 1 if there are stopped jobs, otherwise 0
5283 if (jp && jp->state == JOBSTOPPED) {
5284 out2str("You have stopped jobs.\n");
5294 * Code for dealing with input/output redirection.
5299 #define EMPTY -2 /* marks an unused slot in redirtab */
5300 #define CLOSED -1 /* marks a slot of previously-closed fd */
5303 * Handle here documents. Normally we fork off a process to write the
5304 * data to a pipe. If the document is short, we can stuff the data in
5305 * the pipe without forking.
5307 /* openhere needs this forward reference */
5308 static void expandhere(union node *arg, int fd);
5310 openhere(union node *redir)
5316 ash_msg_and_raise_perror("can't create pipe");
5317 if (redir->type == NHERE) {
5318 len = strlen(redir->nhere.doc->narg.text);
5319 if (len <= PIPE_BUF) {
5320 full_write(pip[1], redir->nhere.doc->narg.text, len);
5324 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5327 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5328 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5329 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5330 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5331 signal(SIGPIPE, SIG_DFL);
5332 if (redir->type == NHERE)
5333 full_write(pip[1], redir->nhere.doc->narg.text, len);
5335 expandhere(redir->nhere.doc, pip[1]);
5336 _exit(EXIT_SUCCESS);
5344 openredirect(union node *redir)
5350 switch (redir->nfile.type) {
5351 /* Can't happen, our single caller does this itself */
5357 return openhere(redir);
5360 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5361 * allocated space. Do it only when we know it is safe.
5363 fname = redir->nfile.expfname;
5365 switch (redir->nfile.type) {
5371 f = open(fname, O_RDONLY);
5376 f = open(fname, O_RDWR|O_CREAT, 0666);
5381 #if BASH_REDIR_OUTPUT
5384 /* Take care of noclobber mode. */
5386 if (stat(fname, &sb) < 0) {
5387 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5390 } else if (!S_ISREG(sb.st_mode)) {
5391 f = open(fname, O_WRONLY, 0666);
5394 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5407 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5412 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5420 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5422 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5426 * Copy a file descriptor to be >= 10. Throws exception on error.
5434 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5435 err = newfd < 0 ? errno : 0;
5438 ash_msg_and_raise_perror("%d", from);
5440 if (F_DUPFD_CLOEXEC == F_DUPFD)
5441 close_on_exec_on(newfd);
5447 dup2_or_raise(int from, int to)
5451 newfd = (from != to) ? dup2(from, to) : to;
5453 /* Happens when source fd is not open: try "echo >&99" */
5454 ash_msg_and_raise_perror("%d", from);
5459 dup_CLOEXEC(int fd, int avoid_fd)
5463 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5465 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5466 close_on_exec_on(newfd);
5467 } else { /* newfd < 0 */
5476 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5480 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5486 /* fd was not open? */
5489 ash_msg_and_raise_perror("%d", newfd);
5491 if (F_DUPFD_CLOEXEC == F_DUPFD)
5492 close_on_exec_on(newfd);
5497 /* Struct def and variable are moved down to the first usage site */
5503 struct redirtab *next;
5505 struct squirrel two_fd[];
5507 #define redirlist (G_var.redirlist)
5510 add_squirrel_closed(struct redirtab *sq, int fd)
5517 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5518 /* If we collide with an already moved fd... */
5519 if (fd == sq->two_fd[i].orig_fd) {
5521 * "echo 3>FILE 3>&- 3>FILE"
5522 * "echo 3>&- 3>FILE"
5523 * No need for last redirect to insert
5524 * another "need to close 3" indicator.
5526 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5530 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5531 sq->two_fd[i].orig_fd = fd;
5532 sq->two_fd[i].moved_to = CLOSED;
5536 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5540 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5545 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5546 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5547 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5548 return 1; /* "we closed fd" */
5551 /* Are we called from redirect(0)? E.g. redirect
5552 * in a forked child. No need to save fds,
5553 * we aren't going to use them anymore, ok to trash.
5558 /* If this one of script's fds? */
5560 struct parsefile *pf = g_parsefile;
5562 /* We skip fd == 0 case because of the following:
5563 * $ ash # running ash interactively
5565 * and in script.sh: "exec 9>&0".
5566 * Even though top-level pf_fd _is_ 0,
5567 * it's still ok to use it: "read" builtin uses it,
5568 * why should we cripple "exec" builtin?
5570 if (fd == pf->pf_fd) {
5571 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5572 return 1; /* "we closed fd" */
5578 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5580 /* First: do we collide with some already moved fds? */
5581 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5582 /* If we collide with an already moved fd... */
5583 if (fd == sq->two_fd[i].moved_to) {
5584 new_fd = dup_CLOEXEC(fd, avoid_fd);
5585 sq->two_fd[i].moved_to = new_fd;
5586 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5587 if (new_fd < 0) /* what? */
5589 return 0; /* "we did not close fd" */
5591 if (fd == sq->two_fd[i].orig_fd) {
5592 /* Example: echo Hello >/dev/null 1>&2 */
5593 TRACE(("redirect_fd %d: already moved\n", fd));
5594 return 0; /* "we did not close fd" */
5598 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5599 new_fd = dup_CLOEXEC(fd, avoid_fd);
5600 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5604 /* new_fd = CLOSED; - already is -1 */
5606 sq->two_fd[i].moved_to = new_fd;
5607 sq->two_fd[i].orig_fd = fd;
5609 /* if we move stderr, let "set -x" code know */
5610 if (fd == preverrout_fd)
5611 preverrout_fd = new_fd;
5613 return 0; /* "we did not close fd" */
5617 internally_opened_fd(int fd, struct redirtab *sq)
5624 /* If this one of script's fds? */
5626 struct parsefile *pf = g_parsefile;
5628 if (fd == pf->pf_fd)
5634 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5635 if (fd == sq->two_fd[i].moved_to)
5642 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5643 * old file descriptors are stashed away so that the redirection can be
5644 * undone by calling popredir.
5646 /* flags passed to redirect */
5647 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5649 redirect(union node *redir, int flags)
5651 struct redirtab *sv;
5658 if (flags & REDIR_PUSH)
5666 fd = redir->nfile.fd;
5667 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5668 //bb_error_msg("doing %d > %d", fd, newfd);
5669 newfd = redir->ndup.dupfd;
5672 newfd = openredirect(redir); /* always >= 0 */
5674 /* open() gave us precisely the fd we wanted.
5675 * This means that this fd was not busy
5676 * (not opened to anywhere).
5677 * Remember to close it on restore:
5679 add_squirrel_closed(sv, fd);
5688 /* if "N>FILE": move newfd to fd */
5689 /* if "N>&M": dup newfd to fd */
5690 /* if "N>&-": close fd (newfd is -1) */
5692 IF_BASH_REDIR_OUTPUT(redirect_more:)
5694 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5696 /* "N>&-" means "close me" */
5698 /* ^^^ optimization: saving may already
5699 * have closed it. If not... */
5703 /* if newfd is a script fd or saved fd, simulate EBADF */
5704 if (internally_opened_fd(newfd, sv)) {
5706 ash_msg_and_raise_perror("%d", newfd);
5708 dup2_or_raise(newfd, fd);
5709 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5711 #if BASH_REDIR_OUTPUT
5712 if (redir->nfile.type == NTO2 && fd == 1) {
5713 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5721 } while ((redir = redir->nfile.next) != NULL);
5724 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5725 #define REDIR_SAVEFD2 0
5726 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5727 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5728 // not only for calls with flags containing REDIR_SAVEFD2.
5729 // We do this unconditionally (see save_fd_on_redirect()).
5730 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5731 // preverrout_fd = copied_fd2;
5735 redirectsafe(union node *redir, int flags)
5738 volatile int saveint;
5739 struct jmploc *volatile savehandler = exception_handler;
5740 struct jmploc jmploc;
5743 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5744 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5746 exception_handler = &jmploc;
5747 redirect(redir, flags);
5749 exception_handler = savehandler;
5750 if (err && exception_type != EXERROR)
5751 longjmp(exception_handler->loc, 1);
5752 RESTORE_INT(saveint);
5756 static struct redirtab*
5757 pushredir(union node *redir)
5759 struct redirtab *sv;
5768 #if BASH_REDIR_OUTPUT
5769 if (redir->nfile.type == NTO2)
5772 redir = redir->nfile.next;
5775 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5778 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5779 sv->next = redirlist;
5785 * Undo the effects of the last redirection.
5790 struct redirtab *rp;
5793 if (redirlist == NULL)
5797 for (i = 0; i < rp->pair_count; i++) {
5798 int fd = rp->two_fd[i].orig_fd;
5799 int copy = rp->two_fd[i].moved_to;
5800 if (copy == CLOSED) {
5805 if (copy != EMPTY) {
5808 dup2_or_raise(copy, fd);
5813 redirlist = rp->next;
5819 unwindredir(struct redirtab *stop)
5821 while (redirlist != stop)
5822 popredir(/*drop:*/ 0);
5826 /* ============ Routines to expand arguments to commands
5828 * We have to deal with backquotes, shell variables, and file metacharacters.
5831 #if ENABLE_FEATURE_SH_MATH
5833 ash_arith(const char *s)
5835 arith_state_t math_state;
5838 math_state.lookupvar = lookupvar;
5839 math_state.setvar = setvar0;
5840 //math_state.endofname = endofname;
5843 result = arith(&math_state, s);
5844 if (math_state.errmsg)
5845 ash_msg_and_raise_error(math_state.errmsg);
5852 # if ENABLE_FEATURE_SH_MATH
5853 static int substr_atoi(const char *s)
5855 arith_t t = ash_arith(s);
5856 if (sizeof(t) > sizeof(int)) {
5857 /* clamp very large or very large negative nums for ${v:N:M}:
5858 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5868 # define substr_atoi(s) number(s)
5875 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5876 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5877 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5878 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5879 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5880 * POSIX says for this case:
5881 * Pathname expansion shall not be performed on the word by a
5882 * non-interactive shell; an interactive shell may perform it, but shall
5883 * do so only when the expansion would result in one word.
5884 * Currently, our code complies to the above rule by never globbing
5885 * redirection filenames.
5886 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5887 * (this means that on a typical Linux distro, bash almost always
5888 * performs globbing, and thus diverges from what we do).
5890 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5891 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5892 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5893 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5894 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5898 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5899 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5900 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5901 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5903 /* Add CTLESC when necessary. */
5904 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5905 /* Do not skip NUL characters. */
5906 #define QUOTES_KEEPNUL EXP_TILDE
5909 * Structure specifying which parts of the string should be searched
5910 * for IFS characters.
5913 struct ifsregion *next; /* next region in list */
5914 int begoff; /* offset of start of region */
5915 int endoff; /* offset of end of region */
5916 int nulonly; /* search for nul bytes only */
5920 struct strlist *list;
5921 struct strlist **lastp;
5924 /* output of current string */
5925 static char *expdest;
5926 /* list of back quote expressions */
5927 static struct nodelist *argbackq;
5928 /* first struct in list of ifs regions */
5929 static struct ifsregion ifsfirst;
5930 /* last struct in list */
5931 static struct ifsregion *ifslastp;
5932 /* holds expanded arg list */
5933 static struct arglist exparg;
5937 * cvtnum() is used even if math support is off (to prepare $? values and such).
5944 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5945 len = sizeof(arith_t) * 3;
5946 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5947 if (sizeof(arith_t) < 4) len += 2;
5949 expdest = makestrspace(len, expdest);
5950 len = fmtstr(expdest, len, ARITH_FMT, num);
5951 STADJUST(len, expdest);
5956 * Break the argument string into pieces based upon IFS and add the
5957 * strings to the argument list. The regions of the string to be
5958 * searched for IFS characters have been stored by recordregion.
5961 ifsbreakup(char *string, struct arglist *arglist)
5963 struct ifsregion *ifsp;
5968 const char *ifs, *realifs;
5973 if (ifslastp != NULL) {
5976 realifs = ifsset() ? ifsval() : defifs;
5979 p = string + ifsp->begoff;
5980 nulonly = ifsp->nulonly;
5981 ifs = nulonly ? nullstr : realifs;
5983 while (p < string + ifsp->endoff) {
5985 if ((unsigned char)*p == CTLESC)
5987 if (!strchr(ifs, *p)) {
5992 ifsspc = (strchr(defifs, *p) != NULL);
5993 /* Ignore IFS whitespace at start */
5994 if (q == start && ifsspc) {
6000 sp = stzalloc(sizeof(*sp));
6002 *arglist->lastp = sp;
6003 arglist->lastp = &sp->next;
6007 if (p >= string + ifsp->endoff) {
6011 if ((unsigned char)*p == CTLESC)
6013 if (strchr(ifs, *p) == NULL) {
6017 if (strchr(defifs, *p) == NULL) {
6032 } while (ifsp != NULL);
6041 sp = stzalloc(sizeof(*sp));
6043 *arglist->lastp = sp;
6044 arglist->lastp = &sp->next;
6050 struct ifsregion *p = ifsfirst.next;
6057 struct ifsregion *ifsp;
6062 ifsfirst.next = NULL;
6069 esclen(const char *start, const char *p)
6073 while (p > start && (unsigned char)*--p == CTLESC) {
6080 * Remove any CTLESC characters from a string.
6082 #if !BASH_PATTERN_SUBST
6083 #define rmescapes(str, flag, slash_position) \
6084 rmescapes(str, flag)
6087 rmescapes(char *str, int flag, int *slash_position)
6089 static const char qchars[] ALIGN1 = {
6090 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6094 unsigned protect_against_glob;
6097 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6103 if (flag & RMESCAPE_ALLOC) {
6104 size_t len = p - str;
6105 size_t fulllen = len + strlen(p) + 1;
6107 if (flag & RMESCAPE_GROW) {
6108 int strloc = str - (char *)stackblock();
6109 r = makestrspace(fulllen, expdest);
6110 /* p and str may be invalidated by makestrspace */
6111 str = (char *)stackblock() + strloc;
6113 } else if (flag & RMESCAPE_HEAP) {
6114 r = ckmalloc(fulllen);
6116 r = stalloc(fulllen);
6120 q = (char *)mempcpy(q, str, len);
6125 globbing = flag & RMESCAPE_GLOB;
6126 protect_against_glob = globbing;
6128 if ((unsigned char)*p == CTLQUOTEMARK) {
6129 // Note: both inquotes and protect_against_glob only affect whether
6130 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6131 inquotes = ~inquotes;
6133 protect_against_glob = globbing;
6136 if ((unsigned char)*p == CTLESC) {
6140 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6142 if (protect_against_glob) {
6144 * We used to trust glob() and fnmatch() to eat
6145 * superfluous escapes (\z where z has no
6146 * special meaning anyway). But this causes
6147 * bugs such as string of one greek letter rho
6148 * (unicode-encoded as two bytes "cf,81")
6149 * getting encoded as "cf,CTLESC,81"
6150 * and here, converted to "cf,\,81" -
6151 * which does not go well with some flavors
6152 * of fnmatch() in unicode locales
6153 * (for example, glibc <= 2.22).
6155 * Lets add "\" only on the chars which need it.
6156 * Testcases for less obvious chars are shown.
6161 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6162 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6163 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6164 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6165 /* Some libc support [^negate], that's why "^" also needs love */
6166 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6171 } else if (*p == '\\' && !inquotes) {
6172 /* naked back slash */
6173 protect_against_glob = 0;
6176 #if BASH_PATTERN_SUBST
6177 else if (slash_position && p == str + *slash_position) {
6178 /* stop handling globbing */
6180 *slash_position = q - r;
6181 slash_position = NULL;
6184 protect_against_glob = globbing;
6189 if (flag & RMESCAPE_GROW) {
6191 STADJUST(q - r + 1, expdest);
6195 #define pmatch(a, b) !fnmatch((a), (b), 0)
6198 * Prepare a pattern for a expmeta (internal glob(3)) call.
6200 * Returns an stalloced string.
6203 preglob(const char *pattern, int flag)
6205 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6209 * Put a string on the stack.
6212 memtodest(const char *p, size_t len, int syntax, int quotes)
6219 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6222 unsigned char c = *p++;
6224 if (quotes & QUOTES_ESC) {
6225 int n = SIT(c, syntax);
6227 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6234 } else if (!(quotes & QUOTES_KEEPNUL))
6243 strtodest(const char *p, int syntax, int quotes)
6245 size_t len = strlen(p);
6246 memtodest(p, len, syntax, quotes);
6251 * Record the fact that we have to scan this region of the
6252 * string for IFS characters.
6255 recordregion(int start, int end, int nulonly)
6257 struct ifsregion *ifsp;
6259 if (ifslastp == NULL) {
6263 ifsp = ckzalloc(sizeof(*ifsp));
6264 /*ifsp->next = NULL; - ckzalloc did it */
6265 ifslastp->next = ifsp;
6269 ifslastp->begoff = start;
6270 ifslastp->endoff = end;
6271 ifslastp->nulonly = nulonly;
6275 removerecordregions(int endoff)
6277 if (ifslastp == NULL)
6280 if (ifsfirst.endoff > endoff) {
6281 while (ifsfirst.next) {
6282 struct ifsregion *ifsp;
6284 ifsp = ifsfirst.next->next;
6285 free(ifsfirst.next);
6286 ifsfirst.next = ifsp;
6289 if (ifsfirst.begoff > endoff) {
6292 ifslastp = &ifsfirst;
6293 ifsfirst.endoff = endoff;
6298 ifslastp = &ifsfirst;
6299 while (ifslastp->next && ifslastp->next->begoff < endoff)
6300 ifslastp = ifslastp->next;
6301 while (ifslastp->next) {
6302 struct ifsregion *ifsp;
6304 ifsp = ifslastp->next->next;
6305 free(ifslastp->next);
6306 ifslastp->next = ifsp;
6309 if (ifslastp->endoff > endoff)
6310 ifslastp->endoff = endoff;
6314 exptilde(char *startp, char *p, int flags)
6320 int quotes = flags & QUOTES_ESC;
6324 while ((c = *++p) != '\0') {
6331 if (flags & EXP_VARTILDE)
6341 if (*name == '\0') {
6342 home = lookupvar("HOME");
6344 pw = getpwnam(name);
6349 if (!home || !*home)
6352 strtodest(home, SQSYNTAX, quotes);
6360 * Execute a command inside back quotes. If it's a builtin command, we
6361 * want to save its output in a block obtained from malloc. Otherwise
6362 * we fork off a subprocess and get the output of the command via a pipe.
6363 * Should be called with interrupts off.
6365 struct backcmd { /* result of evalbackcmd */
6366 int fd; /* file descriptor to read from */
6367 int nleft; /* number of chars in buffer */
6368 char *buf; /* buffer */
6369 struct job *jp; /* job structure for command */
6372 /* These forward decls are needed to use "eval" code for backticks handling: */
6373 /* flags in argument to evaltree */
6374 #define EV_EXIT 01 /* exit after evaluating tree */
6375 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6376 static int evaltree(union node *, int);
6378 /* An evaltree() which is known to never return.
6379 * Used to use an alias:
6380 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6381 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6383 static ALWAYS_INLINE NORETURN void
6384 evaltreenr(union node *n, int flags)
6387 bb_unreachable(abort());
6391 static void FAST_FUNC
6392 evalbackcmd(union node *n, struct backcmd *result)
6406 ash_msg_and_raise_perror("can't create pipe");
6407 jp = makejob(/*n,*/ 1);
6408 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6414 dup2_or_raise(pip[1], 1);
6417 /* TODO: eflag clearing makes the following not abort:
6418 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6419 * which is what bash does (unless it is in POSIX mode).
6420 * dash deleted "eflag = 0" line in the commit
6421 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6422 * [EVAL] Don't clear eflag in evalbackcmd
6423 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6427 evaltreenr(n, EV_EXIT);
6432 result->fd = pip[0];
6436 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6437 result->fd, result->buf, result->nleft, result->jp));
6441 * Expand stuff in backwards quotes.
6444 expbackq(union node *cmd, int flag)
6452 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6453 struct stackmark smark;
6456 startloc = expdest - (char *)stackblock();
6457 pushstackmark(&smark, startloc);
6458 evalbackcmd(cmd, &in);
6459 popstackmark(&smark);
6466 memtodest(p, i, syntax, flag & QUOTES_ESC);
6470 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6471 TRACE(("expbackq: read returns %d\n", i));
6480 back_exitstatus = waitforjob(in.jp);
6484 /* Eat all trailing newlines */
6486 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6490 if (!(flag & EXP_QUOTED))
6491 recordregion(startloc, dest - (char *)stackblock(), 0);
6492 TRACE(("evalbackq: size:%d:'%.*s'\n",
6493 (int)((dest - (char *)stackblock()) - startloc),
6494 (int)((dest - (char *)stackblock()) - startloc),
6495 stackblock() + startloc));
6498 #if ENABLE_FEATURE_SH_MATH
6500 * Expand arithmetic expression. Backup to start of expression,
6501 * evaluate, place result in (backed up) result, adjust string position.
6513 * This routine is slightly over-complicated for
6514 * efficiency. Next we scan backwards looking for the
6515 * start of arithmetic.
6517 start = stackblock();
6524 while ((unsigned char)*p != CTLARI) {
6528 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6533 esc = esclen(start, p);
6543 removerecordregions(begoff);
6547 if (flag & QUOTES_ESC)
6548 rmescapes(p + 1, 0, NULL);
6550 len = cvtnum(ash_arith(p + 1));
6552 if (!(flag & EXP_QUOTED))
6553 recordregion(begoff, begoff + len, 0);
6557 /* argstr needs it */
6558 static char *evalvar(char *p, int flags);
6561 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6562 * characters to allow for further processing. Otherwise treat
6563 * $@ like $* since no splitting will be performed.
6566 argstr(char *p, int flags)
6568 static const char spclchars[] ALIGN1 = {
6576 #if ENABLE_FEATURE_SH_MATH
6581 const char *reject = spclchars;
6582 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6587 if (!(flags & EXP_VARTILDE)) {
6589 } else if (flags & EXP_VARTILDE2) {
6594 if (flags & EXP_TILDE) {
6597 flags &= ~EXP_TILDE;
6601 p = exptilde(p, q, flags);
6604 startloc = expdest - (char *)stackblock();
6608 length += strcspn(p + length, reject);
6612 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6614 /* c == '=' || c == ':' || c == CTLENDARI */
6620 expdest = stack_nputstr(p, length, expdest);
6621 newloc = expdest - (char *)stackblock();
6622 if (breakall && !inquotes && newloc > startloc) {
6623 recordregion(startloc, newloc, 0);
6634 if (flags & EXP_VARTILDE2) {
6638 flags |= EXP_VARTILDE2;
6643 * sort of a hack - expand tildes in variable
6644 * assignments (after the first '=' and after ':'s).
6653 case CTLENDVAR: /* ??? */
6656 inquotes ^= EXP_QUOTED;
6657 /* "$@" syntax adherence hack */
6658 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6659 p = evalvar(p + 1, flags | inquotes) + 1;
6663 if (flags & QUOTES_ESC) {
6674 * Quoted parameter expansion pattern: remove quote
6675 * unless inside inner quotes or we have a literal
6678 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6679 EXP_QPAT && *p != '\\')
6684 TRACE(("argstr: evalvar('%s')\n", p));
6685 p = evalvar(p, flags | inquotes);
6686 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6689 expbackq(argbackq->n, flags | inquotes);
6690 argbackq = argbackq->next;
6692 #if ENABLE_FEATURE_SH_MATH
6695 expari(flags | inquotes);
6704 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6705 char *pattern, int quotes, int zero)
6714 const char *s = loc2;
6721 match = pmatch(pattern, s);
6726 if (quotes && (unsigned char)*loc == CTLESC)
6735 scanright(char *startp, char *rmesc, char *rmescend,
6736 char *pattern, int quotes, int match_at_start)
6738 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6739 int try2optimize = match_at_start;
6745 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6746 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6747 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6749 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6750 * and on each iteration they go back two/one char until they reach the beginning.
6751 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6753 /* TODO: document in what other circumstances we are called. */
6755 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6758 const char *s = loc2;
6759 if (match_at_start) {
6763 match = pmatch(pattern, s);
6764 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6768 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6770 /* Maybe we can optimize this:
6771 * if pattern ends with unescaped *, we can avoid checking
6772 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6773 * it won't match truncated "raw_value_of_" strings too.
6775 unsigned plen = strlen(pattern);
6776 /* Does it end with "*"? */
6777 if (plen != 0 && pattern[--plen] == '*') {
6778 /* "xxxx*" is not escaped */
6779 /* "xxx\*" is escaped */
6780 /* "xx\\*" is not escaped */
6781 /* "x\\\*" is escaped */
6783 while (plen != 0 && pattern[--plen] == '\\')
6786 break; /* ends with unescaped "*" */
6794 esc = esclen(startp, loc);
6805 static void varunset(const char *, const char *, const char *, int) NORETURN;
6807 varunset(const char *end, const char *var, const char *umsg, int varflags)
6813 msg = "parameter not set";
6815 if ((unsigned char)*end == CTLENDVAR) {
6816 if (varflags & VSNUL)
6822 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6826 subevalvar(char *p, char *varname, int strloc, int subtype,
6827 int startloc, int varflags, int flag)
6829 struct nodelist *saveargbackq = argbackq;
6830 int quotes = flag & QUOTES_ESC;
6833 char *rmesc, *rmescend;
6835 int amount, resetloc;
6837 IF_BASH_PATTERN_SUBST(int workloc;)
6838 IF_BASH_PATTERN_SUBST(int slash_pos;)
6839 IF_BASH_PATTERN_SUBST(char *repl;)
6841 char *(*scan)(char*, char*, char*, char*, int, int);
6843 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6844 // p, varname, strloc, subtype, startloc, varflags, quotes);
6846 #if BASH_PATTERN_SUBST
6847 /* For "${v/pattern/repl}", we must find the delimiter _before_
6848 * argstr() call expands possible variable references in pattern:
6849 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6852 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6853 /* Find '/' and replace with NUL */
6856 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6857 if (*repl == '\0') {
6865 if ((unsigned char)*repl == CTLESC && repl[1])
6871 argstr_flags = EXP_TILDE;
6872 if (subtype != VSASSIGN && subtype != VSQUESTION)
6873 argstr_flags |= (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE);
6874 argstr(p, argstr_flags);
6875 #if BASH_PATTERN_SUBST
6878 slash_pos = expdest - ((char *)stackblock() + strloc);
6879 STPUTC('/', expdest);
6880 argstr(repl + 1, argstr_flags);
6884 STPUTC('\0', expdest);
6885 argbackq = saveargbackq;
6886 startp = (char *)stackblock() + startloc;
6887 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6891 setvar0(varname, startp);
6892 amount = startp - expdest;
6893 STADJUST(amount, expdest);
6897 varunset(p, varname, startp, varflags);
6902 int pos, len, orig_len;
6905 loc = str = stackblock() + strloc;
6907 /* Read POS in ${var:POS:LEN} */
6908 colon = strchr(loc, ':');
6909 if (colon) *colon = '\0';
6910 pos = substr_atoi(loc);
6911 if (colon) *colon = ':';
6913 /* Read LEN in ${var:POS:LEN} */
6914 len = str - startp - 1;
6915 /* *loc != '\0', guaranteed by parser */
6918 /* Adjust the length by the number of escapes */
6919 for (ptr = startp; ptr < (str - 1); ptr++) {
6920 if ((unsigned char)*ptr == CTLESC) {
6927 if (*loc++ == ':') {
6929 len = substr_atoi(loc);
6931 /* Skip POS in ${var:POS:LEN} */
6933 while (*loc && *loc != ':')
6936 len = substr_atoi(loc);
6939 /* ${VAR:$((-n)):l} starts n chars from the end */
6940 pos = orig_len + pos;
6942 if ((unsigned)pos >= orig_len) {
6943 /* apart from obvious ${VAR:999999:l},
6944 * covers ${VAR:$((-9999999)):l} - result is ""
6951 /* ${VAR:N:-M} sets LEN to strlen()-M */
6952 len = (orig_len - pos) + len;
6954 if ((unsigned)len > (orig_len - pos))
6955 len = orig_len - pos;
6957 for (str = startp; pos; str++, pos--) {
6958 if (quotes && (unsigned char)*str == CTLESC)
6961 for (loc = startp; len; len--) {
6962 if (quotes && (unsigned char)*str == CTLESC)
6967 amount = loc - expdest;
6968 STADJUST(amount, expdest);
6971 #endif /* BASH_SUBSTR */
6974 resetloc = expdest - (char *)stackblock();
6976 #if BASH_PATTERN_SUBST
6979 /* We'll comeback here if we grow the stack while handling
6980 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6981 * stack will need rebasing, and we'll need to remove our work
6987 amount = expdest - ((char *)stackblock() + resetloc);
6988 STADJUST(-amount, expdest);
6989 startp = (char *)stackblock() + startloc;
6992 rmescend = (char *)stackblock() + strloc;
6993 //bb_error_msg("str7:'%s'", rmescend);
6995 //TODO: how to handle slash_pos here if string changes (shortens?)
6996 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
6997 if (rmesc != startp) {
6999 startp = (char *)stackblock() + startloc;
7003 str = (char *)stackblock() + strloc;
7005 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7006 * The result is a_\_z_c (not a\_\_z_c)!
7008 * The search pattern and replace string treat backslashes differently!
7009 * "&slash_pos" causes rmescapes() to work differently on the pattern
7010 * and string. It's only used on the first call.
7012 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7013 rmescapes(str, RMESCAPE_GLOB,
7014 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7017 #if BASH_PATTERN_SUBST
7018 workloc = expdest - (char *)stackblock();
7019 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7024 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7026 if (slash_pos >= 0) {
7027 repl = str + slash_pos;
7031 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7033 /* If there's no pattern to match, return the expansion unmolested */
7042 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7043 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7045 /* No match, advance */
7046 char *restart_detect = stackblock();
7048 STPUTC(*idx, expdest);
7049 if (quotes && (unsigned char)*idx == CTLESC) {
7052 STPUTC(*idx, expdest);
7054 if (stackblock() != restart_detect)
7059 /* continue; - prone to quadratic behavior, smarter code: */
7062 if (str[0] == '*') {
7063 /* Pattern is "*foo". If "*foo" does not match "long_string",
7064 * it would never match "ong_string" etc, no point in trying.
7071 if (subtype == VSREPLACEALL) {
7073 if (quotes && (unsigned char)*idx == CTLESC)
7082 //bb_error_msg("repl:'%s'", repl);
7083 for (loc = (char*)repl; *loc; loc++) {
7084 char *restart_detect = stackblock();
7085 if (quotes && *loc == '\\') {
7086 STPUTC(CTLESC, expdest);
7089 STPUTC(*loc, expdest);
7090 if (stackblock() != restart_detect)
7095 if (subtype == VSREPLACE) {
7096 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7098 char *restart_detect = stackblock();
7099 STPUTC(*idx, expdest);
7100 if (stackblock() != restart_detect)
7109 /* We've put the replaced text into a buffer at workloc, now
7110 * move it to the right place and adjust the stack.
7112 STPUTC('\0', expdest);
7113 startp = (char *)stackblock() + startloc;
7114 memmove(startp, (char *)stackblock() + workloc, len + 1);
7115 //bb_error_msg("startp:'%s'", startp);
7116 amount = expdest - (startp + len);
7117 STADJUST(-amount, expdest);
7120 #endif /* BASH_PATTERN_SUBST */
7122 subtype -= VSTRIMRIGHT;
7124 if (subtype < 0 || subtype > 7)
7127 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7128 zero = subtype >> 1;
7129 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7130 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7132 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7135 memmove(startp, loc, str - loc);
7136 loc = startp + (str - loc) - 1;
7139 amount = loc - expdest;
7140 STADJUST(amount, expdest);
7146 * Add the value of a specialized variable to the stack string.
7147 * name parameter (examples):
7148 * ash -c 'echo $1' name:'1='
7149 * ash -c 'echo $qwe' name:'qwe='
7150 * ash -c 'echo $$' name:'$='
7151 * ash -c 'echo ${$}' name:'$='
7152 * ash -c 'echo ${$##q}' name:'$=q'
7153 * ash -c 'echo ${#$}' name:'$='
7154 * note: examples with bad shell syntax:
7155 * ash -c 'echo ${#$1}' name:'$=1'
7156 * ash -c 'echo ${#1#}' name:'1=#'
7158 static NOINLINE ssize_t
7159 varvalue(char *name, int varflags, int flags, int *quotedp)
7166 int quoted = *quotedp;
7167 int subtype = varflags & VSTYPE;
7168 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7169 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7172 sep = (flags & EXP_FULL) << CHAR_BIT;
7173 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7183 num = shellparam.nparam;
7191 goto check_1char_name;
7193 expdest = makestrspace(NOPTS, expdest);
7194 for (i = NOPTS - 1; i >= 0; i--) {
7195 if (optlist[i] && optletters(i)) {
7196 USTPUTC(optletters(i), expdest);
7202 /* handles cases similar to ${#$1} */
7203 if (name[2] != '\0')
7204 raise_error_syntax("bad substitution");
7217 sep |= ifsset() ? ifsval()[0] : ' ';
7224 while ((p = *ap++) != NULL) {
7225 len += strtodest(p, syntax, quotes);
7229 memtodest(&sepc, 1, syntax, quotes);
7244 num = atoi(name); /* number(name) fails on ${N#str} etc */
7245 if (num < 0 || num > shellparam.nparam)
7247 p = num ? shellparam.p[num - 1] : arg0;
7250 /* NB: name has form "VAR=..." */
7251 p = lookupvar(name);
7256 len = strtodest(p, syntax, quotes);
7257 #if ENABLE_UNICODE_SUPPORT
7258 if (subtype == VSLENGTH && len > 0) {
7259 reinit_unicode_for_ash();
7260 if (unicode_status == UNICODE_ON) {
7261 STADJUST(-len, expdest);
7263 len = unicode_strlen(p);
7271 STADJUST(-len, expdest);
7276 * Expand a variable, and return a pointer to the next character in the
7280 evalvar(char *p, int flag)
7291 varflags = (unsigned char) *p++;
7292 subtype = varflags & VSTYPE;
7295 raise_error_syntax("bad substitution");
7297 quoted = flag & EXP_QUOTED;
7299 easy = (!quoted || (*var == '@' && shellparam.nparam));
7300 startloc = expdest - (char *)stackblock();
7301 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7304 varlen = varvalue(var, varflags, flag, "ed);
7305 if (varflags & VSNUL)
7308 if (subtype == VSPLUS) {
7309 varlen = -1 - varlen;
7313 if (subtype == VSMINUS) {
7318 flag | EXP_TILDE | EXP_WORD
7325 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7329 subevalvar(p, var, 0, subtype, startloc, varflags,
7330 flag & ~QUOTES_ESC);
7333 * Remove any recorded regions beyond
7336 removerecordregions(startloc);
7340 if (varlen < 0 && uflag)
7341 varunset(p, var, 0, 0);
7343 if (subtype == VSLENGTH) {
7344 cvtnum(varlen > 0 ? varlen : 0);
7348 if (subtype == VSNORMAL) {
7352 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7361 case VSTRIMRIGHTMAX:
7365 #if BASH_PATTERN_SUBST
7377 * Terminate the string and start recording the pattern
7380 STPUTC('\0', expdest);
7381 patloc = expdest - (char *)stackblock();
7382 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7383 startloc, varflags, flag)) {
7384 int amount = expdest - (
7385 (char *)stackblock() + patloc - 1
7387 STADJUST(-amount, expdest);
7389 /* Remove any recorded regions beyond start of variable */
7390 removerecordregions(startloc);
7395 if (subtype != VSNORMAL) { /* skip to end of alternative */
7398 unsigned char c = *p++;
7401 else if (c == CTLBACKQ) {
7403 argbackq = argbackq->next;
7404 } else if (c == CTLVAR) {
7405 if ((*p++ & VSTYPE) != VSNORMAL)
7407 } else if (c == CTLENDVAR) {
7417 * Add a file name to the list.
7420 addfname(const char *name)
7424 sp = stzalloc(sizeof(*sp));
7425 sp->text = sstrdup(name);
7427 exparg.lastp = &sp->next;
7430 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7432 hasmeta(const char *p)
7434 static const char chars[] ALIGN1 = {
7435 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7439 p = strpbrk(p, chars);
7442 switch ((unsigned char)*p) {
7446 if ((unsigned char)*p == CTLQUOTEMARK)
7448 if ((unsigned char)*p == CTLESC)
7450 if (*p == '\0') /* huh? */
7461 if (!strchr(p + 1, ']')) {
7462 /* It's not a properly closed [] pattern,
7463 * but other metas may follow. Continue checking.
7464 * my[file* _is_ globbed by bash
7465 * and matches filenames like "my[file1".
7481 /* If we want to use glob() from libc... */
7482 #if !ENABLE_ASH_INTERNAL_GLOB
7484 /* Add the result of glob() to the list */
7486 addglob(const glob_t *pglob)
7488 char **p = pglob->gl_pathv;
7495 expandmeta(struct strlist *str /*, int flag*/)
7497 /* TODO - EXP_REDIR */
7507 if (!hasmeta(str->text))
7511 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7512 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7513 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7515 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7516 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7517 // Which means you need to unescape the string, right? Not so fast:
7518 // if there _is_ a file named "file\?" (with backslash), it is returned
7519 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7520 // You DON'T KNOW by looking at the result whether you need to unescape it.
7522 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7523 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7524 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7525 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7526 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7527 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7528 i = glob(p, 0, NULL, &pglob);
7529 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7534 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7535 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7536 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7548 *exparg.lastp = str;
7549 rmescapes(str->text, 0, NULL);
7550 exparg.lastp = &str->next;
7552 default: /* GLOB_NOSPACE */
7555 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7562 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7565 * Do metacharacter (i.e. *, ?, [...]) expansion.
7568 expmeta(char *expdir, char *enddir, char *name)
7584 for (p = name; esc = 0, *p; p += esc + 1) {
7585 if (*p == '*' || *p == '?')
7587 else if (*p == '[') {
7594 if (*q == '/' || *q == '\0')
7604 if (p[esc] == '/') {
7607 start = p + esc + 1;
7611 if (metaflag == 0) { /* we've reached the end of the file name */
7612 if (enddir != expdir)
7620 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7631 } while (p < start);
7633 if (enddir == expdir) {
7635 } else if (enddir == expdir + 1 && *expdir == '/') {
7644 if (enddir != expdir)
7646 if (*endname == 0) {
7659 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7660 if (dp->d_name[0] == '.' && !matchdot)
7662 if (pmatch(start, dp->d_name)) {
7664 strcpy(enddir, dp->d_name);
7667 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7670 expmeta(expdir, p, endname);
7676 endname[-esc - 1] = esc ? '\\' : '/';
7679 static struct strlist *
7680 msort(struct strlist *list, int len)
7682 struct strlist *p, *q = NULL;
7683 struct strlist **lpp;
7691 for (n = half; --n >= 0;) {
7695 q->next = NULL; /* terminate first half of list */
7696 q = msort(list, half); /* sort first half of list */
7697 p = msort(p, len - half); /* sort second half */
7700 #if ENABLE_LOCALE_SUPPORT
7701 if (strcoll(p->text, q->text) < 0)
7703 if (strcmp(p->text, q->text) < 0)
7727 * Sort the results of file name expansion. It calculates the number of
7728 * strings to sort and then calls msort (short for merge sort) to do the
7731 static struct strlist *
7732 expsort(struct strlist *str)
7738 for (sp = str; sp; sp = sp->next)
7740 return msort(str, len);
7744 expandmeta(struct strlist *str /*, int flag*/)
7746 /* TODO - EXP_REDIR */
7750 struct strlist **savelastp;
7756 if (!hasmeta(str->text))
7758 savelastp = exparg.lastp;
7761 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7763 int i = strlen(str->text);
7764 //BUGGY estimation of how long expanded name can be
7765 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7767 expmeta(expdir, expdir, p);
7772 if (exparg.lastp == savelastp) {
7777 *exparg.lastp = str;
7778 rmescapes(str->text, 0, NULL);
7779 exparg.lastp = &str->next;
7781 *exparg.lastp = NULL;
7782 *savelastp = sp = expsort(*savelastp);
7783 while (sp->next != NULL)
7785 exparg.lastp = &sp->next;
7790 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7793 * Perform variable substitution and command substitution on an argument,
7794 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7795 * perform splitting and file name expansion. When arglist is NULL, perform
7796 * here document expansion.
7799 expandarg(union node *arg, struct arglist *arglist, int flag)
7804 argbackq = arg->narg.backquote;
7805 STARTSTACKSTR(expdest);
7806 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7807 argstr(arg->narg.text, flag);
7808 p = _STPUTC('\0', expdest);
7810 if (arglist == NULL) {
7811 /* here document expanded */
7814 p = grabstackstr(p);
7815 TRACE(("expandarg: p:'%s'\n", p));
7816 exparg.lastp = &exparg.list;
7820 if (flag & EXP_FULL) {
7821 ifsbreakup(p, &exparg);
7822 *exparg.lastp = NULL;
7823 exparg.lastp = &exparg.list;
7824 expandmeta(exparg.list /*, flag*/);
7826 sp = stzalloc(sizeof(*sp));
7829 exparg.lastp = &sp->next;
7831 *exparg.lastp = NULL;
7833 *arglist->lastp = exparg.list;
7834 arglist->lastp = exparg.lastp;
7842 * Expand shell variables and backquotes inside a here document.
7845 expandhere(union node *arg, int fd)
7847 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7848 full_write(fd, stackblock(), expdest - (char *)stackblock());
7852 * Returns true if the pattern matches the string.
7855 patmatch(char *pattern, const char *string)
7857 char *p = preglob(pattern, 0);
7858 int r = pmatch(p, string);
7859 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7864 * See if a pattern matches in a case statement.
7867 casematch(union node *pattern, char *val)
7869 struct stackmark smark;
7872 setstackmark(&smark);
7873 argbackq = pattern->narg.backquote;
7874 STARTSTACKSTR(expdest);
7875 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7876 STACKSTRNUL(expdest);
7878 result = patmatch(stackblock(), val);
7879 popstackmark(&smark);
7884 /* ============ find_command */
7888 int (*builtin)(int, char **) FAST_FUNC;
7889 /* unsigned flags; */
7891 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7892 /* "regular" builtins always take precedence over commands,
7893 * regardless of PATH=....%builtin... position */
7894 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7895 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7898 smallint cmdtype; /* CMDxxx */
7901 /* index >= 0 for commands without path (slashes) */
7902 /* (TODO: what exactly does the value mean? PATH position?) */
7903 /* index == -1 for commands with slashes */
7904 /* index == (-2 - applet_no) for NOFORK applets */
7905 const struct builtincmd *cmd;
7906 struct funcnode *func;
7909 /* values of cmdtype */
7910 #define CMDUNKNOWN -1 /* no entry in table for command */
7911 #define CMDNORMAL 0 /* command is an executable program */
7912 #define CMDFUNCTION 1 /* command is a shell function */
7913 #define CMDBUILTIN 2 /* command is a shell builtin */
7915 /* action to find_command() */
7916 #define DO_ERR 0x01 /* prints errors */
7917 #define DO_ABS 0x02 /* checks absolute paths */
7918 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7919 #define DO_ALTPATH 0x08 /* using alternate path */
7920 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7922 static void find_command(char *, struct cmdentry *, int, const char *);
7925 /* ============ Hashing commands */
7928 * When commands are first encountered, they are entered in a hash table.
7929 * This ensures that a full path search will not have to be done for them
7930 * on each invocation.
7932 * We should investigate converting to a linear search, even though that
7933 * would make the command name "hash" a misnomer.
7937 struct tblentry *next; /* next entry in hash chain */
7938 union param param; /* definition of builtin function */
7939 smallint cmdtype; /* CMDxxx */
7940 char rehash; /* if set, cd done since entry created */
7941 char cmdname[1]; /* name of command */
7944 static struct tblentry **cmdtable;
7945 #define INIT_G_cmdtable() do { \
7946 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7949 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7953 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7955 #if ENABLE_FEATURE_SH_STANDALONE
7956 if (applet_no >= 0) {
7957 if (APPLET_IS_NOEXEC(applet_no)) {
7961 popredir(/*drop:*/ 1);
7962 run_noexec_applet_and_exit(applet_no, cmd, argv);
7964 /* re-exec ourselves with the new arguments */
7965 execve(bb_busybox_exec_path, argv, envp);
7966 /* If they called chroot or otherwise made the binary no longer
7967 * executable, fall through */
7974 execve(cmd, argv, envp);
7975 } while (errno == EINTR);
7977 execve(cmd, argv, envp);
7979 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7980 /* Run "cmd" as a shell script:
7981 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7982 * "If the execve() function fails with ENOEXEC, the shell
7983 * shall execute a command equivalent to having a shell invoked
7984 * with the command name as its first operand,
7985 * with any remaining arguments passed to the new shell"
7987 * That is, do not use $SHELL, user's shell, or /bin/sh;
7988 * just call ourselves.
7990 * Note that bash reads ~80 chars of the file, and if it sees
7991 * a zero byte before it sees newline, it doesn't try to
7992 * interpret it, but fails with "cannot execute binary file"
7993 * message and exit code 126. For one, this prevents attempts
7994 * to interpret foreign ELF binaries as shell scripts.
7996 argv[0] = (char*) cmd;
7997 cmd = bb_busybox_exec_path;
7998 /* NB: this is only possible because all callers of shellexec()
7999 * ensure that the argv[-1] slot exists!
8002 argv[0] = (char*) "ash";
8008 * Exec a program. Never returns. If you change this routine, you may
8009 * have to change the find_command routine as well.
8010 * argv[-1] must exist and be writable! See tryexec() for why.
8012 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8013 static void shellexec(char *prog, char **argv, const char *path, int idx)
8019 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8021 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8022 if (strchr(prog, '/') != NULL
8023 #if ENABLE_FEATURE_SH_STANDALONE
8024 || (applet_no = find_applet_by_name(prog)) >= 0
8027 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8028 if (applet_no >= 0) {
8029 /* We tried execing ourself, but it didn't work.
8030 * Maybe /proc/self/exe doesn't exist?
8039 while ((cmdname = path_advance(&path, prog)) != NULL) {
8040 if (--idx < 0 && pathopt == NULL) {
8041 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8042 if (errno != ENOENT && errno != ENOTDIR)
8049 /* Map to POSIX errors */
8061 exitstatus = exerrno;
8062 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8063 prog, e, suppress_int));
8064 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8069 printentry(struct tblentry *cmdp)
8075 idx = cmdp->param.index;
8078 name = path_advance(&path, cmdp->cmdname);
8080 } while (--idx >= 0);
8081 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8085 * Clear out command entries. The argument specifies the first entry in
8086 * PATH which has changed.
8089 clearcmdentry(int firstchange)
8091 struct tblentry **tblp;
8092 struct tblentry **pp;
8093 struct tblentry *cmdp;
8096 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8098 while ((cmdp = *pp) != NULL) {
8099 if ((cmdp->cmdtype == CMDNORMAL &&
8100 cmdp->param.index >= firstchange)
8101 || (cmdp->cmdtype == CMDBUILTIN &&
8102 builtinloc >= firstchange)
8115 * Locate a command in the command hash table. If "add" is nonzero,
8116 * add the command to the table if it is not already present. The
8117 * variable "lastcmdentry" is set to point to the address of the link
8118 * pointing to the entry, so that delete_cmd_entry can delete the
8121 * Interrupts must be off if called with add != 0.
8123 static struct tblentry **lastcmdentry;
8125 static struct tblentry *
8126 cmdlookup(const char *name, int add)
8128 unsigned int hashval;
8130 struct tblentry *cmdp;
8131 struct tblentry **pp;
8134 hashval = (unsigned char)*p << 4;
8136 hashval += (unsigned char)*p++;
8138 pp = &cmdtable[hashval % CMDTABLESIZE];
8139 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8140 if (strcmp(cmdp->cmdname, name) == 0)
8144 if (add && cmdp == NULL) {
8145 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8147 /* + 1 - already done because
8148 * tblentry::cmdname is char[1] */);
8149 /*cmdp->next = NULL; - ckzalloc did it */
8150 cmdp->cmdtype = CMDUNKNOWN;
8151 strcpy(cmdp->cmdname, name);
8158 * Delete the command entry returned on the last lookup.
8161 delete_cmd_entry(void)
8163 struct tblentry *cmdp;
8166 cmdp = *lastcmdentry;
8167 *lastcmdentry = cmdp->next;
8168 if (cmdp->cmdtype == CMDFUNCTION)
8169 freefunc(cmdp->param.func);
8175 * Add a new command entry, replacing any existing command entry for
8176 * the same name - except special builtins.
8179 addcmdentry(char *name, struct cmdentry *entry)
8181 struct tblentry *cmdp;
8183 cmdp = cmdlookup(name, 1);
8184 if (cmdp->cmdtype == CMDFUNCTION) {
8185 freefunc(cmdp->param.func);
8187 cmdp->cmdtype = entry->cmdtype;
8188 cmdp->param = entry->u;
8192 static int FAST_FUNC
8193 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8195 struct tblentry **pp;
8196 struct tblentry *cmdp;
8198 struct cmdentry entry;
8201 if (nextopt("r") != '\0') {
8206 if (*argptr == NULL) {
8207 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8208 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8209 if (cmdp->cmdtype == CMDNORMAL)
8217 while ((name = *argptr) != NULL) {
8218 cmdp = cmdlookup(name, 0);
8220 && (cmdp->cmdtype == CMDNORMAL
8221 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8225 find_command(name, &entry, DO_ERR, pathval());
8226 if (entry.cmdtype == CMDUNKNOWN)
8234 * Called when a cd is done. Marks all commands so the next time they
8235 * are executed they will be rehashed.
8240 struct tblentry **pp;
8241 struct tblentry *cmdp;
8243 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8244 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8245 if (cmdp->cmdtype == CMDNORMAL
8246 || (cmdp->cmdtype == CMDBUILTIN
8247 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8257 * Fix command hash table when PATH changed.
8258 * Called before PATH is changed. The argument is the new value of PATH;
8259 * pathval() still returns the old value at this point.
8260 * Called with interrupts off.
8262 static void FAST_FUNC
8263 changepath(const char *new)
8271 firstchange = 9999; /* assume no change */
8277 if ((*old == '\0' && *new == ':')
8278 || (*old == ':' && *new == '\0')
8282 old = new; /* ignore subsequent differences */
8286 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8293 if (builtinloc < 0 && idx_bltin >= 0)
8294 builtinloc = idx_bltin; /* zap builtins */
8295 if (builtinloc >= 0 && idx_bltin < 0)
8297 clearcmdentry(firstchange);
8298 builtinloc = idx_bltin;
8334 typedef smallint token_id_t;
8336 /* Nth bit indicates if token marks the end of a list */
8339 /* 0 */ | (1u << TEOF)
8340 /* 1 */ | (0u << TNL)
8341 /* 2 */ | (0u << TREDIR)
8342 /* 3 */ | (0u << TWORD)
8343 /* 4 */ | (0u << TSEMI)
8344 /* 5 */ | (0u << TBACKGND)
8345 /* 6 */ | (0u << TAND)
8346 /* 7 */ | (0u << TOR)
8347 /* 8 */ | (0u << TPIPE)
8348 /* 9 */ | (0u << TLP)
8349 /* 10 */ | (1u << TRP)
8350 /* 11 */ | (1u << TENDCASE)
8351 /* 12 */ | (1u << TENDBQUOTE)
8352 /* 13 */ | (0u << TNOT)
8353 /* 14 */ | (0u << TCASE)
8354 /* 15 */ | (1u << TDO)
8355 /* 16 */ | (1u << TDONE)
8356 /* 17 */ | (1u << TELIF)
8357 /* 18 */ | (1u << TELSE)
8358 /* 19 */ | (1u << TESAC)
8359 /* 20 */ | (1u << TFI)
8360 /* 21 */ | (0u << TFOR)
8362 /* 22 */ | (0u << TFUNCTION)
8364 /* 23 */ | (0u << TIF)
8365 /* 24 */ | (0u << TIN)
8366 /* 25 */ | (1u << TTHEN)
8367 /* 26 */ | (0u << TUNTIL)
8368 /* 27 */ | (0u << TWHILE)
8369 /* 28 */ | (0u << TBEGIN)
8370 /* 29 */ | (1u << TEND)
8371 , /* thus far 29 bits used */
8374 static const char *const tokname_array[] = {
8388 #define KWDOFFSET 13
8389 /* the following are keywords */
8411 /* Wrapper around strcmp for qsort/bsearch/... */
8413 pstrcmp(const void *a, const void *b)
8415 return strcmp((char*)a, *(char**)b);
8418 static const char *const *
8419 findkwd(const char *s)
8421 return bsearch(s, tokname_array + KWDOFFSET,
8422 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8423 sizeof(tokname_array[0]), pstrcmp);
8427 * Locate and print what a word is...
8430 describe_command(char *command, const char *path, int describe_command_verbose)
8432 struct cmdentry entry;
8433 #if ENABLE_ASH_ALIAS
8434 const struct alias *ap;
8437 path = path ? path : pathval();
8439 if (describe_command_verbose) {
8443 /* First look at the keywords */
8444 if (findkwd(command)) {
8445 out1str(describe_command_verbose ? " is a shell keyword" : command);
8449 #if ENABLE_ASH_ALIAS
8450 /* Then look at the aliases */
8451 ap = lookupalias(command, 0);
8453 if (!describe_command_verbose) {
8458 out1fmt(" is an alias for %s", ap->val);
8463 find_command(command, &entry, DO_ABS, path);
8465 switch (entry.cmdtype) {
8467 int j = entry.u.index;
8473 p = path_advance(&path, command);
8477 if (describe_command_verbose) {
8478 out1fmt(" is %s", p);
8486 if (describe_command_verbose) {
8487 out1str(" is a shell function");
8494 if (describe_command_verbose) {
8495 out1fmt(" is a %sshell builtin",
8496 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8497 "special " : nullstr
8505 if (describe_command_verbose) {
8506 out1str(": not found\n");
8515 static int FAST_FUNC
8516 typecmd(int argc UNUSED_PARAM, char **argv)
8522 /* type -p ... ? (we don't bother checking for 'p') */
8523 if (argv[1] && argv[1][0] == '-') {
8528 err |= describe_command(argv[i++], NULL, verbose);
8533 #if ENABLE_ASH_CMDCMD
8534 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8536 parse_command_args(char **argv, const char **path)
8549 if (c == '-' && !*cp) {
8557 *path = bb_default_path;
8560 /* run 'typecmd' for other options */
8569 static int FAST_FUNC
8570 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8578 const char *path = NULL;
8580 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8581 * never reaches this function.
8584 while ((c = nextopt("pvV")) != '\0')
8586 verify |= VERIFY_VERBOSE;
8588 /*verify |= VERIFY_BRIEF*/;
8594 path = bb_default_path;
8596 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8598 if (/*verify && */ cmd)
8599 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8606 /*static int funcblocksize; // size of structures in function */
8607 /*static int funcstringsize; // size of strings in node */
8608 static void *funcblock; /* block to allocate function from */
8609 static char *funcstring_end; /* end of block to allocate strings from */
8611 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8612 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8613 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8614 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8615 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8616 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8617 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8618 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8619 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8620 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8621 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8622 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8623 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8624 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8625 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8626 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8627 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8628 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8629 #if BASH_REDIR_OUTPUT
8630 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8632 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8633 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8634 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8635 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8636 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8637 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8638 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8639 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8640 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8643 static int calcsize(int funcblocksize, union node *n);
8646 sizenodelist(int funcblocksize, struct nodelist *lp)
8649 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8650 funcblocksize = calcsize(funcblocksize, lp->n);
8653 return funcblocksize;
8657 calcsize(int funcblocksize, union node *n)
8660 return funcblocksize;
8661 funcblocksize += nodesize[n->type];
8664 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8665 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8666 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8669 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8674 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8675 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8682 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8683 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8686 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8687 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8688 funcblocksize = calcsize(funcblocksize, n->nif.test);
8691 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8692 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8693 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8696 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8697 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8700 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8701 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8702 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8705 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8706 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8709 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8710 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8711 funcblocksize = calcsize(funcblocksize, n->narg.next);
8714 #if BASH_REDIR_OUTPUT
8721 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8722 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8726 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8727 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8731 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8732 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8735 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8738 return funcblocksize;
8742 nodeckstrdup(char *s)
8744 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8745 return strcpy(funcstring_end, s);
8748 static union node *copynode(union node *);
8750 static struct nodelist *
8751 copynodelist(struct nodelist *lp)
8753 struct nodelist *start;
8754 struct nodelist **lpp;
8759 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8760 (*lpp)->n = copynode(lp->n);
8762 lpp = &(*lpp)->next;
8769 copynode(union node *n)
8776 funcblock = (char *) funcblock + nodesize[n->type];
8780 new->ncmd.redirect = copynode(n->ncmd.redirect);
8781 new->ncmd.args = copynode(n->ncmd.args);
8782 new->ncmd.assign = copynode(n->ncmd.assign);
8783 new->ncmd.linno = n->ncmd.linno;
8786 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8787 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8792 new->nredir.redirect = copynode(n->nredir.redirect);
8793 new->nredir.n = copynode(n->nredir.n);
8794 new->nredir.linno = n->nredir.linno;
8801 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8802 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8805 new->nif.elsepart = copynode(n->nif.elsepart);
8806 new->nif.ifpart = copynode(n->nif.ifpart);
8807 new->nif.test = copynode(n->nif.test);
8810 new->nfor.var = nodeckstrdup(n->nfor.var);
8811 new->nfor.body = copynode(n->nfor.body);
8812 new->nfor.args = copynode(n->nfor.args);
8813 new->nfor.linno = n->nfor.linno;
8816 new->ncase.cases = copynode(n->ncase.cases);
8817 new->ncase.expr = copynode(n->ncase.expr);
8818 new->ncase.linno = n->ncase.linno;
8821 new->nclist.body = copynode(n->nclist.body);
8822 new->nclist.pattern = copynode(n->nclist.pattern);
8823 new->nclist.next = copynode(n->nclist.next);
8826 new->ndefun.body = copynode(n->ndefun.body);
8827 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8828 new->ndefun.linno = n->ndefun.linno;
8831 new->narg.backquote = copynodelist(n->narg.backquote);
8832 new->narg.text = nodeckstrdup(n->narg.text);
8833 new->narg.next = copynode(n->narg.next);
8836 #if BASH_REDIR_OUTPUT
8843 new->nfile.fname = copynode(n->nfile.fname);
8844 new->nfile.fd = n->nfile.fd;
8845 new->nfile.next = copynode(n->nfile.next);
8849 new->ndup.vname = copynode(n->ndup.vname);
8850 new->ndup.dupfd = n->ndup.dupfd;
8851 new->ndup.fd = n->ndup.fd;
8852 new->ndup.next = copynode(n->ndup.next);
8856 new->nhere.doc = copynode(n->nhere.doc);
8857 new->nhere.fd = n->nhere.fd;
8858 new->nhere.next = copynode(n->nhere.next);
8861 new->nnot.com = copynode(n->nnot.com);
8864 new->type = n->type;
8869 * Make a copy of a parse tree.
8871 static struct funcnode *
8872 copyfunc(union node *n)
8877 /*funcstringsize = 0;*/
8878 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8879 f = ckzalloc(blocksize /* + funcstringsize */);
8880 funcblock = (char *) f + offsetof(struct funcnode, n);
8881 funcstring_end = (char *) f + blocksize;
8883 /* f->count = 0; - ckzalloc did it */
8888 * Define a shell function.
8891 defun(union node *func)
8893 struct cmdentry entry;
8896 entry.cmdtype = CMDFUNCTION;
8897 entry.u.func = copyfunc(func);
8898 addcmdentry(func->ndefun.text, &entry);
8902 /* Reasons for skipping commands (see comment on breakcmd routine) */
8903 #define SKIPBREAK (1 << 0)
8904 #define SKIPCONT (1 << 1)
8905 #define SKIPFUNC (1 << 2)
8906 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8907 static int skipcount; /* number of levels to skip */
8908 static int loopnest; /* current loop nesting level */
8909 static int funcline; /* starting line number of current function, or 0 if not in a function */
8911 /* Forward decl way out to parsing code - dotrap needs it */
8912 static int evalstring(char *s, int flags);
8914 /* Called to execute a trap.
8915 * Single callsite - at the end of evaltree().
8916 * If we return non-zero, evaltree raises EXEXIT exception.
8918 * Perhaps we should avoid entering new trap handlers
8919 * while we are executing a trap handler. [is it a TODO?]
8926 uint8_t last_status;
8931 last_status = exitstatus;
8935 TRACE(("dotrap entered\n"));
8936 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8948 /* non-trapped SIGINT is handled separately by raise_interrupt,
8949 * don't upset it by resetting gotsig[SIGINT-1] */
8950 if (sig == SIGINT && !p)
8953 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8959 exitstatus = last_status;
8960 TRACE(("dotrap returns\n"));
8963 /* forward declarations - evaluation is fairly recursive business... */
8964 static int evalloop(union node *, int);
8965 static int evalfor(union node *, int);
8966 static int evalcase(union node *, int);
8967 static int evalsubshell(union node *, int);
8968 static void expredir(union node *);
8969 static int evalpipe(union node *, int);
8970 static int evalcommand(union node *, int);
8971 static int evalbltin(const struct builtincmd *, int, char **, int);
8972 static void prehash(union node *);
8975 * Evaluate a parse tree. The value is left in the global variable
8979 evaltree(union node *n, int flags)
8982 int (*evalfn)(union node *, int);
8986 TRACE(("evaltree(NULL) called\n"));
8989 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8996 out1fmt("Node type = %d\n", n->type);
9001 status = !evaltree(n->nnot.com, EV_TESTED);
9004 errlinno = lineno = n->nredir.linno;
9006 lineno -= funcline - 1;
9007 expredir(n->nredir.redirect);
9008 pushredir(n->nredir.redirect);
9009 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9011 status = evaltree(n->nredir.n, flags & EV_TESTED);
9013 if (n->nredir.redirect)
9014 popredir(/*drop:*/ 0);
9017 evalfn = evalcommand;
9019 if (eflag && !(flags & EV_TESTED))
9031 evalfn = evalsubshell;
9044 #error NAND + 1 != NOR
9046 #if NOR + 1 != NSEMI
9047 #error NOR + 1 != NSEMI
9049 unsigned is_or = n->type - NAND;
9052 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9054 if ((!status) == is_or || evalskip)
9060 status = evalfn(n, flags);
9064 status = evaltree(n->nif.test, EV_TESTED);
9071 if (n->nif.elsepart) {
9072 n = n->nif.elsepart;
9079 /* Not necessary. To test it:
9080 * "false; f() { qwerty; }; echo $?" should print 0.
9084 exitstatus = status;
9088 /* Order of checks below is important:
9089 * signal handlers trigger before exit caused by "set -e".
9093 if (checkexit & status)
9094 raise_exception(EXEXIT);
9095 if (flags & EV_EXIT)
9096 raise_exception(EXEXIT);
9098 TRACE(("leaving evaltree (no interrupts)\n"));
9105 int skip = evalskip;
9112 if (--skipcount <= 0) {
9123 evalloop(union node *n, int flags)
9134 i = evaltree(n->nbinary.ch1, EV_TESTED);
9136 if (skip == SKIPFUNC)
9140 if (n->type != NWHILE)
9144 status = evaltree(n->nbinary.ch2, flags);
9146 } while (!(skip & ~SKIPCONT));
9153 evalfor(union node *n, int flags)
9155 struct arglist arglist;
9158 struct stackmark smark;
9161 errlinno = lineno = n->ncase.linno;
9163 lineno -= funcline - 1;
9165 setstackmark(&smark);
9166 arglist.list = NULL;
9167 arglist.lastp = &arglist.list;
9168 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9169 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9171 *arglist.lastp = NULL;
9175 for (sp = arglist.list; sp; sp = sp->next) {
9176 setvar0(n->nfor.var, sp->text);
9177 status = evaltree(n->nfor.body, flags);
9178 if (skiploop() & ~SKIPCONT)
9182 popstackmark(&smark);
9188 evalcase(union node *n, int flags)
9192 struct arglist arglist;
9193 struct stackmark smark;
9196 errlinno = lineno = n->ncase.linno;
9198 lineno -= funcline - 1;
9200 setstackmark(&smark);
9201 arglist.list = NULL;
9202 arglist.lastp = &arglist.list;
9203 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9204 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9205 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9206 if (casematch(patp, arglist.list->text)) {
9207 /* Ensure body is non-empty as otherwise
9208 * EV_EXIT may prevent us from setting the
9211 if (evalskip == 0 && cp->nclist.body) {
9212 status = evaltree(cp->nclist.body, flags);
9219 popstackmark(&smark);
9225 * Kick off a subshell to evaluate a tree.
9228 evalsubshell(union node *n, int flags)
9231 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9234 errlinno = lineno = n->nredir.linno;
9236 lineno -= funcline - 1;
9238 expredir(n->nredir.redirect);
9239 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9242 if (backgnd == FORK_FG)
9244 jp = makejob(/*n,*/ 1);
9245 if (forkshell(jp, n, backgnd) == 0) {
9250 flags &= ~EV_TESTED;
9252 redirect(n->nredir.redirect, 0);
9253 evaltreenr(n->nredir.n, flags);
9258 if (backgnd == FORK_FG)
9259 status = waitforjob(jp);
9265 * Compute the names of the files in a redirection list.
9267 static void fixredir(union node *, const char *, int);
9269 expredir(union node *n)
9273 for (redir = n; redir; redir = redir->nfile.next) {
9277 fn.lastp = &fn.list;
9278 switch (redir->type) {
9282 #if BASH_REDIR_OUTPUT
9287 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9288 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9289 #if BASH_REDIR_OUTPUT
9293 // By the design of stack allocator, the loop of this kind:
9294 // while true; do while true; do break; done </dev/null; done
9295 // will look like a memory leak: ash plans to free expfname's
9296 // of "/dev/null" as soon as it finishes running the loop
9297 // (in this case, never).
9298 // This "fix" is wrong:
9299 if (redir->nfile.expfname)
9300 stunalloc(redir->nfile.expfname);
9301 // It results in corrupted state of stacked allocations.
9303 redir->nfile.expfname = fn.list->text;
9306 case NTOFD: /* >& */
9307 if (redir->ndup.vname) {
9308 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9309 if (fn.list == NULL)
9310 ash_msg_and_raise_error("redir error");
9311 #if BASH_REDIR_OUTPUT
9312 //FIXME: we used expandarg with different args!
9313 if (!isdigit_str9(fn.list->text)) {
9314 /* >&file, not >&fd */
9315 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9316 ash_msg_and_raise_error("redir error");
9318 goto store_expfname;
9321 fixredir(redir, fn.list->text, 1);
9329 * Evaluate a pipeline. All the processes in the pipeline are children
9330 * of the process creating the pipeline. (This differs from some versions
9331 * of the shell, which make the last process in a pipeline the parent
9335 evalpipe(union node *n, int flags)
9338 struct nodelist *lp;
9344 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9346 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9350 if (n->npipe.pipe_backgnd == 0)
9352 jp = makejob(/*n,*/ pipelen);
9354 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9358 if (pipe(pip) < 0) {
9360 ash_msg_and_raise_perror("can't create pipe");
9363 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9377 evaltreenr(lp->n, flags);
9384 /* Don't want to trigger debugging */
9388 if (n->npipe.pipe_backgnd == 0) {
9389 status = waitforjob(jp);
9390 TRACE(("evalpipe: job done exit status %d\n", status));
9398 * Controls whether the shell is interactive or not.
9401 setinteractive(int on)
9403 static smallint is_interactive;
9405 if (++on == is_interactive)
9407 is_interactive = on;
9411 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9412 if (is_interactive > 1) {
9413 /* Looks like they want an interactive shell */
9414 static smallint did_banner;
9417 /* note: ash and hush share this string */
9418 out1fmt("\n\n%s %s\n"
9419 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9422 "built-in shell (ash)"
9436 setinteractive(iflag);
9438 #if ENABLE_FEATURE_EDITING_VI
9440 line_input_state->flags |= VI_MODE;
9442 line_input_state->flags &= ~VI_MODE;
9444 viflag = 0; /* forcibly keep the option off */
9448 struct localvar_list {
9449 struct localvar_list *next;
9450 struct localvar *lv;
9453 static struct localvar_list *localvar_stack;
9456 * Called after a function returns.
9457 * Interrupts must be off.
9460 poplocalvars(int keep)
9462 struct localvar_list *ll;
9463 struct localvar *lvp, *next;
9467 ll = localvar_stack;
9468 localvar_stack = ll->next;
9473 while ((lvp = next) != NULL) {
9476 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9478 int bits = VSTRFIXED;
9480 if (lvp->flags != VUNSET) {
9481 if (vp->var_text == lvp->text)
9483 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9484 free((char*)lvp->text);
9488 vp->flags |= (lvp->flags & bits);
9491 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9492 unsetvar(vp->var_text);
9493 } else if (vp == NULL) { /* $- saved */
9494 memcpy(optlist, lvp->text, sizeof(optlist));
9495 free((char*)lvp->text);
9497 } else if (lvp->flags == VUNSET) {
9498 vp->flags &= ~(VSTRFIXED|VREADONLY);
9499 unsetvar(vp->var_text);
9502 vp->var_func(var_end(lvp->text));
9503 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9504 free((char*)vp->var_text);
9505 vp->flags = lvp->flags;
9506 vp->var_text = lvp->text;
9514 * Create a new localvar environment.
9516 static struct localvar_list *
9519 struct localvar_list *ll;
9522 ll = ckzalloc(sizeof(*ll));
9523 /*ll->lv = NULL; - zalloc did it */
9524 ll->next = localvar_stack;
9525 localvar_stack = ll;
9532 unwindlocalvars(struct localvar_list *stop)
9534 while (localvar_stack != stop)
9539 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9541 volatile struct shparam saveparam;
9542 struct jmploc *volatile savehandler;
9543 struct jmploc jmploc;
9547 saveparam = shellparam;
9548 savefuncline = funcline;
9549 savehandler = exception_handler;
9550 e = setjmp(jmploc.loc);
9555 exception_handler = &jmploc;
9556 shellparam.malloced = 0;
9558 funcline = func->n.ndefun.linno;
9560 shellparam.nparam = argc - 1;
9561 shellparam.p = argv + 1;
9562 #if ENABLE_ASH_GETOPTS
9563 shellparam.optind = 1;
9564 shellparam.optoff = -1;
9567 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9571 funcline = savefuncline;
9573 freeparam(&shellparam);
9574 shellparam = saveparam;
9575 exception_handler = savehandler;
9577 evalskip &= ~SKIPFUNC;
9582 * Make a variable a local variable. When a variable is made local, it's
9583 * value and flags are saved in a localvar structure. The saved values
9584 * will be restored when the shell function returns. We handle the name
9585 * "-" as a special case: it makes changes to "set +-options" local
9586 * (options will be restored on return from the function).
9591 struct localvar *lvp;
9594 char *eq = strchr(name, '=');
9597 /* Cater for duplicate "local". Examples:
9598 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9599 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9601 lvp = localvar_stack->lv;
9603 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9607 * it's a duplicate "local VAR" declaration, do nothing
9614 lvp = ckzalloc(sizeof(*lvp));
9615 if (LONE_DASH(name)) {
9617 p = ckmalloc(sizeof(optlist));
9618 lvp->text = memcpy(p, optlist, sizeof(optlist));
9621 vpp = hashvar(name);
9622 vp = *findvar(vpp, name);
9624 /* variable did not exist yet */
9626 vp = setvareq(name, VSTRFIXED);
9628 vp = setvar(name, NULL, VSTRFIXED);
9629 lvp->flags = VUNSET;
9631 lvp->text = vp->var_text;
9632 lvp->flags = vp->flags;
9633 /* make sure neither "struct var" nor string gets freed
9634 * during (un)setting:
9636 vp->flags |= VSTRFIXED|VTEXTFIXED;
9640 /* "local VAR" unsets VAR: */
9641 setvar0(name, NULL);
9645 lvp->next = localvar_stack->lv;
9646 localvar_stack->lv = lvp;
9652 * The "local" command.
9654 static int FAST_FUNC
9655 localcmd(int argc UNUSED_PARAM, char **argv)
9659 if (!localvar_stack)
9660 ash_msg_and_raise_error("not in a function");
9663 while ((name = *argv++) != NULL) {
9669 static int FAST_FUNC
9670 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9675 static int FAST_FUNC
9676 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9681 static int FAST_FUNC
9682 execcmd(int argc UNUSED_PARAM, char **argv)
9685 while (nextopt("a:") != '\0')
9686 /* nextopt() sets optionarg to "-a ARGV0" */;
9692 iflag = 0; /* exit on error */
9695 /* We should set up signals for "exec CMD"
9696 * the same way as for "CMD" without "exec".
9697 * But optschanged->setinteractive->setsignal
9698 * still thought we are a root shell. Therefore, for example,
9699 * SIGQUIT is still set to IGN. Fix it:
9703 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9704 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9705 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9709 argv[0] = optionarg;
9710 shellexec(prog, argv, pathval(), 0);
9717 * The return command.
9719 static int FAST_FUNC
9720 returncmd(int argc UNUSED_PARAM, char **argv)
9723 * If called outside a function, do what ksh does;
9724 * skip the rest of the file.
9726 evalskip = SKIPFUNC;
9727 return argv[1] ? number(argv[1]) : exitstatus;
9730 /* Forward declarations for builtintab[] */
9731 static int breakcmd(int, char **) FAST_FUNC;
9732 static int dotcmd(int, char **) FAST_FUNC;
9733 static int evalcmd(int, char **, int) FAST_FUNC;
9734 static int exitcmd(int, char **) FAST_FUNC;
9735 static int exportcmd(int, char **) FAST_FUNC;
9736 #if ENABLE_ASH_GETOPTS
9737 static int getoptscmd(int, char **) FAST_FUNC;
9740 static int helpcmd(int, char **) FAST_FUNC;
9743 static int historycmd(int, char **) FAST_FUNC;
9745 #if ENABLE_FEATURE_SH_MATH
9746 static int letcmd(int, char **) FAST_FUNC;
9748 static int readcmd(int, char **) FAST_FUNC;
9749 static int setcmd(int, char **) FAST_FUNC;
9750 static int shiftcmd(int, char **) FAST_FUNC;
9751 static int timescmd(int, char **) FAST_FUNC;
9752 static int trapcmd(int, char **) FAST_FUNC;
9753 static int umaskcmd(int, char **) FAST_FUNC;
9754 static int unsetcmd(int, char **) FAST_FUNC;
9755 static int ulimitcmd(int, char **) FAST_FUNC;
9757 #define BUILTIN_NOSPEC "0"
9758 #define BUILTIN_SPECIAL "1"
9759 #define BUILTIN_REGULAR "2"
9760 #define BUILTIN_SPEC_REG "3"
9761 #define BUILTIN_ASSIGN "4"
9762 #define BUILTIN_SPEC_ASSG "5"
9763 #define BUILTIN_REG_ASSG "6"
9764 #define BUILTIN_SPEC_REG_ASSG "7"
9766 /* Stubs for calling non-FAST_FUNC's */
9768 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9770 #if ENABLE_ASH_PRINTF
9771 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9773 #if ENABLE_ASH_TEST || BASH_TEST2
9774 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9777 /* Keep these in proper order since it is searched via bsearch() */
9778 static const struct builtincmd builtintab[] = {
9779 { BUILTIN_SPEC_REG "." , dotcmd },
9780 { BUILTIN_SPEC_REG ":" , truecmd },
9782 { BUILTIN_REGULAR "[" , testcmd },
9785 { BUILTIN_REGULAR "[[" , testcmd },
9787 #if ENABLE_ASH_ALIAS
9788 { BUILTIN_REG_ASSG "alias" , aliascmd },
9791 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9793 { BUILTIN_SPEC_REG "break" , breakcmd },
9794 { BUILTIN_REGULAR "cd" , cdcmd },
9795 { BUILTIN_NOSPEC "chdir" , cdcmd },
9796 #if ENABLE_ASH_CMDCMD
9797 { BUILTIN_REGULAR "command" , commandcmd },
9799 { BUILTIN_SPEC_REG "continue", breakcmd },
9801 { BUILTIN_REGULAR "echo" , echocmd },
9803 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9804 { BUILTIN_SPEC_REG "exec" , execcmd },
9805 { BUILTIN_SPEC_REG "exit" , exitcmd },
9806 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9807 { BUILTIN_REGULAR "false" , falsecmd },
9809 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9811 #if ENABLE_ASH_GETOPTS
9812 { BUILTIN_REGULAR "getopts" , getoptscmd },
9814 { BUILTIN_NOSPEC "hash" , hashcmd },
9816 { BUILTIN_NOSPEC "help" , helpcmd },
9819 { BUILTIN_NOSPEC "history" , historycmd },
9822 { BUILTIN_REGULAR "jobs" , jobscmd },
9823 { BUILTIN_REGULAR "kill" , killcmd },
9825 #if ENABLE_FEATURE_SH_MATH
9826 { BUILTIN_NOSPEC "let" , letcmd },
9828 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9829 #if ENABLE_ASH_PRINTF
9830 { BUILTIN_REGULAR "printf" , printfcmd },
9832 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9833 { BUILTIN_REGULAR "read" , readcmd },
9834 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9835 { BUILTIN_SPEC_REG "return" , returncmd },
9836 { BUILTIN_SPEC_REG "set" , setcmd },
9837 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9839 { BUILTIN_SPEC_REG "source" , dotcmd },
9842 { BUILTIN_REGULAR "test" , testcmd },
9844 { BUILTIN_SPEC_REG "times" , timescmd },
9845 { BUILTIN_SPEC_REG "trap" , trapcmd },
9846 { BUILTIN_REGULAR "true" , truecmd },
9847 { BUILTIN_NOSPEC "type" , typecmd },
9848 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9849 { BUILTIN_REGULAR "umask" , umaskcmd },
9850 #if ENABLE_ASH_ALIAS
9851 { BUILTIN_REGULAR "unalias" , unaliascmd },
9853 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9854 { BUILTIN_REGULAR "wait" , waitcmd },
9857 /* Should match the above table! */
9858 #define COMMANDCMD (builtintab + \
9860 /* [ */ 1 * ENABLE_ASH_TEST + \
9861 /* [[ */ 1 * BASH_TEST2 + \
9862 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9863 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9864 /* break cd cddir */ 3)
9865 #define EVALCMD (COMMANDCMD + \
9866 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9867 /* continue */ 1 + \
9868 /* echo */ 1 * ENABLE_ASH_ECHO + \
9870 #define EXECCMD (EVALCMD + \
9874 * Search the table of builtin commands.
9877 pstrcmp1(const void *a, const void *b)
9879 return strcmp((char*)a, *(char**)b + 1);
9881 static struct builtincmd *
9882 find_builtin(const char *name)
9884 struct builtincmd *bp;
9887 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9894 * Execute a simple command.
9897 isassignment(const char *p)
9899 const char *q = endofname(p);
9904 static int FAST_FUNC
9905 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9907 /* Preserve exitstatus of a previous possible redirection
9908 * as POSIX mandates */
9909 return back_exitstatus;
9912 evalcommand(union node *cmd, int flags)
9914 static const struct builtincmd null_bltin = {
9915 "\0\0", bltincmd /* why three NULs? */
9917 struct localvar_list *localvar_stop;
9918 struct redirtab *redir_stop;
9919 struct stackmark smark;
9921 struct arglist arglist;
9922 struct arglist varlist;
9925 const struct strlist *sp;
9926 struct cmdentry cmdentry;
9933 smallint cmd_is_exec;
9935 errlinno = lineno = cmd->ncmd.linno;
9937 lineno -= funcline - 1;
9939 /* First expand the arguments. */
9940 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9941 setstackmark(&smark);
9942 localvar_stop = pushlocalvars();
9943 back_exitstatus = 0;
9945 cmdentry.cmdtype = CMDBUILTIN;
9946 cmdentry.u.cmd = &null_bltin;
9947 varlist.lastp = &varlist.list;
9948 *varlist.lastp = NULL;
9949 arglist.lastp = &arglist.list;
9950 *arglist.lastp = NULL;
9953 if (cmd->ncmd.args) {
9954 struct builtincmd *bcmd;
9955 smallint pseudovarflag;
9957 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9958 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9960 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9961 struct strlist **spp;
9963 spp = arglist.lastp;
9964 if (pseudovarflag && isassignment(argp->narg.text))
9965 expandarg(argp, &arglist, EXP_VARTILDE);
9967 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9969 for (sp = *spp; sp; sp = sp->next)
9974 /* Reserve one extra spot at the front for shellexec. */
9975 nargv = stalloc(sizeof(char *) * (argc + 2));
9977 for (sp = arglist.list; sp; sp = sp->next) {
9978 TRACE(("evalcommand arg: %s\n", sp->text));
9979 *nargv++ = sp->text;
9984 if (iflag && funcline == 0 && argc > 0)
9985 lastarg = nargv[-1];
9987 expredir(cmd->ncmd.redirect);
9988 redir_stop = pushredir(cmd->ncmd.redirect);
9990 if (BASH_XTRACEFD && xflag) {
9991 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
9992 * we do not emulate this. We only use its value.
9994 const char *xtracefd = lookupvar("BASH_XTRACEFD");
9995 if (xtracefd && is_number(xtracefd))
9996 preverrout_fd = atoi(xtracefd);
9999 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10001 path = vpath.var_text;
10002 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10003 struct strlist **spp;
10006 spp = varlist.lastp;
10007 expandarg(argp, &varlist, EXP_VARTILDE);
10009 mklocal((*spp)->text);
10012 * Modify the command lookup path, if a PATH= assignment
10016 if (varcmp(p, path) == 0)
10020 /* Print the command if xflag is set. */
10022 const char *pfx = "";
10024 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10028 char *varval = sp->text;
10029 char *eq = strchrnul(varval, '=');
10032 fdprintf(preverrout_fd, "%s%.*s%s",
10034 (int)(eq - varval), varval,
10035 maybe_single_quote(eq)
10043 fdprintf(preverrout_fd, "%s%s",
10045 /* always quote if matches reserved word: */
10047 ? single_quote(sp->text)
10048 : maybe_single_quote(sp->text)
10053 safe_write(preverrout_fd, "\n", 1);
10059 /* Now locate the command. */
10061 int cmd_flag = DO_ERR;
10062 #if ENABLE_ASH_CMDCMD
10063 const char *oldpath = path + 5;
10067 find_command(argv[0], &cmdentry, cmd_flag, path);
10068 if (cmdentry.cmdtype == CMDUNKNOWN) {
10069 flush_stdout_stderr();
10074 /* implement bltin and command here */
10075 if (cmdentry.cmdtype != CMDBUILTIN)
10078 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10079 if (cmdentry.u.cmd == EXECCMD)
10081 #if ENABLE_ASH_CMDCMD
10082 if (cmdentry.u.cmd == COMMANDCMD) {
10084 nargv = parse_command_args(argv, &path);
10087 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10088 * nargv => "PROG". path is updated if -p.
10090 argc -= nargv - argv;
10092 cmd_flag |= DO_NOFUNC;
10101 exitstatus = status;
10103 /* We have a redirection error. */
10105 raise_exception(EXERROR);
10110 /* Execute the command. */
10111 switch (cmdentry.cmdtype) {
10114 #if ENABLE_FEATURE_SH_STANDALONE \
10115 && ENABLE_FEATURE_SH_NOFORK \
10117 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10118 * around run_nofork_applet() call.
10119 * (2) Should this check also be done in forkshell()?
10120 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10122 /* find_command() encodes applet_no as (-2 - applet_no) */
10123 int applet_no = (- cmdentry.u.index - 2);
10124 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10128 sv_environ = environ;
10129 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10131 * Run <applet>_main().
10132 * Signals (^C) can't interrupt here.
10133 * Otherwise we can mangle stdio or malloc internal state.
10134 * This makes applets which can run for a long time
10135 * and/or wait for user input ineligible for NOFORK:
10136 * for example, "yes" or "rm" (rm -i waits for input).
10138 status = run_nofork_applet(applet_no, argv);
10139 environ = sv_environ;
10141 * Try enabling NOFORK for "yes" applet.
10142 * ^C _will_ stop it (write returns EINTR),
10143 * but this causes stdout FILE to be stuck
10144 * and needing clearerr(). What if other applets
10145 * also can get EINTRs? Do we need to switch
10146 * our signals to SA_RESTART?
10148 /*clearerr(stdout);*/
10153 /* Can we avoid forking? For example, very last command
10154 * in a script or a subshell does not need forking,
10155 * we can just exec it.
10157 if (!(flags & EV_EXIT) || may_have_traps) {
10158 /* No, forking off a child is necessary */
10161 jp = makejob(/*cmd,*/ 1);
10162 if (forkshell(jp, cmd, FORK_FG) != 0) {
10164 status = waitforjob(jp);
10166 TRACE(("forked child exited with %d\n", status));
10171 /* fall through to exec'ing external program */
10173 listsetvar(varlist.list, VEXPORT|VSTACK);
10174 shellexec(argv[0], argv, path, cmdentry.u.index);
10178 if (spclbltin > 0 || argc == 0) {
10180 if (cmd_is_exec && argc > 1)
10181 listsetvar(varlist.list, VEXPORT);
10184 /* Tight loop with builtins only:
10185 * "while kill -0 $child; do true; done"
10186 * will never exit even if $child died, unless we do this
10187 * to reap the zombie and make kill detect that it's gone: */
10188 dowait(DOWAIT_NONBLOCK, NULL);
10190 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10191 if (exception_type == EXERROR && spclbltin <= 0) {
10196 longjmp(exception_handler->loc, 1);
10202 /* See above for the rationale */
10203 dowait(DOWAIT_NONBLOCK, NULL);
10204 if (evalfun(cmdentry.u.func, argc, argv, flags))
10207 status = exitstatus;
10212 if (cmd->ncmd.redirect)
10213 popredir(/*drop:*/ cmd_is_exec);
10214 unwindredir(redir_stop);
10215 unwindlocalvars(localvar_stop);
10217 /* dsl: I think this is intended to be used to support
10218 * '_' in 'vi' command mode during line editing...
10219 * However I implemented that within libedit itself.
10221 setvar0("_", lastarg);
10223 popstackmark(&smark);
10229 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10231 char *volatile savecmdname;
10232 struct jmploc *volatile savehandler;
10233 struct jmploc jmploc;
10237 savecmdname = commandname;
10238 savehandler = exception_handler;
10239 i = setjmp(jmploc.loc);
10242 exception_handler = &jmploc;
10243 commandname = argv[0];
10245 optptr = NULL; /* initialize nextopt */
10246 if (cmd == EVALCMD)
10247 status = evalcmd(argc, argv, flags);
10249 status = (*cmd->builtin)(argc, argv);
10250 flush_stdout_stderr();
10251 status |= ferror(stdout);
10252 exitstatus = status;
10255 commandname = savecmdname;
10256 exception_handler = savehandler;
10262 goodname(const char *p)
10264 return endofname(p)[0] == '\0';
10269 * Search for a command. This is called before we fork so that the
10270 * location of the command will be available in the parent as well as
10271 * the child. The check for "goodname" is an overly conservative
10272 * check that the name will not be subject to expansion.
10275 prehash(union node *n)
10277 struct cmdentry entry;
10279 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10280 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10284 /* ============ Builtin commands
10286 * Builtin commands whose functions are closely tied to evaluation
10287 * are implemented here.
10291 * Handle break and continue commands. Break, continue, and return are
10292 * all handled by setting the evalskip flag. The evaluation routines
10293 * above all check this flag, and if it is set they start skipping
10294 * commands rather than executing them. The variable skipcount is
10295 * the number of loops to break/continue, or the number of function
10296 * levels to return. (The latter is always 1.) It should probably
10297 * be an error to break out of more loops than exist, but it isn't
10298 * in the standard shell so we don't make it one here.
10300 static int FAST_FUNC
10301 breakcmd(int argc UNUSED_PARAM, char **argv)
10303 int n = argv[1] ? number(argv[1]) : 1;
10306 ash_msg_and_raise_error(msg_illnum, argv[1]);
10310 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10318 * This implements the input routines used by the parser.
10322 INPUT_PUSH_FILE = 1,
10323 INPUT_NOFILE_OK = 2,
10326 static smallint checkkwd;
10327 /* values of checkkwd variable */
10328 #define CHKALIAS 0x1
10331 #define CHKEOFMARK 0x8
10334 * Push a string back onto the input at this current parsefile level.
10335 * We handle aliases this way.
10337 #if !ENABLE_ASH_ALIAS
10338 #define pushstring(s, ap) pushstring(s)
10341 pushstring(char *s, struct alias *ap)
10343 struct strpush *sp;
10348 if (g_parsefile->strpush) {
10349 sp = ckzalloc(sizeof(*sp));
10350 sp->prev = g_parsefile->strpush;
10352 sp = &(g_parsefile->basestrpush);
10354 g_parsefile->strpush = sp;
10355 sp->prev_string = g_parsefile->next_to_pgetc;
10356 sp->prev_left_in_line = g_parsefile->left_in_line;
10357 sp->unget = g_parsefile->unget;
10358 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10359 #if ENABLE_ASH_ALIAS
10362 ap->flag |= ALIASINUSE;
10366 g_parsefile->next_to_pgetc = s;
10367 g_parsefile->left_in_line = len;
10368 g_parsefile->unget = 0;
10375 struct strpush *sp = g_parsefile->strpush;
10378 #if ENABLE_ASH_ALIAS
10380 if (g_parsefile->next_to_pgetc[-1] == ' '
10381 || g_parsefile->next_to_pgetc[-1] == '\t'
10383 checkkwd |= CHKALIAS;
10385 if (sp->string != sp->ap->val) {
10388 sp->ap->flag &= ~ALIASINUSE;
10389 if (sp->ap->flag & ALIASDEAD) {
10390 unalias(sp->ap->name);
10394 g_parsefile->next_to_pgetc = sp->prev_string;
10395 g_parsefile->left_in_line = sp->prev_left_in_line;
10396 g_parsefile->unget = sp->unget;
10397 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10398 g_parsefile->strpush = sp->prev;
10399 if (sp != &(g_parsefile->basestrpush))
10408 char *buf = g_parsefile->buf;
10410 g_parsefile->next_to_pgetc = buf;
10411 #if ENABLE_FEATURE_EDITING
10413 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10414 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10416 # if ENABLE_ASH_IDLE_TIMEOUT
10419 const char *tmout_var = lookupvar("TMOUT");
10421 timeout = atoi(tmout_var) * 1000;
10426 line_input_state->timeout = timeout;
10428 # if ENABLE_FEATURE_TAB_COMPLETION
10429 line_input_state->path_lookup = pathval();
10431 reinit_unicode_for_ash();
10432 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10434 /* ^C pressed, "convert" to SIGINT */
10435 write(STDOUT_FILENO, "^C", 2);
10436 if (trap[SIGINT]) {
10442 exitstatus = 128 + SIGINT;
10448 /* Ctrl+D pressed */
10451 # if ENABLE_ASH_IDLE_TIMEOUT
10452 else if (errno == EAGAIN && timeout > 0) {
10453 puts("\007timed out waiting for input: auto-logout");
10460 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10463 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10465 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10466 int flags = fcntl(0, F_GETFL);
10467 if (flags >= 0 && (flags & O_NONBLOCK)) {
10468 flags &= ~O_NONBLOCK;
10469 if (fcntl(0, F_SETFL, flags) >= 0) {
10470 out2str("sh: turning off NDELAY mode\n");
10481 * Refill the input buffer and return the next input character:
10483 * 1) If a string was pushed back on the input, pop it;
10484 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10485 * or we are reading from a string so we can't refill the buffer,
10487 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10488 * 4) Process input up to the next newline, deleting nul characters.
10490 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10491 #define pgetc_debug(...) ((void)0)
10492 static int pgetc(void);
10499 if (g_parsefile->strpush) {
10500 #if ENABLE_ASH_ALIAS
10501 if (g_parsefile->left_in_line == -1
10502 && g_parsefile->strpush->ap
10503 && g_parsefile->next_to_pgetc[-1] != ' '
10504 && g_parsefile->next_to_pgetc[-1] != '\t'
10506 pgetc_debug("preadbuffer PEOA");
10513 /* on both branches above g_parsefile->left_in_line < 0.
10514 * "pgetc" needs refilling.
10517 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10518 * pungetc() may increment it a few times.
10519 * Assuming it won't increment it to less than -90.
10521 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10522 pgetc_debug("preadbuffer PEOF1");
10523 /* even in failure keep left_in_line and next_to_pgetc
10524 * in lock step, for correct multi-layer pungetc.
10525 * left_in_line was decremented before preadbuffer(),
10526 * must inc next_to_pgetc: */
10527 g_parsefile->next_to_pgetc++;
10531 more = g_parsefile->left_in_buffer;
10533 flush_stdout_stderr();
10537 /* don't try reading again */
10538 g_parsefile->left_in_line = -99;
10539 pgetc_debug("preadbuffer PEOF2");
10540 g_parsefile->next_to_pgetc++;
10545 /* Find out where's the end of line.
10546 * Set g_parsefile->left_in_line
10547 * and g_parsefile->left_in_buffer acordingly.
10548 * NUL chars are deleted.
10550 q = g_parsefile->next_to_pgetc;
10558 memmove(q, q + 1, more);
10562 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10568 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10569 if (g_parsefile->left_in_line < 0)
10574 g_parsefile->left_in_buffer = more;
10579 out2str(g_parsefile->next_to_pgetc);
10583 pgetc_debug("preadbuffer at %d:%p'%s'",
10584 g_parsefile->left_in_line,
10585 g_parsefile->next_to_pgetc,
10586 g_parsefile->next_to_pgetc);
10587 return (unsigned char)*g_parsefile->next_to_pgetc++;
10593 g_parsefile->linno++;
10594 setprompt_if(doprompt, 2);
10599 g_parsefile->linno++;
10600 needprompt = doprompt;
10608 pgetc_debug("pgetc at %d:%p'%s'",
10609 g_parsefile->left_in_line,
10610 g_parsefile->next_to_pgetc,
10611 g_parsefile->next_to_pgetc);
10612 if (g_parsefile->unget)
10613 return g_parsefile->lastc[--g_parsefile->unget];
10615 if (--g_parsefile->left_in_line >= 0)
10616 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10620 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10621 g_parsefile->lastc[0] = c;
10626 #if ENABLE_ASH_ALIAS
10628 pgetc_without_PEOA(void)
10632 pgetc_debug("pgetc at %d:%p'%s'",
10633 g_parsefile->left_in_line,
10634 g_parsefile->next_to_pgetc,
10635 g_parsefile->next_to_pgetc);
10637 } while (c == PEOA);
10641 # define pgetc_without_PEOA() pgetc()
10645 * Undo a call to pgetc. Only two characters may be pushed back.
10646 * PEOF may be pushed back.
10651 g_parsefile->unget++;
10654 /* This one eats backslash+newline */
10660 while ((c = pgetc()) == '\\') {
10661 if (pgetc() != '\n') {
10673 * To handle the "." command, a stack of input files is used. Pushfile
10674 * adds a new entry to the stack and popfile restores the previous level.
10679 struct parsefile *pf;
10681 pf = ckzalloc(sizeof(*pf));
10682 pf->prev = g_parsefile;
10684 /*pf->strpush = NULL; - ckzalloc did it */
10685 /*pf->basestrpush.prev = NULL;*/
10693 struct parsefile *pf = g_parsefile;
10699 if (pf->pf_fd >= 0)
10702 while (pf->strpush)
10704 g_parsefile = pf->prev;
10710 * Return to top level.
10715 while (g_parsefile != &basepf)
10720 * Close the file(s) that the shell is reading commands from. Called
10721 * after a fork is done.
10727 if (g_parsefile->pf_fd > 0) {
10728 close(g_parsefile->pf_fd);
10729 g_parsefile->pf_fd = 0;
10734 * Like setinputfile, but takes an open file descriptor. Call this with
10738 setinputfd(int fd, int push)
10742 g_parsefile->buf = NULL;
10744 g_parsefile->pf_fd = fd;
10745 if (g_parsefile->buf == NULL)
10746 g_parsefile->buf = ckmalloc(IBUFSIZ);
10747 g_parsefile->left_in_buffer = 0;
10748 g_parsefile->left_in_line = 0;
10749 g_parsefile->linno = 1;
10753 * Set the input to take input from a file. If push is set, push the
10754 * old input onto the stack first.
10757 setinputfile(const char *fname, int flags)
10762 fd = open(fname, O_RDONLY | O_CLOEXEC);
10764 if (flags & INPUT_NOFILE_OK)
10767 ash_msg_and_raise_perror("can't open '%s'", fname);
10771 else if (O_CLOEXEC == 0) /* old libc */
10772 close_on_exec_on(fd);
10774 setinputfd(fd, flags & INPUT_PUSH_FILE);
10781 * Like setinputfile, but takes input from a string.
10784 setinputstring(char *string)
10788 g_parsefile->next_to_pgetc = string;
10789 g_parsefile->left_in_line = strlen(string);
10790 g_parsefile->buf = NULL;
10791 g_parsefile->linno = 1;
10797 * Routines to check for mail.
10800 #if ENABLE_ASH_MAIL
10802 /* Hash of mtimes of mailboxes */
10803 static unsigned mailtime_hash;
10804 /* Set if MAIL or MAILPATH is changed. */
10805 static smallint mail_var_path_changed;
10808 * Print appropriate message(s) if mail has arrived.
10809 * If mail_var_path_changed is set,
10810 * then the value of MAIL has mail_var_path_changed,
10811 * so we just update the values.
10820 struct stackmark smark;
10823 setstackmark(&smark);
10824 mpath = mpathset() ? mpathval() : mailval();
10827 p = path_advance(&mpath, nullstr);
10832 for (q = p; *q; q++)
10838 q[-1] = '\0'; /* delete trailing '/' */
10839 if (stat(p, &statb) < 0) {
10842 /* Very simplistic "hash": just a sum of all mtimes */
10843 new_hash += (unsigned)statb.st_mtime;
10845 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10846 if (mailtime_hash != 0)
10847 out2str("you have mail\n");
10848 mailtime_hash = new_hash;
10850 mail_var_path_changed = 0;
10851 popstackmark(&smark);
10854 static void FAST_FUNC
10855 changemail(const char *val UNUSED_PARAM)
10857 mail_var_path_changed = 1;
10860 #endif /* ASH_MAIL */
10863 /* ============ ??? */
10866 * Set the shell parameters.
10869 setparam(char **argv)
10875 for (nparam = 0; argv[nparam]; nparam++)
10877 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10879 *ap++ = ckstrdup(*argv++);
10882 freeparam(&shellparam);
10883 shellparam.malloced = 1;
10884 shellparam.nparam = nparam;
10885 shellparam.p = newparam;
10886 #if ENABLE_ASH_GETOPTS
10887 shellparam.optind = 1;
10888 shellparam.optoff = -1;
10893 * Process shell options. The global variable argptr contains a pointer
10894 * to the argument list; we advance it past the options.
10896 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10897 * For a non-interactive shell, an error condition encountered
10898 * by a special built-in ... shall cause the shell to write a diagnostic message
10899 * to standard error and exit as shown in the following table:
10900 * Error Special Built-In
10902 * Utility syntax error (option or operand error) Shall exit
10904 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10905 * we see that bash does not do that (set "finishes" with error code 1 instead,
10906 * and shell continues), and people rely on this behavior!
10908 * set -o barfoo 2>/dev/null
10911 * Oh well. Let's mimic that.
10914 plus_minus_o(char *name, int val)
10919 for (i = 0; i < NOPTS; i++) {
10920 if (strcmp(name, optnames(i)) == 0) {
10925 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10928 for (i = 0; i < NOPTS; i++) {
10930 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10932 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10938 setoption(int flag, int val)
10942 for (i = 0; i < NOPTS; i++) {
10943 if (optletters(i) == flag) {
10948 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10952 options(int cmdline, int *login_sh)
10960 while ((p = *argptr) != NULL) {
10962 if (c != '-' && c != '+')
10965 val = 0; /* val = 0 if c == '+' */
10968 if (p[0] == '\0' || LONE_DASH(p)) {
10970 /* "-" means turn off -x and -v */
10973 /* "--" means reset params */
10974 else if (*argptr == NULL)
10977 break; /* "-" or "--" terminates options */
10980 /* first char was + or - */
10981 while ((c = *p++) != '\0') {
10982 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10983 if (c == 'c' && cmdline) {
10984 minusc = p; /* command is after shell args */
10985 } else if (c == 'o') {
10986 if (plus_minus_o(*argptr, val)) {
10987 /* it already printed err message */
10988 return 1; /* error */
10992 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10995 /* bash does not accept +-login, we also won't */
10996 } else if (cmdline && val && (c == '-')) { /* long options */
10997 if (strcmp(p, "login") == 0) {
11011 * The shift builtin command.
11013 static int FAST_FUNC
11014 shiftcmd(int argc UNUSED_PARAM, char **argv)
11021 n = number(argv[1]);
11022 if (n > shellparam.nparam)
11025 shellparam.nparam -= n;
11026 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11027 if (shellparam.malloced)
11030 ap2 = shellparam.p;
11031 while ((*ap2++ = *ap1++) != NULL)
11033 #if ENABLE_ASH_GETOPTS
11034 shellparam.optind = 1;
11035 shellparam.optoff = -1;
11042 * POSIX requires that 'set' (but not export or readonly) output the
11043 * variables in lexicographic order - by the locale's collating order (sigh).
11044 * Maybe we could keep them in an ordered balanced binary tree
11045 * instead of hashed lists.
11046 * For now just roll 'em through qsort for printing...
11049 showvars(const char *sep_prefix, int on, int off)
11052 char **ep, **epend;
11054 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11055 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11057 sep = *sep_prefix ? " " : sep_prefix;
11059 for (; ep < epend; ep++) {
11063 p = endofname(*ep);
11064 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11065 * makes "export -p" to have output not suitable for "eval":
11067 * os.environ["test-test"]="test"
11068 * if os.fork() == 0:
11069 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11070 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11074 q = single_quote(++p);
11075 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11081 * The set command builtin.
11083 static int FAST_FUNC
11084 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11089 return showvars(nullstr, 0, VUNSET);
11092 retval = options(/*cmdline:*/ 0, NULL);
11093 if (retval == 0) { /* if no parse error... */
11095 if (*argptr != NULL) {
11103 #if ENABLE_ASH_RANDOM_SUPPORT
11104 static void FAST_FUNC
11105 change_random(const char *value)
11109 if (value == NULL) {
11110 /* "get", generate */
11111 t = next_random(&random_gen);
11112 /* set without recursion */
11113 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11114 vrandom.flags &= ~VNOFUNC;
11117 t = strtoul(value, NULL, 10);
11118 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11123 #if ENABLE_ASH_GETOPTS
11125 getopts(char *optstr, char *optvar, char **optfirst)
11132 int ind = shellparam.optind;
11133 int off = shellparam.optoff;
11137 shellparam.optind = -1;
11138 optnext = optfirst + ind - 1;
11140 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11143 p = optnext[-1] + off;
11144 if (p == NULL || *p == '\0') {
11145 /* Current word is done, advance */
11147 if (p == NULL || *p != '-' || *++p == '\0') {
11149 unsetvar("OPTARG");
11155 if (LONE_DASH(p)) /* check for "--" */
11160 for (q = optstr; *q != c;) {
11162 /* OPTERR is a bashism */
11163 const char *cp = lookupvar("OPTERR");
11164 if ((cp && LONE_CHAR(cp, '0'))
11165 || (optstr[0] == ':')
11168 /*sbuf[1] = '\0'; - already is */
11169 setvar0("OPTARG", sbuf);
11171 fprintf(stderr, "Illegal option -%c\n", c);
11172 unsetvar("OPTARG");
11182 if (*p == '\0' && (p = *optnext) == NULL) {
11183 /* OPTERR is a bashism */
11184 const char *cp = lookupvar("OPTERR");
11185 if ((cp && LONE_CHAR(cp, '0'))
11186 || (optstr[0] == ':')
11189 /*sbuf[1] = '\0'; - already is */
11190 setvar0("OPTARG", sbuf);
11193 fprintf(stderr, "No arg for -%c option\n", c);
11194 unsetvar("OPTARG");
11202 setvar0("OPTARG", p);
11205 setvar0("OPTARG", nullstr);
11207 ind = optnext - optfirst + 1;
11208 setvar("OPTIND", itoa(ind), VNOFUNC);
11210 /*sbuf[1] = '\0'; - already is */
11211 setvar0(optvar, sbuf);
11213 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11214 shellparam.optind = ind;
11220 * The getopts builtin. Shellparam.optnext points to the next argument
11221 * to be processed. Shellparam.optptr points to the next character to
11222 * be processed in the current argument. If shellparam.optnext is NULL,
11223 * then it's the first time getopts has been called.
11225 static int FAST_FUNC
11226 getoptscmd(int argc, char **argv)
11231 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11233 optbase = shellparam.p;
11234 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11235 shellparam.optind = 1;
11236 shellparam.optoff = -1;
11239 optbase = &argv[3];
11240 if ((unsigned)shellparam.optind > argc - 2) {
11241 shellparam.optind = 1;
11242 shellparam.optoff = -1;
11246 return getopts(argv[1], argv[2], optbase);
11248 #endif /* ASH_GETOPTS */
11251 /* ============ Shell parser */
11254 struct heredoc *next; /* next here document in list */
11255 union node *here; /* redirection node */
11256 char *eofmark; /* string indicating end of input */
11257 smallint striptabs; /* if set, strip leading tabs */
11260 static smallint tokpushback; /* last token pushed back */
11261 static smallint quoteflag; /* set if (part of) last token was quoted */
11262 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11263 static struct heredoc *heredoclist; /* list of here documents to read */
11264 static char *wordtext; /* text of last word returned by readtoken */
11265 static struct nodelist *backquotelist;
11266 static union node *redirnode;
11267 static struct heredoc *heredoc;
11269 static const char *
11270 tokname(char *buf, int tok)
11273 return tokname_array[tok];
11274 sprintf(buf, "\"%s\"", tokname_array[tok]);
11278 /* raise_error_unexpected_syntax:
11279 * Called when an unexpected token is read during the parse. The argument
11280 * is the token that is expected, or -1 if more than one type of token can
11281 * occur at this point.
11283 static void raise_error_unexpected_syntax(int) NORETURN;
11285 raise_error_unexpected_syntax(int token)
11291 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11293 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11294 raise_error_syntax(msg);
11298 /* parsing is heavily cross-recursive, need these forward decls */
11299 static union node *andor(void);
11300 static union node *pipeline(void);
11301 static union node *parse_command(void);
11302 static void parseheredoc(void);
11303 static int peektoken(void);
11304 static int readtoken(void);
11306 static union node *
11309 union node *n1, *n2, *n3;
11314 switch (peektoken()) {
11322 if (!n1 && (nlflag & 1))
11328 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11329 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11335 if (tok == TBACKGND) {
11336 if (n2->type == NPIPE) {
11337 n2->npipe.pipe_backgnd = 1;
11339 if (n2->type != NREDIR) {
11340 n3 = stzalloc(sizeof(struct nredir));
11342 /*n3->nredir.redirect = NULL; - stzalloc did it */
11345 n2->type = NBACKGND;
11351 n3 = stzalloc(sizeof(struct nbinary));
11353 n3->nbinary.ch1 = n1;
11354 n3->nbinary.ch2 = n2;
11367 raise_error_unexpected_syntax(-1);
11374 static union node *
11377 union node *n1, *n2, *n3;
11385 } else if (t == TOR) {
11391 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11393 n3 = stzalloc(sizeof(struct nbinary));
11395 n3->nbinary.ch1 = n1;
11396 n3->nbinary.ch2 = n2;
11401 static union node *
11404 union node *n1, *n2, *pipenode;
11405 struct nodelist *lp, *prev;
11409 TRACE(("pipeline: entered\n"));
11410 if (readtoken() == TNOT) {
11412 checkkwd = CHKKWD | CHKALIAS;
11415 n1 = parse_command();
11416 if (readtoken() == TPIPE) {
11417 pipenode = stzalloc(sizeof(struct npipe));
11418 pipenode->type = NPIPE;
11419 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11420 lp = stzalloc(sizeof(struct nodelist));
11421 pipenode->npipe.cmdlist = lp;
11425 lp = stzalloc(sizeof(struct nodelist));
11426 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11427 lp->n = parse_command();
11429 } while (readtoken() == TPIPE);
11435 n2 = stzalloc(sizeof(struct nnot));
11443 static union node *
11448 n = stzalloc(sizeof(struct narg));
11450 /*n->narg.next = NULL; - stzalloc did it */
11451 n->narg.text = wordtext;
11452 n->narg.backquote = backquotelist;
11457 fixredir(union node *n, const char *text, int err)
11461 TRACE(("Fix redir %s %d\n", text, err));
11463 n->ndup.vname = NULL;
11465 fd = bb_strtou(text, NULL, 10);
11466 if (!errno && fd >= 0)
11467 n->ndup.dupfd = fd;
11468 else if (LONE_DASH(text))
11469 n->ndup.dupfd = -1;
11472 raise_error_syntax("bad fd number");
11473 n->ndup.vname = makename();
11480 union node *n = redirnode;
11482 if (n->type == NHERE)
11483 checkkwd = CHKEOFMARK;
11484 if (readtoken() != TWORD)
11485 raise_error_unexpected_syntax(-1);
11486 if (n->type == NHERE) {
11487 struct heredoc *here = heredoc;
11490 if (quoteflag == 0)
11492 TRACE(("Here document %d\n", n->type));
11493 rmescapes(wordtext, 0, NULL);
11494 here->eofmark = wordtext;
11496 if (heredoclist == NULL)
11497 heredoclist = here;
11499 for (p = heredoclist; p->next; p = p->next)
11503 } else if (n->type == NTOFD || n->type == NFROMFD) {
11504 fixredir(n, wordtext, 0);
11506 n->nfile.fname = makename();
11510 static union node *
11513 union node *args, **app;
11514 union node *n = NULL;
11515 union node *vars, **vpp;
11516 union node **rpp, *redir;
11520 smallint double_brackets_flag = 0;
11522 IF_BASH_FUNCTION(smallint function_flag = 0;)
11531 savecheckkwd = CHKALIAS;
11532 savelinno = g_parsefile->linno;
11535 checkkwd = savecheckkwd;
11540 if (peektoken() != TWORD)
11541 raise_error_unexpected_syntax(TWORD);
11546 case TAND: /* "&&" */
11547 case TOR: /* "||" */
11548 if (!double_brackets_flag) {
11552 wordtext = (char *) (t == TAND ? "-a" : "-o");
11555 n = stzalloc(sizeof(struct narg));
11557 /*n->narg.next = NULL; - stzalloc did it */
11558 n->narg.text = wordtext;
11560 if (strcmp("[[", wordtext) == 0)
11561 double_brackets_flag = 1;
11562 else if (strcmp("]]", wordtext) == 0)
11563 double_brackets_flag = 0;
11565 n->narg.backquote = backquotelist;
11566 if (savecheckkwd && isassignment(wordtext)) {
11568 vpp = &n->narg.next;
11571 app = &n->narg.next;
11575 if (function_flag) {
11576 checkkwd = CHKNL | CHKKWD;
11577 switch (peektoken()) {
11589 if (strcmp("[[", wordtext) == 0)
11593 raise_error_unexpected_syntax(-1);
11599 *rpp = n = redirnode;
11600 rpp = &n->nfile.next;
11601 parsefname(); /* read name of redirection file */
11604 IF_BASH_FUNCTION(do_func:)
11605 if (args && app == &args->narg.next
11608 struct builtincmd *bcmd;
11611 /* We have a function */
11612 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11613 raise_error_unexpected_syntax(TRP);
11614 name = n->narg.text;
11615 if (!goodname(name)
11616 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11618 raise_error_syntax("bad function name");
11621 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11622 n->ndefun.text = n->narg.text;
11623 n->ndefun.linno = g_parsefile->linno;
11624 n->ndefun.body = parse_command();
11627 IF_BASH_FUNCTION(function_flag = 0;)
11638 n = stzalloc(sizeof(struct ncmd));
11640 n->ncmd.linno = savelinno;
11641 n->ncmd.args = args;
11642 n->ncmd.assign = vars;
11643 n->ncmd.redirect = redir;
11647 static union node *
11648 parse_command(void)
11650 union node *n1, *n2;
11651 union node *ap, **app;
11652 union node *cp, **cpp;
11653 union node *redir, **rpp;
11661 savelinno = g_parsefile->linno;
11663 switch (readtoken()) {
11665 raise_error_unexpected_syntax(-1);
11668 n1 = stzalloc(sizeof(struct nif));
11670 n1->nif.test = list(0);
11671 if (readtoken() != TTHEN)
11672 raise_error_unexpected_syntax(TTHEN);
11673 n1->nif.ifpart = list(0);
11675 while (readtoken() == TELIF) {
11676 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11677 n2 = n2->nif.elsepart;
11679 n2->nif.test = list(0);
11680 if (readtoken() != TTHEN)
11681 raise_error_unexpected_syntax(TTHEN);
11682 n2->nif.ifpart = list(0);
11684 if (lasttoken == TELSE)
11685 n2->nif.elsepart = list(0);
11687 n2->nif.elsepart = NULL;
11695 n1 = stzalloc(sizeof(struct nbinary));
11696 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11697 n1->nbinary.ch1 = list(0);
11700 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11701 got == TWORD ? wordtext : ""));
11702 raise_error_unexpected_syntax(TDO);
11704 n1->nbinary.ch2 = list(0);
11709 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11710 raise_error_syntax("bad for loop variable");
11711 n1 = stzalloc(sizeof(struct nfor));
11713 n1->nfor.linno = savelinno;
11714 n1->nfor.var = wordtext;
11715 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11716 if (readtoken() == TIN) {
11718 while (readtoken() == TWORD) {
11719 n2 = stzalloc(sizeof(struct narg));
11721 /*n2->narg.next = NULL; - stzalloc did it */
11722 n2->narg.text = wordtext;
11723 n2->narg.backquote = backquotelist;
11725 app = &n2->narg.next;
11728 n1->nfor.args = ap;
11729 if (lasttoken != TNL && lasttoken != TSEMI)
11730 raise_error_unexpected_syntax(-1);
11732 n2 = stzalloc(sizeof(struct narg));
11734 /*n2->narg.next = NULL; - stzalloc did it */
11735 n2->narg.text = (char *)dolatstr;
11736 /*n2->narg.backquote = NULL;*/
11737 n1->nfor.args = n2;
11739 * Newline or semicolon here is optional (but note
11740 * that the original Bourne shell only allowed NL).
11742 if (lasttoken != TSEMI)
11745 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11746 if (readtoken() != TDO)
11747 raise_error_unexpected_syntax(TDO);
11748 n1->nfor.body = list(0);
11752 n1 = stzalloc(sizeof(struct ncase));
11754 n1->ncase.linno = savelinno;
11755 if (readtoken() != TWORD)
11756 raise_error_unexpected_syntax(TWORD);
11757 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11759 /*n2->narg.next = NULL; - stzalloc did it */
11760 n2->narg.text = wordtext;
11761 n2->narg.backquote = backquotelist;
11762 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11763 if (readtoken() != TIN)
11764 raise_error_unexpected_syntax(TIN);
11765 cpp = &n1->ncase.cases;
11767 checkkwd = CHKNL | CHKKWD;
11769 while (t != TESAC) {
11770 if (lasttoken == TLP)
11772 *cpp = cp = stzalloc(sizeof(struct nclist));
11774 app = &cp->nclist.pattern;
11776 *app = ap = stzalloc(sizeof(struct narg));
11778 /*ap->narg.next = NULL; - stzalloc did it */
11779 ap->narg.text = wordtext;
11780 ap->narg.backquote = backquotelist;
11781 if (readtoken() != TPIPE)
11783 app = &ap->narg.next;
11786 //ap->narg.next = NULL;
11787 if (lasttoken != TRP)
11788 raise_error_unexpected_syntax(TRP);
11789 cp->nclist.body = list(2);
11791 cpp = &cp->nclist.next;
11793 checkkwd = CHKNL | CHKKWD;
11797 raise_error_unexpected_syntax(TENDCASE);
11804 n1 = stzalloc(sizeof(struct nredir));
11805 n1->type = NSUBSHELL;
11806 n1->nredir.linno = savelinno;
11807 n1->nredir.n = list(0);
11808 /*n1->nredir.redirect = NULL; - stzalloc did it */
11815 IF_BASH_FUNCTION(case TFUNCTION:)
11819 return simplecmd();
11822 if (readtoken() != t)
11823 raise_error_unexpected_syntax(t);
11826 /* Now check for redirection which may follow command */
11827 checkkwd = CHKKWD | CHKALIAS;
11829 while (readtoken() == TREDIR) {
11830 *rpp = n2 = redirnode;
11831 rpp = &n2->nfile.next;
11837 if (n1->type != NSUBSHELL) {
11838 n2 = stzalloc(sizeof(struct nredir));
11840 n2->nredir.linno = savelinno;
11844 n1->nredir.redirect = redir;
11849 #if BASH_DOLLAR_SQUOTE
11851 decode_dollar_squote(void)
11853 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11859 p = strchr(C_escapes, c);
11864 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11868 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11870 } else if (c == 'x') { /* \xHH */
11874 } while (isxdigit(c) && --cnt);
11876 if (cnt == 3) { /* \x but next char is "bad" */
11880 } else { /* simple seq like \\ or \t */
11885 c = bb_process_escape_sequence((void*)&p);
11886 } else { /* unrecognized "\z": print both chars unless ' or " */
11887 if (c != '\'' && c != '"') {
11889 c |= 0x100; /* "please encode \, then me" */
11896 /* Used by expandstr to get here-doc like behaviour. */
11897 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11899 static ALWAYS_INLINE int
11900 realeofmark(const char *eofmark)
11902 return eofmark && eofmark != FAKEEOFMARK;
11906 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11907 * is not NULL, read a here document. In the latter case, eofmark is the
11908 * word which marks the end of the document and striptabs is true if
11909 * leading tabs should be stripped from the document. The argument c
11910 * is the first character of the input token or document.
11912 * Because C does not have internal subroutines, I have simulated them
11913 * using goto's to implement the subroutine linkage. The following macros
11914 * will run code that appears at the end of readtoken1.
11916 #define CHECKEND() {goto checkend; checkend_return:;}
11917 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11918 #define PARSESUB() {goto parsesub; parsesub_return:;}
11919 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11920 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11921 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11923 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11925 /* NB: syntax parameter fits into smallint */
11926 /* c parameter is an unsigned char or PEOF or PEOA */
11929 struct nodelist *bqlist;
11933 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11934 smallint pssyntax; /* we are expanding a prompt string */
11935 int varnest; /* levels of variables expansion */
11936 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11937 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11938 int dqvarnest; /* levels of variables expansion within double quotes */
11939 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11943 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11944 #if ENABLE_ASH_EXPAND_PRMT
11945 pssyntax = (syntax == PSSYNTAX);
11949 pssyntax = 0; /* constant */
11951 dblquote = (syntax == DQSYNTAX);
11953 IF_FEATURE_SH_MATH(arinest = 0;)
11954 IF_FEATURE_SH_MATH(parenlevel = 0;)
11957 STARTSTACKSTR(out);
11959 /* For each line, until end of word */
11960 CHECKEND(); /* set c to PEOF if at end of here document */
11961 for (;;) { /* until end of line or end of word */
11962 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11963 switch (SIT(c, syntax)) {
11964 case CNL: /* '\n' */
11965 if (syntax == BASESYNTAX)
11966 goto endword; /* exit outer loop */
11970 goto loop; /* continue outer loop */
11975 #if BASH_DOLLAR_SQUOTE
11976 if (c == '\\' && bash_dollar_squote) {
11977 c = decode_dollar_squote();
11979 /* skip $'\000', $'\x00' (like bash) */
11983 /* Unknown escape. Encode as '\z' */
11984 c = (unsigned char)c;
11985 if (eofmark == NULL || dblquote)
11986 USTPUTC(CTLESC, out);
11987 USTPUTC('\\', out);
11991 if (eofmark == NULL || dblquote)
11992 USTPUTC(CTLESC, out);
11995 case CBACK: /* backslash */
11996 c = pgetc_without_PEOA();
11998 USTPUTC(CTLESC, out);
11999 USTPUTC('\\', out);
12001 } else if (c == '\n') {
12004 if (pssyntax && c == '$') {
12005 USTPUTC(CTLESC, out);
12006 USTPUTC('\\', out);
12008 /* Backslash is retained if we are in "str"
12009 * and next char isn't dquote-special.
12015 && (c != '"' || eofmark != NULL)
12017 //dash survives not doing USTPUTC(CTLESC), but merely by chance:
12018 //Example: "\z" gets encoded as "\<CTLESC>z".
12019 //rmescapes() then emits "\", "\z", protecting z from globbing.
12020 //But it's wrong, should protect _both_ from globbing:
12021 //everything in double quotes is not globbed.
12022 //Unlike dash, we have a fix in rmescapes() which emits bare "z"
12023 //for "<CTLESC>z" since "z" is not glob-special (else unicode may break),
12024 //and glob would see "\z" and eat "\". Thus:
12025 USTPUTC(CTLESC, out); /* protect '\' from glob */
12026 USTPUTC('\\', out);
12028 USTPUTC(CTLESC, out);
12036 if (eofmark == NULL) {
12037 USTPUTC(CTLQUOTEMARK, out);
12045 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12046 if (eofmark != NULL && varnest == 0) {
12049 if (dqvarnest == 0) {
12050 syntax = BASESYNTAX;
12057 case CVAR: /* '$' */
12058 PARSESUB(); /* parse substitution */
12060 case CENDVAR: /* '}' */
12063 if (dqvarnest > 0) {
12070 #if ENABLE_FEATURE_SH_MATH
12071 case CLP: /* '(' in arithmetic */
12075 case CRP: /* ')' in arithmetic */
12076 if (parenlevel > 0) {
12079 if (pgetc_eatbnl() == ')') {
12081 if (--arinest == 0) {
12082 syntax = prevsyntax;
12086 * unbalanced parens
12087 * (don't 2nd guess - no error)
12095 case CBQUOTE: /* '`' */
12096 if (checkkwd & CHKEOFMARK) {
12105 goto endword; /* exit outer loop */
12109 if (varnest == 0) {
12110 #if BASH_REDIR_OUTPUT
12112 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12113 if (pgetc() == '>')
12114 c = 0x100 + '>'; /* flag &> */
12118 goto endword; /* exit outer loop */
12120 IF_ASH_ALIAS(if (c != PEOA))
12127 #if ENABLE_FEATURE_SH_MATH
12128 if (syntax == ARISYNTAX)
12129 raise_error_syntax("missing '))'");
12131 if (syntax != BASESYNTAX && eofmark == NULL)
12132 raise_error_syntax("unterminated quoted string");
12133 if (varnest != 0) {
12135 raise_error_syntax("missing '}'");
12137 USTPUTC('\0', out);
12138 len = out - (char *)stackblock();
12139 out = stackblock();
12140 if (eofmark == NULL) {
12141 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12144 if (isdigit_str9(out)) {
12145 PARSEREDIR(); /* passed as params: out, c */
12146 lasttoken = TREDIR;
12149 /* else: non-number X seen, interpret it
12150 * as "NNNX>file" = "NNNX >file" */
12154 quoteflag = quotef;
12155 backquotelist = bqlist;
12156 grabstackblock(len);
12160 /* end of readtoken routine */
12163 * Check to see whether we are at the end of the here document. When this
12164 * is called, c is set to the first character of the next input line. If
12165 * we are at the end of the here document, this routine sets the c to PEOF.
12168 if (realeofmark(eofmark)) {
12172 #if ENABLE_ASH_ALIAS
12174 c = pgetc_without_PEOA();
12177 while (c == '\t') {
12178 c = pgetc_without_PEOA();
12182 markloc = out - (char *)stackblock();
12183 for (p = eofmark; STPUTC(c, out), *p; p++) {
12187 c = pgetc_without_PEOA();
12190 if (c == '\n' || c == PEOF) {
12192 g_parsefile->linno++;
12193 needprompt = doprompt;
12198 p = (char *)stackblock() + markloc + 1;
12199 len_here = out - p;
12202 len_here -= (c >= PEOF);
12208 str = alloca(len_here + 1);
12209 *(char *)mempcpy(str, p, len_here) = '\0';
12211 pushstring(str, NULL);
12216 STADJUST((char *)stackblock() + markloc - out, out);
12218 goto checkend_return;
12222 * Parse a redirection operator. The variable "out" points to a string
12223 * specifying the fd to be redirected. The variable "c" contains the
12224 * first character of the redirection operator.
12227 /* out is already checked to be a valid number or "" */
12228 int fd = (*out == '\0' ? -1 : atoi(out));
12231 np = stzalloc(sizeof(struct nfile));
12234 c = pgetc_eatbnl();
12236 np->type = NAPPEND;
12238 np->type = NCLOBBER;
12241 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12247 #if BASH_REDIR_OUTPUT
12248 else if (c == 0x100 + '>') { /* this flags &> redirection */
12250 pgetc(); /* this is '>', no need to check */
12254 else { /* c == '<' */
12255 /*np->nfile.fd = 0; - stzalloc did it */
12256 c = pgetc_eatbnl();
12259 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12260 np = stzalloc(sizeof(struct nhere));
12261 /*np->nfile.fd = 0; - stzalloc did it */
12264 heredoc = stzalloc(sizeof(struct heredoc));
12265 heredoc->here = np;
12266 c = pgetc_eatbnl();
12268 heredoc->striptabs = 1;
12270 /*heredoc->striptabs = 0; - stzalloc did it */
12276 np->type = NFROMFD;
12280 np->type = NFROMTO;
12292 goto parseredir_return;
12296 * Parse a substitution. At this point, we have read the dollar sign
12297 * and nothing else.
12300 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12301 * (assuming ascii char codes, as the original implementation did) */
12302 #define is_special(c) \
12303 (((unsigned)(c) - 33 < 32) \
12304 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12306 unsigned char subtype;
12309 c = pgetc_eatbnl();
12310 if ((checkkwd & CHKEOFMARK)
12311 || c > 255 /* PEOA or PEOF */
12312 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12314 #if BASH_DOLLAR_SQUOTE
12315 if (syntax != DQSYNTAX && c == '\'')
12316 bash_dollar_squote = 1;
12321 } else if (c == '(') {
12322 /* $(command) or $((arith)) */
12323 if (pgetc_eatbnl() == '(') {
12324 #if ENABLE_FEATURE_SH_MATH
12327 raise_error_syntax("support for $((arith)) is disabled");
12334 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12335 USTPUTC(CTLVAR, out);
12336 typeloc = out - (char *)stackblock();
12338 subtype = VSNORMAL;
12340 c = pgetc_eatbnl();
12345 /* $[{[#]]NAME[}] */
12348 c = pgetc_eatbnl();
12349 } while (is_in_name(c));
12350 } else if (isdigit(c)) {
12351 /* $[{[#]]NUM[}] */
12354 c = pgetc_eatbnl();
12355 } while (isdigit(c));
12357 /* $[{[#]]<specialchar>[}] */
12360 c = pgetc_eatbnl();
12361 if (!subtype && cc == '#') {
12362 subtype = VSLENGTH;
12363 if (c == '_' || isalnum(c))
12366 c = pgetc_eatbnl();
12367 if (cc == '}' || c != '}') {
12375 if (!is_special(cc)) {
12376 if (subtype == VSLENGTH)
12384 if (c != '}' && subtype == VSLENGTH) {
12385 /* ${#VAR didn't end with } */
12389 if (subtype == 0) {
12390 static const char types[] ALIGN1 = "}-+?=";
12391 /* ${VAR...} but not $VAR or ${#VAR} */
12392 /* c == first char after VAR */
12395 c = pgetc_eatbnl();
12397 /* This check is only needed to not misinterpret
12398 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12401 if (!strchr(types, c)) {
12402 subtype = VSSUBSTR;
12404 break; /* "goto badsub" is bigger (!) */
12410 const char *p = strchr(types, c);
12413 subtype |= p - types + VSNORMAL;
12419 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12420 c = pgetc_eatbnl();
12426 #if BASH_PATTERN_SUBST
12428 /* ${v/[/]pattern/repl} */
12429 //TODO: encode pattern and repl separately.
12430 // Currently ${v/$var_with_slash/repl} is horribly broken
12431 subtype = VSREPLACE;
12432 c = pgetc_eatbnl();
12435 subtype++; /* VSREPLACEALL */
12443 ((unsigned char *)stackblock())[typeloc] = subtype;
12444 if (subtype != VSNORMAL) {
12451 goto parsesub_return;
12455 * Called to parse command substitutions. Newstyle is set if the command
12456 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12457 * list of commands (passed by reference), and savelen is the number of
12458 * characters on the top of the stack which must be preserved.
12461 struct nodelist **nlpp;
12465 smallint saveprompt = 0;
12468 savelen = out - (char *)stackblock();
12471 * FIXME: this can allocate very large block on stack and SEGV.
12473 * echo "..<100kbytes>..`true` $(true) `true` ..."
12474 * allocates 100kb for every command subst. With about
12475 * a hundred command substitutions stack overflows.
12476 * With larger prepended string, SEGV happens sooner.
12478 str = alloca(savelen);
12479 memcpy(str, stackblock(), savelen);
12483 /* We must read until the closing backquote, giving special
12484 * treatment to some slashes, and then push the string and
12485 * reread it as input, interpreting it normally.
12491 STARTSTACKSTR(pout);
12495 setprompt_if(needprompt, 2);
12496 pc = pgetc_eatbnl();
12502 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12503 if (pc != '\\' && pc != '`' && pc != '$'
12504 && (!dblquote || pc != '"')
12506 STPUTC('\\', pout);
12508 if (pc <= 255 /* not PEOA or PEOF */) {
12514 IF_ASH_ALIAS(case PEOA:)
12515 raise_error_syntax("EOF in backquote substitution");
12527 STPUTC('\0', pout);
12528 psavelen = pout - (char *)stackblock();
12529 if (psavelen > 0) {
12530 pstr = grabstackstr(pout);
12531 setinputstring(pstr);
12536 nlpp = &(*nlpp)->next;
12537 *nlpp = stzalloc(sizeof(**nlpp));
12538 /* (*nlpp)->next = NULL; - stzalloc did it */
12541 saveprompt = doprompt;
12548 doprompt = saveprompt;
12549 else if (readtoken() != TRP)
12550 raise_error_unexpected_syntax(TRP);
12555 * Start reading from old file again, ignoring any pushed back
12556 * tokens left from the backquote parsing
12561 while (stackblocksize() <= savelen)
12563 STARTSTACKSTR(out);
12565 memcpy(out, str, savelen);
12566 STADJUST(savelen, out);
12568 USTPUTC(CTLBACKQ, out);
12570 goto parsebackq_oldreturn;
12571 goto parsebackq_newreturn;
12574 #if ENABLE_FEATURE_SH_MATH
12576 * Parse an arithmetic expansion (indicate start of one and set state)
12579 if (++arinest == 1) {
12580 prevsyntax = syntax;
12581 syntax = ARISYNTAX;
12583 USTPUTC(CTLARI, out);
12584 goto parsearith_return;
12587 } /* end of readtoken */
12590 * Read the next input token.
12591 * If the token is a word, we set backquotelist to the list of cmds in
12592 * backquotes. We set quoteflag to true if any part of the word was
12594 * If the token is TREDIR, then we set redirnode to a structure containing
12597 * [Change comment: here documents and internal procedures]
12598 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12599 * word parsing code into a separate routine. In this case, readtoken
12600 * doesn't need to have any internal procedures, but parseword does.
12601 * We could also make parseoperator in essence the main routine, and
12602 * have parseword (readtoken1?) handle both words and redirection.]
12604 #define NEW_xxreadtoken
12605 #ifdef NEW_xxreadtoken
12606 /* singles must be first! */
12607 static const char xxreadtoken_chars[7] ALIGN1 = {
12608 '\n', '(', ')', /* singles */
12609 '&', '|', ';', /* doubles */
12613 #define xxreadtoken_singles 3
12614 #define xxreadtoken_doubles 3
12616 static const char xxreadtoken_tokens[] ALIGN1 = {
12617 TNL, TLP, TRP, /* only single occurrence allowed */
12618 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12619 TEOF, /* corresponds to trailing nul */
12620 TAND, TOR, TENDCASE /* if double occurrence */
12632 setprompt_if(needprompt, 2);
12633 for (;;) { /* until token or start of word found */
12634 c = pgetc_eatbnl();
12635 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12639 while ((c = pgetc()) != '\n' && c != PEOF)
12642 } else if (c == '\\') {
12643 break; /* return readtoken1(...) */
12647 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12653 p = strchr(xxreadtoken_chars, c);
12655 break; /* return readtoken1(...) */
12657 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12658 int cc = pgetc_eatbnl();
12659 if (cc == c) { /* double occurrence? */
12660 p += xxreadtoken_doubles + 1;
12663 #if BASH_REDIR_OUTPUT
12664 if (c == '&' && cc == '>') /* &> */
12665 break; /* return readtoken1(...) */
12670 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12675 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12677 #else /* old xxreadtoken */
12678 #define RETURN(token) return lasttoken = token
12688 setprompt_if(needprompt, 2);
12689 for (;;) { /* until token or start of word found */
12690 c = pgetc_eatbnl();
12692 case ' ': case '\t':
12693 IF_ASH_ALIAS(case PEOA:)
12696 while ((c = pgetc()) != '\n' && c != PEOF)
12706 if (pgetc_eatbnl() == '&')
12711 if (pgetc_eatbnl() == '|')
12716 if (pgetc_eatbnl() == ';')
12727 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12730 #endif /* old xxreadtoken */
12736 int kwd = checkkwd;
12738 smallint alreadyseen = tokpushback;
12741 #if ENABLE_ASH_ALIAS
12757 if (t != TWORD || quoteflag) {
12762 * check for keywords
12764 if (kwd & CHKKWD) {
12765 const char *const *pp;
12767 pp = findkwd(wordtext);
12769 lasttoken = t = pp - tokname_array;
12770 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12775 if (checkkwd & CHKALIAS) {
12776 #if ENABLE_ASH_ALIAS
12778 ap = lookupalias(wordtext, 1);
12781 pushstring(ap->val, ap);
12791 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12793 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12809 * Read and parse a command. Returns NODE_EOF on end of file.
12810 * (NULL is a valid parse tree indicating a blank line.)
12812 static union node *
12813 parsecmd(int interact)
12818 doprompt = interact;
12819 setprompt_if(doprompt, doprompt);
12825 * Input any here documents.
12830 struct heredoc *here;
12833 here = heredoclist;
12834 heredoclist = NULL;
12837 setprompt_if(needprompt, 2);
12838 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12839 here->eofmark, here->striptabs);
12840 n = stzalloc(sizeof(struct narg));
12841 n->narg.type = NARG;
12842 /*n->narg.next = NULL; - stzalloc did it */
12843 n->narg.text = wordtext;
12844 n->narg.backquote = backquotelist;
12845 here->here->nhere.doc = n;
12851 static const char *
12852 expandstr(const char *ps, int syntax_type)
12857 /* XXX Fix (char *) cast. */
12858 setinputstring((char *)ps);
12860 saveprompt = doprompt;
12863 /* readtoken1() might die horribly.
12864 * Try a prompt with syntactically wrong command:
12865 * PS1='$(date "+%H:%M:%S) > '
12868 volatile int saveint;
12869 struct jmploc *volatile savehandler = exception_handler;
12870 struct jmploc jmploc;
12872 if (setjmp(jmploc.loc) == 0) {
12873 exception_handler = &jmploc;
12874 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12876 exception_handler = savehandler;
12877 RESTORE_INT(saveint);
12880 doprompt = saveprompt;
12884 n.narg.type = NARG;
12885 n.narg.next = NULL;
12886 n.narg.text = wordtext;
12887 n.narg.backquote = backquotelist;
12889 expandarg(&n, NULL, EXP_QUOTED);
12890 return stackblock();
12896 return tokpushback && lasttoken == TEOF;
12900 * Execute a command or commands contained in a string.
12903 evalstring(char *s, int flags)
12905 struct jmploc *volatile savehandler;
12906 struct jmploc jmploc;
12910 struct stackmark smark;
12915 setstackmark(&smark);
12918 /* On exception inside execution loop, we must popfile().
12919 * Try interactively:
12921 * command eval "a=b" # throws "is read only" error
12922 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12923 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12925 savehandler = exception_handler;
12926 ex = setjmp(jmploc.loc);
12929 exception_handler = &jmploc;
12931 while ((n = parsecmd(0)) != NODE_EOF) {
12934 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12937 popstackmark(&smark);
12942 popstackmark(&smark);
12946 exception_handler = savehandler;
12948 longjmp(exception_handler->loc, ex);
12954 * The eval command.
12956 static int FAST_FUNC
12957 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12966 STARTSTACKSTR(concat);
12968 concat = stack_putstr(p, concat);
12972 STPUTC(' ', concat);
12974 STPUTC('\0', concat);
12975 p = grabstackstr(concat);
12977 return evalstring(p, flags & EV_TESTED);
12983 * Read and execute commands.
12984 * "Top" is nonzero for the top level command loop;
12985 * it turns on prompting if the shell is interactive.
12991 struct stackmark smark;
12996 TRACE(("cmdloop(%d) called\n", top));
13000 setstackmark(&smark);
13003 showjobs(SHOW_CHANGED|SHOW_STDERR);
13006 if (iflag && top) {
13010 n = parsecmd(inter);
13012 if (DEBUG > 2 && debug && (n != NODE_EOF))
13015 if (n == NODE_EOF) {
13016 if (!top || numeof >= 50)
13018 if (!stoppedjobs()) {
13021 out2str("\nUse \"exit\" to leave shell.\n");
13024 } else if (nflag == 0) {
13027 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13030 i = evaltree(n, 0);
13034 popstackmark(&smark);
13038 evalskip &= ~SKIPFUNC;
13046 * Take commands from a file. To be compatible we should do a path
13047 * search for the file, which is necessary to find sub-commands.
13050 find_dot_file(char *name)
13053 const char *path = pathval();
13056 /* don't try this for absolute or relative paths */
13057 if (strchr(name, '/'))
13060 while ((fullname = path_advance(&path, name)) != NULL) {
13061 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13063 * Don't bother freeing here, since it will
13064 * be freed by the caller.
13068 if (fullname != name)
13069 stunalloc(fullname);
13071 /* not found in PATH */
13073 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13076 ash_msg_and_raise_error("%s: not found", name);
13081 static int FAST_FUNC
13082 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13084 /* "false; . empty_file; echo $?" should print 0, not 1: */
13088 char *args_need_save;
13089 volatile struct shparam saveparam;
13092 // struct strlist *sp;
13093 // for (sp = cmdenviron; sp; sp = sp->next)
13094 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13096 nextopt(nullstr); /* handle possible "--" */
13100 /* bash says: "bash: .: filename argument required" */
13101 return 2; /* bash compat */
13104 /* This aborts if file isn't found, which is POSIXly correct.
13105 * bash returns exitcode 1 instead.
13107 fullname = find_dot_file(argv[0]);
13109 args_need_save = argv[0];
13110 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13112 saveparam = shellparam;
13113 shellparam.malloced = 0;
13117 shellparam.nparam = argc;
13118 shellparam.p = argv;
13121 /* This aborts if file can't be opened, which is POSIXly correct.
13122 * bash returns exitcode 1 instead.
13124 setinputfile(fullname, INPUT_PUSH_FILE);
13125 commandname = fullname;
13126 status = cmdloop(0);
13129 if (args_need_save) {
13130 freeparam(&shellparam);
13131 shellparam = saveparam;
13137 static int FAST_FUNC
13138 exitcmd(int argc UNUSED_PARAM, char **argv)
13143 exitstatus = number(argv[1]);
13144 raise_exception(EXEXIT);
13149 * Read a file containing shell functions.
13152 readcmdfile(char *name)
13154 setinputfile(name, INPUT_PUSH_FILE);
13160 /* ============ find_command inplementation */
13163 * Resolve a command name. If you change this routine, you may have to
13164 * change the shellexec routine as well.
13167 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13169 struct tblentry *cmdp;
13176 struct builtincmd *bcmd;
13178 /* If name contains a slash, don't use PATH or hash table */
13179 if (strchr(name, '/') != NULL) {
13180 entry->u.index = -1;
13181 if (act & DO_ABS) {
13182 while (stat(name, &statb) < 0) {
13184 if (errno == EINTR)
13187 entry->cmdtype = CMDUNKNOWN;
13191 entry->cmdtype = CMDNORMAL;
13195 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13197 updatetbl = (path == pathval());
13200 if (strstr(path, "%builtin") != NULL)
13201 act |= DO_ALTBLTIN;
13204 /* If name is in the table, check answer will be ok */
13205 cmdp = cmdlookup(name, 0);
13206 if (cmdp != NULL) {
13209 switch (cmdp->cmdtype) {
13227 } else if (cmdp->rehash == 0)
13228 /* if not invalidated by cd, we're done */
13232 /* If %builtin not in path, check for builtin next */
13233 bcmd = find_builtin(name);
13235 if (IS_BUILTIN_REGULAR(bcmd))
13236 goto builtin_success;
13237 if (act & DO_ALTPATH) {
13238 if (!(act & DO_ALTBLTIN))
13239 goto builtin_success;
13240 } else if (builtinloc <= 0) {
13241 goto builtin_success;
13245 #if ENABLE_FEATURE_SH_STANDALONE
13247 int applet_no = find_applet_by_name(name);
13248 if (applet_no >= 0) {
13249 entry->cmdtype = CMDNORMAL;
13250 entry->u.index = -2 - applet_no;
13256 /* We have to search path. */
13257 prev = -1; /* where to start */
13258 if (cmdp && cmdp->rehash) { /* doing a rehash */
13259 if (cmdp->cmdtype == CMDBUILTIN)
13262 prev = cmdp->param.index;
13268 while ((fullname = path_advance(&path, name)) != NULL) {
13269 stunalloc(fullname);
13270 /* NB: code below will still use fullname
13271 * despite it being "unallocated" */
13274 if (prefix(pathopt, "builtin")) {
13276 goto builtin_success;
13279 if ((act & DO_NOFUNC)
13280 || !prefix(pathopt, "func")
13281 ) { /* ignore unimplemented options */
13285 /* if rehash, don't redo absolute path names */
13286 if (fullname[0] == '/' && idx <= prev) {
13289 TRACE(("searchexec \"%s\": no change\n", name));
13292 while (stat(fullname, &statb) < 0) {
13294 if (errno == EINTR)
13297 if (errno != ENOENT && errno != ENOTDIR)
13301 e = EACCES; /* if we fail, this will be the error */
13302 if (!S_ISREG(statb.st_mode))
13304 if (pathopt) { /* this is a %func directory */
13305 stalloc(strlen(fullname) + 1);
13306 /* NB: stalloc will return space pointed by fullname
13307 * (because we don't have any intervening allocations
13308 * between stunalloc above and this stalloc) */
13309 readcmdfile(fullname);
13310 cmdp = cmdlookup(name, 0);
13311 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13312 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13313 stunalloc(fullname);
13316 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13318 entry->cmdtype = CMDNORMAL;
13319 entry->u.index = idx;
13323 cmdp = cmdlookup(name, 1);
13324 cmdp->cmdtype = CMDNORMAL;
13325 cmdp->param.index = idx;
13330 /* We failed. If there was an entry for this command, delete it */
13331 if (cmdp && updatetbl)
13332 delete_cmd_entry();
13333 if (act & DO_ERR) {
13334 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13335 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13336 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13338 argv[0] = (char*) "command_not_found_handle";
13341 evalfun(hookp->param.func, 2, argv, 0);
13342 entry->cmdtype = CMDUNKNOWN;
13346 ash_msg("%s: %s", name, errmsg(e, "not found"));
13348 entry->cmdtype = CMDUNKNOWN;
13353 entry->cmdtype = CMDBUILTIN;
13354 entry->u.cmd = bcmd;
13358 cmdp = cmdlookup(name, 1);
13359 cmdp->cmdtype = CMDBUILTIN;
13360 cmdp->param.cmd = bcmd;
13364 entry->cmdtype = cmdp->cmdtype;
13365 entry->u = cmdp->param;
13370 * The trap builtin.
13372 static int FAST_FUNC
13373 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13377 int signo, exitcode;
13382 for (signo = 0; signo < NSIG; signo++) {
13383 char *tr = trap_ptr[signo];
13385 /* note: bash adds "SIG", but only if invoked
13386 * as "bash". If called as "sh", or if set -o posix,
13387 * then it prints short signal names.
13388 * We are printing short names: */
13389 out1fmt("trap -- %s %s\n",
13391 get_signame(signo));
13392 /* trap_ptr != trap only if we are in special-cased `trap` code.
13393 * In this case, we will exit very soon, no need to free(). */
13394 /* if (trap_ptr != trap && tp[0]) */
13399 if (trap_ptr != trap) {
13407 /* Why the second check?
13408 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13409 * In this case, NUM is signal no, not an action.
13412 if (ap[1] && !is_number(ap[0]))
13417 signo = get_signum(*ap);
13419 /* Mimic bash message exactly */
13420 ash_msg("%s: invalid signal specification", *ap);
13426 if (LONE_DASH(action))
13429 if (action[0]) /* not NULL and not "" and not "-" */
13430 may_have_traps = 1;
13431 action = ckstrdup(action);
13435 trap[signo] = action;
13446 /* ============ Builtins */
13448 #if ENABLE_ASH_HELP
13449 static int FAST_FUNC
13450 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13456 "Built-in commands:\n"
13457 "------------------\n");
13458 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13459 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13460 builtintab[i].name + 1);
13466 # if ENABLE_FEATURE_SH_STANDALONE
13468 const char *a = applet_names;
13470 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13475 while (*a++ != '\0')
13480 newline_and_flush(stdout);
13481 return EXIT_SUCCESS;
13486 static int FAST_FUNC
13487 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13489 show_history(line_input_state);
13490 return EXIT_SUCCESS;
13495 * The export and readonly commands.
13497 static int FAST_FUNC
13498 exportcmd(int argc UNUSED_PARAM, char **argv)
13508 /* "readonly" in bash accepts, but ignores -n.
13509 * We do the same: it saves a conditional in nextopt's param.
13512 while ((opt = nextopt("np")) != '\0') {
13514 flag_off = VEXPORT;
13517 if (argv[0][0] == 'r') {
13519 flag_off = 0; /* readonly ignores -n */
13521 flag_off = ~flag_off;
13523 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13529 p = strchr(name, '=');
13533 vp = *findvar(hashvar(name), name);
13535 vp->flags = ((vp->flags | flag) & flag_off);
13539 setvar(name, p, (flag & flag_off));
13540 } while ((name = *++aptr) != NULL);
13545 /* No arguments. Show the list of exported or readonly vars.
13548 showvars(argv[0], flag, 0);
13553 * Delete a function if it exists.
13556 unsetfunc(const char *name)
13558 struct tblentry *cmdp;
13560 cmdp = cmdlookup(name, 0);
13561 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13562 delete_cmd_entry();
13566 * The unset builtin command. We unset the function before we unset the
13567 * variable to allow a function to be unset when there is a readonly variable
13568 * with the same name.
13570 static int FAST_FUNC
13571 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13577 while ((i = nextopt("vf")) != 0) {
13581 for (ap = argptr; *ap; ap++) {
13592 static const unsigned char timescmd_str[] ALIGN1 = {
13593 ' ', offsetof(struct tms, tms_utime),
13594 '\n', offsetof(struct tms, tms_stime),
13595 ' ', offsetof(struct tms, tms_cutime),
13596 '\n', offsetof(struct tms, tms_cstime),
13599 static int FAST_FUNC
13600 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13603 const unsigned char *p;
13606 clk_tck = bb_clk_tck();
13611 unsigned sec, frac;
13613 t = *(clock_t *)(((char *) &buf) + p[1]);
13615 frac = t % clk_tck;
13616 out1fmt("%um%u.%03us%c",
13617 sec / 60, sec % 60,
13618 (frac * 1000) / clk_tck,
13626 #if ENABLE_FEATURE_SH_MATH
13628 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13629 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13631 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13633 static int FAST_FUNC
13634 letcmd(int argc UNUSED_PARAM, char **argv)
13640 ash_msg_and_raise_error("expression expected");
13642 i = ash_arith(*argv);
13650 * The read builtin. Options:
13651 * -r Do not interpret '\' specially
13652 * -s Turn off echo (tty only)
13653 * -n NCHARS Read NCHARS max
13654 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13655 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13656 * -u FD Read from given FD instead of fd 0
13657 * -d DELIM End on DELIM char, not newline
13658 * This uses unbuffered input, which may be avoidable in some cases.
13659 * TODO: bash also has:
13660 * -a ARRAY Read into array[0],[1],etc
13661 * -e Use line editing (tty only)
13663 static int FAST_FUNC
13664 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13666 char *opt_n = NULL;
13667 char *opt_p = NULL;
13668 char *opt_t = NULL;
13669 char *opt_u = NULL;
13670 char *opt_d = NULL; /* optimized out if !BASH */
13671 int read_flags = 0;
13675 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13684 read_flags |= BUILTIN_READ_SILENT;
13690 read_flags |= BUILTIN_READ_RAW;
13705 /* "read -s" needs to save/restore termios, can't allow ^C
13706 * to jump out of it.
13710 r = shell_builtin_read(setvar0,
13712 bltinlookup("IFS"), /* can be NULL */
13722 if ((uintptr_t)r == 1 && errno == EINTR) {
13723 /* To get SIGCHLD: sleep 1 & read x; echo $x
13724 * Correct behavior is to not exit "read"
13726 if (pending_sig == 0)
13730 if ((uintptr_t)r > 1)
13731 ash_msg_and_raise_error(r);
13733 return (uintptr_t)r;
13736 static int FAST_FUNC
13737 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13739 static const char permuser[3] ALIGN1 = "ogu";
13742 int symbolic_mode = 0;
13744 while (nextopt("S") != '\0') {
13753 if (*argptr == NULL) {
13754 if (symbolic_mode) {
13755 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13762 *p++ = permuser[i];
13764 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13765 if (!(mask & 0400)) *p++ = 'r';
13766 if (!(mask & 0200)) *p++ = 'w';
13767 if (!(mask & 0100)) *p++ = 'x';
13775 out1fmt("%04o\n", mask);
13778 char *modestr = *argptr;
13779 /* numeric umasks are taken as-is */
13780 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13781 if (!isdigit(modestr[0]))
13783 mask = bb_parse_mode(modestr, mask);
13784 if ((unsigned)mask > 0777) {
13785 ash_msg_and_raise_error("illegal mode: %s", modestr);
13787 if (!isdigit(modestr[0]))
13794 static int FAST_FUNC
13795 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13797 return shell_builtin_ulimit(argv);
13800 /* ============ main() and helpers */
13803 * Called to exit the shell.
13812 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13813 save_history(line_input_state);
13815 status = exitstatus;
13816 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13817 if (setjmp(loc.loc)) {
13818 if (exception_type == EXEXIT)
13819 status = exitstatus;
13822 exception_handler = &loc;
13828 /*free(p); - we'll exit soon */
13831 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13832 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13835 flush_stdout_stderr();
13840 /* Don't inline: conserve stack of caller from having our locals too */
13841 static NOINLINE void
13844 /* we will never free this */
13845 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13848 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13849 setsignal(SIGCHLD);
13851 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13852 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13854 signal(SIGHUP, SIG_DFL);
13861 for (envp = environ; envp && *envp; envp++) {
13863 * p = endofname(*envp);
13864 * if (p != *envp && *p == '=') {
13865 * here to weed out badly-named variables, but this breaks
13866 * scenarios where people do want them passed to children:
13868 * os.environ["test-test"]="test"
13869 * if os.fork() == 0:
13870 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
13871 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
13873 if (strchr(*envp, '=')) {
13874 setvareq(*envp, VEXPORT|VTEXTFIXED);
13878 setvareq((char*)defoptindvar, VTEXTFIXED);
13880 setvar0("PPID", utoa(getppid()));
13882 p = lookupvar("SHLVL");
13883 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13885 #if BASH_HOSTNAME_VAR
13886 if (!lookupvar("HOSTNAME")) {
13887 struct utsname uts;
13889 setvar0("HOSTNAME", uts.nodename);
13892 p = lookupvar("PWD");
13894 struct stat st1, st2;
13895 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13896 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13906 //usage:#define ash_trivial_usage
13907 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13908 //usage:#define ash_full_usage "\n\n"
13909 //usage: "Unix shell interpreter"
13912 * Process the shell command line arguments.
13915 procargs(char **argv)
13918 const char *xminusc;
13923 login_sh = xargv[0] && xargv[0][0] == '-';
13925 /* if (xargv[0]) - mmm, this is always true! */
13927 for (i = 0; i < NOPTS; i++)
13930 if (options(/*cmdline:*/ 1, &login_sh)) {
13931 /* it already printed err message */
13932 raise_exception(EXERROR);
13936 if (*xargv == NULL) {
13938 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13941 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13945 for (i = 0; i < NOPTS; i++)
13946 if (optlist[i] == 2)
13951 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13956 } else if (!sflag) {
13957 setinputfile(*xargv, 0);
13960 commandname = arg0;
13963 shellparam.p = xargv;
13964 #if ENABLE_ASH_GETOPTS
13965 shellparam.optind = 1;
13966 shellparam.optoff = -1;
13968 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13970 shellparam.nparam++;
13979 * Read /etc/profile, ~/.profile, $ENV.
13982 read_profile(const char *name)
13984 name = expandstr(name, DQSYNTAX);
13985 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13992 * This routine is called when an error or an interrupt occurs in an
13993 * interactive shell and control is returned to the main command loop.
13994 * (In dash, this function is auto-generated by build machinery).
14003 /* from expand.c: */
14006 /* from input.c: */
14007 g_parsefile->left_in_buffer = 0;
14008 g_parsefile->left_in_line = 0; /* clear input buffer */
14011 /* from redir.c: */
14015 unwindlocalvars(NULL);
14019 static short profile_buf[16384];
14020 extern int etext();
14024 * Main routine. We initialize things, parse the arguments, execute
14025 * profiles if we're a login shell, and then call cmdloop to execute
14026 * commands. The setjmp call sets up the location to jump to when an
14027 * exception occurs. When an exception occurs the variable "state"
14028 * is used to figure out how far we had gotten.
14030 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14031 int ash_main(int argc UNUSED_PARAM, char **argv)
14033 volatile smallint state;
14034 struct jmploc jmploc;
14035 struct stackmark smark;
14038 /* Initialize global data */
14042 #if ENABLE_ASH_ALIAS
14048 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14051 #if ENABLE_FEATURE_EDITING
14052 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
14055 if (setjmp(jmploc.loc)) {
14061 e = exception_type;
14063 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14067 newline_and_flush(stderr);
14070 popstackmark(&smark);
14071 FORCE_INT_ON; /* enable interrupts */
14080 exception_handler = &jmploc;
14081 rootpid = getpid();
14084 setstackmark(&smark);
14085 login_sh = procargs(argv);
14087 TRACE(("Shell args: "));
14088 trace_puts_args(argv);
14095 read_profile("/etc/profile");
14098 hp = lookupvar("HOME");
14100 read_profile("$HOME/.profile");
14106 getuid() == geteuid() && getgid() == getegid() &&
14110 const char *shinit = lookupvar("ENV");
14111 if (shinit != NULL && *shinit != '\0')
14112 read_profile(shinit);
14114 popstackmark(&smark);
14118 /* evalstring pushes parsefile stack.
14119 * Ensure we don't falsely claim that 0 (stdin)
14120 * is one of stacked source fds.
14121 * Testcase: ash -c 'exec 1>&0' must not complain. */
14122 // if (!sflag) g_parsefile->pf_fd = -1;
14123 // ^^ not necessary since now we special-case fd 0
14124 // in save_fd_on_redirect()
14125 evalstring(minusc, sflag ? 0 : EV_EXIT);
14128 if (sflag || minusc == NULL) {
14129 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14131 const char *hp = lookupvar("HISTFILE");
14133 hp = lookupvar("HOME");
14136 hp = concat_path_file(hp, ".ash_history");
14137 setvar0("HISTFILE", hp);
14140 hp = lookupvar("HISTFILE");
14144 line_input_state->hist_file = hp;
14145 # if ENABLE_FEATURE_SH_HISTFILESIZE
14146 hp = lookupvar("HISTFILESIZE");
14147 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14151 state4: /* XXX ??? - why isn't this before the "if" statement */
14159 extern void _mcleanup(void);
14163 TRACE(("End of main reached\n"));
14170 * Copyright (c) 1989, 1991, 1993, 1994
14171 * The Regents of the University of California. All rights reserved.
14173 * This code is derived from software contributed to Berkeley by
14174 * Kenneth Almquist.
14176 * Redistribution and use in source and binary forms, with or without
14177 * modification, are permitted provided that the following conditions
14179 * 1. Redistributions of source code must retain the above copyright
14180 * notice, this list of conditions and the following disclaimer.
14181 * 2. Redistributions in binary form must reproduce the above copyright
14182 * notice, this list of conditions and the following disclaimer in the
14183 * documentation and/or other materials provided with the distribution.
14184 * 3. Neither the name of the University nor the names of its contributors
14185 * may be used to endorse or promote products derived from this software
14186 * without specific prior written permission.
14188 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14189 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14190 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14191 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14192 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14193 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14194 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14195 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14196 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14197 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF