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_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
192 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
193 /* Bionic at least up to version 24 has no glob() */
194 # undef ENABLE_ASH_INTERNAL_GLOB
195 # define ENABLE_ASH_INTERNAL_GLOB 1
198 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
199 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
200 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
201 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
202 # error glob() should unbackslash them and match. uClibc does not unbackslash,
203 # error fails to match dirname, subsequently not expanding <pattern> in it.
205 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
206 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
209 #if !ENABLE_ASH_INTERNAL_GLOB
214 #include "shell_common.h"
215 #if ENABLE_FEATURE_SH_MATH
218 #if ENABLE_ASH_RANDOM_SUPPORT
221 # define CLEAR_RANDOM_T(rnd) ((void)0)
224 #include "NUM_APPLETS.h"
226 /* STANDALONE does not make sense, and won't compile */
227 # undef CONFIG_FEATURE_SH_STANDALONE
228 # undef ENABLE_FEATURE_SH_STANDALONE
229 # undef IF_FEATURE_SH_STANDALONE
230 # undef IF_NOT_FEATURE_SH_STANDALONE
231 # define ENABLE_FEATURE_SH_STANDALONE 0
232 # define IF_FEATURE_SH_STANDALONE(...)
233 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
237 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
241 # error "Do not even bother, ash will not run on NOMMU machine"
245 /* ============ Hash table sizes. Configurable. */
249 #define CMDTABLESIZE 31 /* should be prime */
252 /* ============ Shell options */
254 static const char *const optletters_optnames[] = {
278 #define optletters(n) optletters_optnames[n][0]
279 #define optnames(n) (optletters_optnames[n] + 1)
281 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
284 /* ============ Misc data */
286 #define msg_illnum "Illegal number: %s"
289 * We enclose jmp_buf in a structure so that we can declare pointers to
290 * jump locations. The global variable handler contains the location to
291 * jump to when an exception occurs, and the global variable exception_type
292 * contains a code identifying the exception. To implement nested
293 * exception handlers, the user should save the value of handler on entry
294 * to an inner scope, set handler to point to a jmploc structure for the
295 * inner scope, and restore handler on exit from the scope.
301 struct globals_misc {
302 uint8_t exitstatus; /* exit status of last command */
303 uint8_t back_exitstatus;/* exit status of backquoted command */
304 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
305 int rootpid; /* pid of main shell */
306 /* shell level: 0 for the main shell, 1 for its children, and so on */
308 #define rootshell (!shlvl)
309 char *minusc; /* argument to -c option */
311 char *curdir; // = nullstr; /* current working directory */
312 char *physdir; // = nullstr; /* physical working directory */
314 char *arg0; /* value of $0 */
316 struct jmploc *exception_handler;
318 volatile int suppress_int; /* counter */
319 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
320 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
321 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
322 smallint exception_type; /* kind of exception (0..5) */
324 #define EXINT 0 /* SIGINT received */
325 #define EXERROR 1 /* a generic error */
326 #define EXEXIT 4 /* exit the shell */
329 char nullstr[1]; /* zero length string */
332 #define eflag optlist[0]
333 #define fflag optlist[1]
334 #define Iflag optlist[2]
335 #define iflag optlist[3]
336 #define mflag optlist[4]
337 #define nflag optlist[5]
338 #define sflag optlist[6]
339 #define xflag optlist[7]
340 #define vflag optlist[8]
341 #define Cflag optlist[9]
342 #define aflag optlist[10]
343 #define bflag optlist[11]
344 #define uflag optlist[12]
345 #define viflag optlist[13]
347 # define pipefail optlist[14]
352 # define nolog optlist[14 + BASH_PIPEFAIL]
353 # define debug optlist[15 + BASH_PIPEFAIL]
356 /* trap handler commands */
358 * Sigmode records the current value of the signal handlers for the various
359 * modes. A value of zero means that the current handler is not known.
360 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
362 char sigmode[NSIG - 1];
363 #define S_DFL 1 /* default signal handling (SIG_DFL) */
364 #define S_CATCH 2 /* signal is caught */
365 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
366 #define S_HARD_IGN 4 /* signal is ignored permanently */
368 /* indicates specified signal received */
369 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
370 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
372 char **trap_ptr; /* used only by "trap hack" */
374 /* Rarely referenced stuff */
375 #if ENABLE_ASH_RANDOM_SUPPORT
378 pid_t backgndpid; /* pid of last background process */
380 extern struct globals_misc *const ash_ptr_to_globals_misc;
381 #define G_misc (*ash_ptr_to_globals_misc)
382 #define exitstatus (G_misc.exitstatus )
383 #define back_exitstatus (G_misc.back_exitstatus )
384 #define job_warning (G_misc.job_warning)
385 #define rootpid (G_misc.rootpid )
386 #define shlvl (G_misc.shlvl )
387 #define minusc (G_misc.minusc )
388 #define curdir (G_misc.curdir )
389 #define physdir (G_misc.physdir )
390 #define arg0 (G_misc.arg0 )
391 #define exception_handler (G_misc.exception_handler)
392 #define exception_type (G_misc.exception_type )
393 #define suppress_int (G_misc.suppress_int )
394 #define pending_int (G_misc.pending_int )
395 #define got_sigchld (G_misc.got_sigchld )
396 #define pending_sig (G_misc.pending_sig )
397 #define isloginsh (G_misc.isloginsh )
398 #define nullstr (G_misc.nullstr )
399 #define optlist (G_misc.optlist )
400 #define sigmode (G_misc.sigmode )
401 #define gotsig (G_misc.gotsig )
402 #define may_have_traps (G_misc.may_have_traps )
403 #define trap (G_misc.trap )
404 #define trap_ptr (G_misc.trap_ptr )
405 #define random_gen (G_misc.random_gen )
406 #define backgndpid (G_misc.backgndpid )
407 #define INIT_G_misc() do { \
408 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
416 /* ============ DEBUG */
418 static void trace_printf(const char *fmt, ...);
419 static void trace_vprintf(const char *fmt, va_list va);
420 # define TRACE(param) trace_printf param
421 # define TRACEV(param) trace_vprintf param
422 # define close(fd) do { \
424 if (close(dfd) < 0) \
425 bb_error_msg("bug on %d: closing %d(0x%x)", \
426 __LINE__, dfd, dfd); \
429 # define TRACE(param)
430 # define TRACEV(param)
434 /* ============ Utility functions */
435 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
436 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
439 isdigit_str9(const char *str)
441 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
442 while (--maxlen && isdigit(*str))
444 return (*str == '\0');
448 var_end(const char *var)
457 /* ============ Interrupts / exceptions */
459 static void exitshell(void) NORETURN;
462 * These macros allow the user to suspend the handling of interrupt signals
463 * over a period of time. This is similar to SIGHOLD or to sigblock, but
464 * much more efficient and portable. (But hacking the kernel is so much
465 * more fun than worrying about efficiency and portability. :-))
468 # define INT_OFF do { \
469 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
474 # define INT_OFF do { \
481 * Called to raise an exception. Since C doesn't include exceptions, we
482 * just do a longjmp to the exception handler. The type of exception is
483 * stored in the global variable "exception_type".
485 static void raise_exception(int) NORETURN;
487 raise_exception(int e)
490 if (exception_handler == NULL)
495 longjmp(exception_handler->loc, 1);
498 #define raise_exception(e) do { \
499 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
500 raise_exception(e); \
505 * Called when a SIGINT is received. (If the user specifies
506 * that SIGINT is to be trapped or ignored using the trap builtin, then
507 * this routine is not called.) Suppressint is nonzero when interrupts
508 * are held using the INT_OFF macro. (The test for iflag is just
509 * defensive programming.)
511 static void raise_interrupt(void) NORETURN;
513 raise_interrupt(void)
516 /* Signal is not automatically unmasked after it is raised,
517 * do it ourself - unmask all signals */
518 sigprocmask_allsigs(SIG_UNBLOCK);
519 /* pending_sig = 0; - now done in signal_handler() */
521 if (!(rootshell && iflag)) {
522 /* Kill ourself with SIGINT */
523 signal(SIGINT, SIG_DFL);
526 /* bash: ^C even on empty command line sets $? */
527 exitstatus = SIGINT + 128;
528 raise_exception(EXINT);
532 #define raise_interrupt() do { \
533 TRACE(("raising interrupt on line %d\n", __LINE__)); \
538 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
542 if (--suppress_int == 0 && pending_int) {
547 # define INT_ON do { \
548 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
552 # define INT_ON int_on()
554 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
562 #define FORCE_INT_ON force_int_on()
564 #define SAVE_INT(v) ((v) = suppress_int)
566 #define RESTORE_INT(v) do { \
568 suppress_int = (v); \
569 if (suppress_int == 0 && pending_int) \
574 /* ============ Stdout/stderr output */
577 outstr(const char *p, FILE *file)
585 flush_stdout_stderr(void)
592 /* Was called outcslow(c,FILE*), but c was always '\n' */
594 newline_and_flush(FILE *dest)
602 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
604 out1fmt(const char *fmt, ...)
611 r = vprintf(fmt, ap);
617 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
619 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
626 ret = vsnprintf(outbuf, length, fmt, ap);
633 out1str(const char *p)
639 out2str(const char *p)
642 flush_stdout_stderr();
646 /* ============ Parser structures */
648 /* control characters in argument strings */
649 #define CTL_FIRST CTLESC
650 #define CTLESC ((unsigned char)'\201') /* escape next character */
651 #define CTLVAR ((unsigned char)'\202') /* variable defn */
652 #define CTLENDVAR ((unsigned char)'\203')
653 #define CTLBACKQ ((unsigned char)'\204')
654 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
655 #define CTLENDARI ((unsigned char)'\207')
656 #define CTLQUOTEMARK ((unsigned char)'\210')
657 #define CTL_LAST CTLQUOTEMARK
659 /* variable substitution byte (follows CTLVAR) */
660 #define VSTYPE 0x0f /* type of variable substitution */
661 #define VSNUL 0x10 /* colon--treat the empty string as unset */
663 /* values of VSTYPE field */
664 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
665 #define VSMINUS 0x2 /* ${var-text} */
666 #define VSPLUS 0x3 /* ${var+text} */
667 #define VSQUESTION 0x4 /* ${var?message} */
668 #define VSASSIGN 0x5 /* ${var=text} */
669 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
670 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
671 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
672 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
673 #define VSLENGTH 0xa /* ${#var} */
675 #define VSSUBSTR 0xc /* ${var:position:length} */
677 #if BASH_PATTERN_SUBST
678 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
679 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
682 static const char dolatstr[] ALIGN1 = {
683 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
685 #define DOLATSTRLEN 6
704 #if BASH_REDIR_OUTPUT
721 smallint type; /* Nxxxx */
724 union node *redirect;
729 smallint pipe_backgnd;
730 struct nodelist *cmdlist;
736 union node *redirect;
749 union node *elsepart;
776 struct nodelist *backquote;
779 /* nfile and ndup layout must match!
780 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
781 * that it is actually NTO2 (>&file), and change its type.
798 char *_unused_expfname;
817 struct nredir nredir;
818 struct nbinary nbinary;
822 struct nclist nclist;
831 * NODE_EOF is returned by parsecmd when it encounters an end of file.
832 * It must be distinct from NULL.
834 #define NODE_EOF ((union node *) -1L)
837 struct nodelist *next;
850 freefunc(struct funcnode *f)
852 if (f && --f->count < 0)
857 /* ============ Debugging output */
861 static FILE *tracefile;
864 trace_printf(const char *fmt, ...)
871 fprintf(tracefile, "%u ", (int) time(NULL));
873 fprintf(tracefile, "[%u] ", (int) getpid());
875 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
877 vfprintf(tracefile, fmt, va);
882 trace_vprintf(const char *fmt, va_list va)
886 vfprintf(tracefile, fmt, va);
887 fprintf(tracefile, "\n");
891 trace_puts(const char *s)
899 trace_puts_quoted(char *s)
906 putc('"', tracefile);
907 for (p = s; *p; p++) {
908 switch ((unsigned char)*p) {
909 case '\n': c = 'n'; goto backslash;
910 case '\t': c = 't'; goto backslash;
911 case '\r': c = 'r'; goto backslash;
912 case '\"': c = '\"'; goto backslash;
913 case '\\': c = '\\'; goto backslash;
914 case CTLESC: c = 'e'; goto backslash;
915 case CTLVAR: c = 'v'; goto backslash;
916 case CTLBACKQ: c = 'q'; goto backslash;
918 putc('\\', tracefile);
922 if (*p >= ' ' && *p <= '~')
925 putc('\\', tracefile);
926 putc((*p >> 6) & 03, tracefile);
927 putc((*p >> 3) & 07, tracefile);
928 putc(*p & 07, tracefile);
933 putc('"', tracefile);
937 trace_puts_args(char **ap)
944 trace_puts_quoted(*ap);
946 putc('\n', tracefile);
949 putc(' ', tracefile);
964 /* leave open because libedit might be using it */
967 strcpy(s, "./trace");
969 if (!freopen(s, "a", tracefile)) {
970 fprintf(stderr, "Can't re-open %s\n", s);
975 tracefile = fopen(s, "a");
976 if (tracefile == NULL) {
977 fprintf(stderr, "Can't open %s\n", s);
983 flags = fcntl(fileno(tracefile), F_GETFL);
985 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
987 setlinebuf(tracefile);
988 fputs("\nTracing started.\n", tracefile);
992 indent(int amount, char *pfx, FILE *fp)
996 for (i = 0; i < amount; i++) {
997 if (pfx && i == amount - 1)
1003 /* little circular references here... */
1004 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1007 sharg(union node *arg, FILE *fp)
1010 struct nodelist *bqlist;
1011 unsigned char subtype;
1013 if (arg->type != NARG) {
1014 out1fmt("<node type %d>\n", arg->type);
1017 bqlist = arg->narg.backquote;
1018 for (p = arg->narg.text; *p; p++) {
1019 switch ((unsigned char)*p) {
1028 if (subtype == VSLENGTH)
1036 if (subtype & VSNUL)
1039 switch (subtype & VSTYPE) {
1065 case VSTRIMRIGHTMAX:
1072 out1fmt("<subtype %d>", subtype);
1081 shtree(bqlist->n, -1, NULL, fp);
1092 shcmd(union node *cmd, FILE *fp)
1100 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1106 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1110 switch (np->nfile.type) {
1111 case NTO: s = ">>"+1; dftfd = 1; break;
1112 case NCLOBBER: s = ">|"; dftfd = 1; break;
1113 case NAPPEND: s = ">>"; dftfd = 1; break;
1114 #if BASH_REDIR_OUTPUT
1117 case NTOFD: s = ">&"; dftfd = 1; break;
1118 case NFROM: s = "<"; break;
1119 case NFROMFD: s = "<&"; break;
1120 case NFROMTO: s = "<>"; break;
1121 default: s = "*error*"; break;
1123 if (np->nfile.fd != dftfd)
1124 fprintf(fp, "%d", np->nfile.fd);
1126 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1127 fprintf(fp, "%d", np->ndup.dupfd);
1129 sharg(np->nfile.fname, fp);
1136 shtree(union node *n, int ind, char *pfx, FILE *fp)
1138 struct nodelist *lp;
1144 indent(ind, pfx, fp);
1146 if (n == NODE_EOF) {
1161 shtree(n->nbinary.ch1, ind, NULL, fp);
1164 shtree(n->nbinary.ch2, ind, NULL, fp);
1172 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1173 shtree(lp->n, 0, NULL, fp);
1177 if (n->npipe.pipe_backgnd)
1183 fprintf(fp, "<node type %d>", n->type);
1191 showtree(union node *n)
1193 trace_puts("showtree called\n");
1194 shtree(n, 1, NULL, stderr);
1200 /* ============ Parser data */
1203 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1206 struct strlist *next;
1213 struct strpush *prev; /* preceding string on stack */
1215 int prev_left_in_line;
1216 #if ENABLE_ASH_ALIAS
1217 struct alias *ap; /* if push was associated with an alias */
1219 char *string; /* remember the string since it may change */
1221 /* Remember last two characters for pungetc. */
1224 /* Number of outstanding calls to pungetc. */
1229 struct parsefile *prev; /* preceding file on stack */
1230 int linno; /* current line */
1231 int pf_fd; /* file descriptor (or -1 if string) */
1232 int left_in_line; /* number of chars left in this line */
1233 int left_in_buffer; /* number of chars left in this buffer past the line */
1234 char *next_to_pgetc; /* next char in buffer */
1235 char *buf; /* input buffer */
1236 struct strpush *strpush; /* for pushing strings at this level */
1237 struct strpush basestrpush; /* so pushing one is fast */
1239 /* Remember last two characters for pungetc. */
1242 /* Number of outstanding calls to pungetc. */
1246 static struct parsefile basepf; /* top level input file */
1247 static struct parsefile *g_parsefile = &basepf; /* current input file */
1248 static int startlinno; /* line # where last token started */
1249 static char *commandname; /* currently executing command */
1250 static struct strlist *cmdenviron; /* environment for builtin command */
1253 /* ============ Message printing */
1256 ash_vmsg(const char *msg, va_list ap)
1258 fprintf(stderr, "%s: ", arg0);
1260 if (strcmp(arg0, commandname))
1261 fprintf(stderr, "%s: ", commandname);
1262 if (!iflag || g_parsefile->pf_fd > 0)
1263 fprintf(stderr, "line %d: ", startlinno);
1265 vfprintf(stderr, msg, ap);
1266 newline_and_flush(stderr);
1270 * Exverror is called to raise the error exception. If the second argument
1271 * is not NULL then error prints an error message using printf style
1272 * formatting. It then raises the error exception.
1274 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1276 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1280 TRACE(("ash_vmsg_and_raise(%d):", cond));
1283 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1288 flush_stdout_stderr();
1289 raise_exception(cond);
1293 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1295 ash_msg_and_raise_error(const char *msg, ...)
1302 ash_vmsg_and_raise(EXERROR, msg, ap);
1307 static void raise_error_syntax(const char *) NORETURN;
1309 raise_error_syntax(const char *msg)
1311 ash_msg_and_raise_error("syntax error: %s", msg);
1315 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1317 ash_msg_and_raise(int cond, const char *msg, ...)
1322 ash_vmsg_and_raise(cond, msg, ap);
1328 * error/warning routines for external builtins
1331 ash_msg(const char *fmt, ...)
1341 * Return a string describing an error. The returned string may be a
1342 * pointer to a static buffer that will be overwritten on the next call.
1343 * Action describes the operation that got the error.
1346 errmsg(int e, const char *em)
1348 if (e == ENOENT || e == ENOTDIR) {
1355 /* ============ Memory allocation */
1358 /* I consider these wrappers nearly useless:
1359 * ok, they return you to nearest exception handler, but
1360 * how much memory do you leak in the process, making
1361 * memory starvation worse?
1364 ckrealloc(void * p, size_t nbytes)
1366 p = realloc(p, nbytes);
1368 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1373 ckmalloc(size_t nbytes)
1375 return ckrealloc(NULL, nbytes);
1379 ckzalloc(size_t nbytes)
1381 return memset(ckmalloc(nbytes), 0, nbytes);
1385 ckstrdup(const char *s)
1387 char *p = strdup(s);
1389 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1393 /* Using bbox equivalents. They exit if out of memory */
1394 # define ckrealloc xrealloc
1395 # define ckmalloc xmalloc
1396 # define ckzalloc xzalloc
1397 # define ckstrdup xstrdup
1401 * It appears that grabstackstr() will barf with such alignments
1402 * because stalloc() will return a string allocated in a new stackblock.
1404 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1406 /* Most machines require the value returned from malloc to be aligned
1407 * in some way. The following macro will get this right
1408 * on many machines. */
1409 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1410 /* Minimum size of a block */
1411 MINSIZE = SHELL_ALIGN(504),
1414 struct stack_block {
1415 struct stack_block *prev;
1416 char space[MINSIZE];
1420 struct stack_block *stackp;
1426 struct globals_memstack {
1427 struct stack_block *g_stackp; // = &stackbase;
1428 char *g_stacknxt; // = stackbase.space;
1429 char *sstrend; // = stackbase.space + MINSIZE;
1430 size_t g_stacknleft; // = MINSIZE;
1431 struct stack_block stackbase;
1433 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1434 #define G_memstack (*ash_ptr_to_globals_memstack)
1435 #define g_stackp (G_memstack.g_stackp )
1436 #define g_stacknxt (G_memstack.g_stacknxt )
1437 #define sstrend (G_memstack.sstrend )
1438 #define g_stacknleft (G_memstack.g_stacknleft)
1439 #define stackbase (G_memstack.stackbase )
1440 #define INIT_G_memstack() do { \
1441 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1443 g_stackp = &stackbase; \
1444 g_stacknxt = stackbase.space; \
1445 g_stacknleft = MINSIZE; \
1446 sstrend = stackbase.space + MINSIZE; \
1450 #define stackblock() ((void *)g_stacknxt)
1451 #define stackblocksize() g_stacknleft
1454 * Parse trees for commands are allocated in lifo order, so we use a stack
1455 * to make this more efficient, and also to avoid all sorts of exception
1456 * handling code to handle interrupts in the middle of a parse.
1458 * The size 504 was chosen because the Ultrix malloc handles that size
1462 stalloc(size_t nbytes)
1467 aligned = SHELL_ALIGN(nbytes);
1468 if (aligned > g_stacknleft) {
1471 struct stack_block *sp;
1473 blocksize = aligned;
1474 if (blocksize < MINSIZE)
1475 blocksize = MINSIZE;
1476 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1477 if (len < blocksize)
1478 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1481 sp->prev = g_stackp;
1482 g_stacknxt = sp->space;
1483 g_stacknleft = blocksize;
1484 sstrend = g_stacknxt + blocksize;
1489 g_stacknxt += aligned;
1490 g_stacknleft -= aligned;
1495 stzalloc(size_t nbytes)
1497 return memset(stalloc(nbytes), 0, nbytes);
1504 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1505 write(STDERR_FILENO, "stunalloc\n", 10);
1509 g_stacknleft += g_stacknxt - (char *)p;
1514 * Like strdup but works with the ash stack.
1517 sstrdup(const char *p)
1519 size_t len = strlen(p) + 1;
1520 return memcpy(stalloc(len), p, len);
1524 grabstackblock(size_t len)
1530 pushstackmark(struct stackmark *mark, size_t len)
1532 mark->stackp = g_stackp;
1533 mark->stacknxt = g_stacknxt;
1534 mark->stacknleft = g_stacknleft;
1535 grabstackblock(len);
1539 setstackmark(struct stackmark *mark)
1541 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1545 popstackmark(struct stackmark *mark)
1547 struct stack_block *sp;
1553 while (g_stackp != mark->stackp) {
1555 g_stackp = sp->prev;
1558 g_stacknxt = mark->stacknxt;
1559 g_stacknleft = mark->stacknleft;
1560 sstrend = mark->stacknxt + mark->stacknleft;
1565 * When the parser reads in a string, it wants to stick the string on the
1566 * stack and only adjust the stack pointer when it knows how big the
1567 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1568 * of space on top of the stack and stackblocklen returns the length of
1569 * this block. Growstackblock will grow this space by at least one byte,
1570 * possibly moving it (like realloc). Grabstackblock actually allocates the
1571 * part of the block that has been used.
1574 growstackblock(void)
1578 newlen = g_stacknleft * 2;
1579 if (newlen < g_stacknleft)
1580 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1584 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1585 struct stack_block *sp;
1586 struct stack_block *prevstackp;
1591 prevstackp = sp->prev;
1592 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1593 sp = ckrealloc(sp, grosslen);
1594 sp->prev = prevstackp;
1596 g_stacknxt = sp->space;
1597 g_stacknleft = newlen;
1598 sstrend = sp->space + newlen;
1601 char *oldspace = g_stacknxt;
1602 size_t oldlen = g_stacknleft;
1603 char *p = stalloc(newlen);
1605 /* free the space we just allocated */
1606 g_stacknxt = memcpy(p, oldspace, oldlen);
1607 g_stacknleft += newlen;
1612 * The following routines are somewhat easier to use than the above.
1613 * The user declares a variable of type STACKSTR, which may be declared
1614 * to be a register. The macro STARTSTACKSTR initializes things. Then
1615 * the user uses the macro STPUTC to add characters to the string. In
1616 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1617 * grown as necessary. When the user is done, she can just leave the
1618 * string there and refer to it using stackblock(). Or she can allocate
1619 * the space for it using grabstackstr(). If it is necessary to allow
1620 * someone else to use the stack temporarily and then continue to grow
1621 * the string, the user should use grabstack to allocate the space, and
1622 * then call ungrabstr(p) to return to the previous mode of operation.
1624 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1625 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1626 * is space for at least one character.
1631 size_t len = stackblocksize();
1633 return (char *)stackblock() + len;
1637 * Called from CHECKSTRSPACE.
1640 makestrspace(size_t newlen, char *p)
1642 size_t len = p - g_stacknxt;
1648 size = stackblocksize();
1650 if (nleft >= newlen)
1654 return (char *)stackblock() + len;
1658 stack_nputstr(const char *s, size_t n, char *p)
1660 p = makestrspace(n, p);
1661 p = (char *)memcpy(p, s, n) + n;
1666 stack_putstr(const char *s, char *p)
1668 return stack_nputstr(s, strlen(s), p);
1672 _STPUTC(int c, char *p)
1680 #define STARTSTACKSTR(p) ((p) = stackblock())
1681 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1682 #define CHECKSTRSPACE(n, p) do { \
1685 size_t m = sstrend - q; \
1687 (p) = makestrspace(l, q); \
1689 #define USTPUTC(c, p) (*(p)++ = (c))
1690 #define STACKSTRNUL(p) do { \
1691 if ((p) == sstrend) \
1692 (p) = growstackstr(); \
1695 #define STUNPUTC(p) (--(p))
1696 #define STTOPC(p) ((p)[-1])
1697 #define STADJUST(amount, p) ((p) += (amount))
1699 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1700 #define ungrabstackstr(s, p) stunalloc(s)
1701 #define stackstrend() ((void *)sstrend)
1704 /* ============ String helpers */
1707 * prefix -- see if pfx is a prefix of string.
1710 prefix(const char *string, const char *pfx)
1713 if (*pfx++ != *string++)
1716 return (char *) string;
1720 * Check for a valid number. This should be elsewhere.
1723 is_number(const char *p)
1728 } while (*++p != '\0');
1733 * Convert a string of digits to an integer, printing an error message on
1737 number(const char *s)
1740 ash_msg_and_raise_error(msg_illnum, s);
1745 * Produce a possibly single quoted string suitable as input to the shell.
1746 * The return string is allocated on the stack.
1749 single_quote(const char *s)
1759 len = strchrnul(s, '\'') - s;
1761 q = p = makestrspace(len + 3, p);
1764 q = (char *)memcpy(q, s, len) + len;
1773 do len++; while (*++s == '\'');
1775 q = p = makestrspace(len + 3, p);
1778 q = (char *)memcpy(q, s - len, len) + len;
1786 return stackblock();
1790 /* ============ nextopt */
1792 static char **argptr; /* argument list for builtin commands */
1793 static char *optionarg; /* set by nextopt (like getopt) */
1794 static char *optptr; /* used by nextopt */
1797 * XXX - should get rid of. Have all builtins use getopt(3).
1798 * The library getopt must have the BSD extension static variable
1799 * "optreset", otherwise it can't be used within the shell safely.
1801 * Standard option processing (a la getopt) for builtin routines.
1802 * The only argument that is passed to nextopt is the option string;
1803 * the other arguments are unnecessary. It returns the character,
1804 * or '\0' on end of input.
1807 nextopt(const char *optstring)
1814 if (p == NULL || *p == '\0') {
1815 /* We ate entire "-param", take next one */
1821 if (*++p == '\0') /* just "-" ? */
1824 if (LONE_DASH(p)) /* "--" ? */
1826 /* p => next "-param" */
1828 /* p => some option char in the middle of a "-param" */
1830 for (q = optstring; *q != c;) {
1832 ash_msg_and_raise_error("illegal option -%c", c);
1840 ash_msg_and_raise_error("no arg for -%c option", c);
1850 /* ============ Shell variables */
1853 * The parsefile structure pointed to by the global variable parsefile
1854 * contains information about the current file being read.
1857 int nparam; /* # of positional parameters (without $0) */
1858 #if ENABLE_ASH_GETOPTS
1859 int optind; /* next parameter to be processed by getopts */
1860 int optoff; /* used by getopts */
1862 unsigned char malloced; /* if parameter list dynamically allocated */
1863 char **p; /* parameter list */
1867 * Free the list of positional parameters.
1870 freeparam(volatile struct shparam *param)
1872 if (param->malloced) {
1874 ap = ap1 = param->p;
1881 #if ENABLE_ASH_GETOPTS
1882 static void FAST_FUNC getoptsreset(const char *value);
1886 struct var *next; /* next entry in hash list */
1887 int flags; /* flags are defined above */
1888 const char *var_text; /* name=value */
1889 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1890 /* the variable gets set/unset */
1894 struct localvar *next; /* next local variable in list */
1895 struct var *vp; /* the variable that was made local */
1896 int flags; /* saved flags */
1897 const char *text; /* saved text */
1901 #define VEXPORT 0x01 /* variable is exported */
1902 #define VREADONLY 0x02 /* variable cannot be modified */
1903 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1904 #define VTEXTFIXED 0x08 /* text is statically allocated */
1905 #define VSTACK 0x10 /* text is allocated on the stack */
1906 #define VUNSET 0x20 /* the variable is not set */
1907 #define VNOFUNC 0x40 /* don't call the callback function */
1908 #define VNOSET 0x80 /* do not set variable - just readonly test */
1909 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1910 #if ENABLE_ASH_RANDOM_SUPPORT
1911 # define VDYNAMIC 0x200 /* dynamic variable */
1917 /* Need to be before varinit_data[] */
1918 #if ENABLE_LOCALE_SUPPORT
1919 static void FAST_FUNC
1920 change_lc_all(const char *value)
1922 if (value && *value != '\0')
1923 setlocale(LC_ALL, value);
1925 static void FAST_FUNC
1926 change_lc_ctype(const char *value)
1928 if (value && *value != '\0')
1929 setlocale(LC_CTYPE, value);
1933 static void chkmail(void);
1934 static void changemail(const char *var_value) FAST_FUNC;
1936 # define chkmail() ((void)0)
1938 static void changepath(const char *) FAST_FUNC;
1939 #if ENABLE_ASH_RANDOM_SUPPORT
1940 static void change_random(const char *) FAST_FUNC;
1943 static const struct {
1945 const char *var_text;
1946 void (*var_func)(const char *) FAST_FUNC;
1947 } varinit_data[] = {
1949 * Note: VEXPORT would not work correctly here for NOFORK applets:
1950 * some environment strings may be constant.
1952 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1954 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1955 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1957 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1958 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1959 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1960 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1961 #if ENABLE_ASH_GETOPTS
1962 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1964 #if ENABLE_ASH_RANDOM_SUPPORT
1965 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1967 #if ENABLE_LOCALE_SUPPORT
1968 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1969 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1971 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1972 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1978 struct globals_var {
1979 struct shparam shellparam; /* $@ current positional parameters */
1980 struct redirtab *redirlist;
1981 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1982 struct var *vartab[VTABSIZE];
1983 struct var varinit[ARRAY_SIZE(varinit_data)];
1985 extern struct globals_var *const ash_ptr_to_globals_var;
1986 #define G_var (*ash_ptr_to_globals_var)
1987 #define shellparam (G_var.shellparam )
1988 //#define redirlist (G_var.redirlist )
1989 #define preverrout_fd (G_var.preverrout_fd)
1990 #define vartab (G_var.vartab )
1991 #define varinit (G_var.varinit )
1992 #define INIT_G_var() do { \
1994 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1996 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1997 varinit[i].flags = varinit_data[i].flags; \
1998 varinit[i].var_text = varinit_data[i].var_text; \
1999 varinit[i].var_func = varinit_data[i].var_func; \
2003 #define vifs varinit[0]
2005 # define vmail (&vifs)[1]
2006 # define vmpath (&vmail)[1]
2007 # define vpath (&vmpath)[1]
2009 # define vpath (&vifs)[1]
2011 #define vps1 (&vpath)[1]
2012 #define vps2 (&vps1)[1]
2013 #define vps4 (&vps2)[1]
2014 #if ENABLE_ASH_GETOPTS
2015 # define voptind (&vps4)[1]
2016 # if ENABLE_ASH_RANDOM_SUPPORT
2017 # define vrandom (&voptind)[1]
2020 # if ENABLE_ASH_RANDOM_SUPPORT
2021 # define vrandom (&vps4)[1]
2026 * The following macros access the values of the above variables.
2027 * They have to skip over the name. They return the null string
2028 * for unset variables.
2030 #define ifsval() (vifs.var_text + 4)
2031 #define ifsset() ((vifs.flags & VUNSET) == 0)
2033 # define mailval() (vmail.var_text + 5)
2034 # define mpathval() (vmpath.var_text + 9)
2035 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2037 #define pathval() (vpath.var_text + 5)
2038 #define ps1val() (vps1.var_text + 4)
2039 #define ps2val() (vps2.var_text + 4)
2040 #define ps4val() (vps4.var_text + 4)
2041 #if ENABLE_ASH_GETOPTS
2042 # define optindval() (voptind.var_text + 7)
2045 #if ENABLE_ASH_GETOPTS
2046 static void FAST_FUNC
2047 getoptsreset(const char *value)
2049 shellparam.optind = number(value) ?: 1;
2050 shellparam.optoff = -1;
2055 * Compares two strings up to the first = or '\0'. The first
2056 * string must be terminated by '='; the second may be terminated by
2057 * either '=' or '\0'.
2060 varcmp(const char *p, const char *q)
2064 while ((c = *p) == (d = *q)) {
2065 if (c == '\0' || c == '=')
2079 * Find the appropriate entry in the hash table from the name.
2081 static struct var **
2082 hashvar(const char *p)
2086 hashval = ((unsigned char) *p) << 4;
2087 while (*p && *p != '=')
2088 hashval += (unsigned char) *p++;
2089 return &vartab[hashval % VTABSIZE];
2093 vpcmp(const void *a, const void *b)
2095 return varcmp(*(const char **)a, *(const char **)b);
2099 * This routine initializes the builtin variables.
2109 * PS1 depends on uid
2111 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2112 vps1.var_text = "PS1=\\w \\$ ";
2115 vps1.var_text = "PS1=# ";
2118 end = vp + ARRAY_SIZE(varinit);
2120 vpp = hashvar(vp->var_text);
2123 } while (++vp < end);
2126 static struct var **
2127 findvar(struct var **vpp, const char *name)
2129 for (; *vpp; vpp = &(*vpp)->next) {
2130 if (varcmp((*vpp)->var_text, name) == 0) {
2138 * Find the value of a variable. Returns NULL if not set.
2140 static const char* FAST_FUNC
2141 lookupvar(const char *name)
2145 v = *findvar(hashvar(name), name);
2147 #if ENABLE_ASH_RANDOM_SUPPORT
2149 * Dynamic variables are implemented roughly the same way they are
2150 * in bash. Namely, they're "special" so long as they aren't unset.
2151 * As soon as they're unset, they're no longer dynamic, and dynamic
2152 * lookup will no longer happen at that point. -- PFM.
2154 if (v->flags & VDYNAMIC)
2157 if (!(v->flags & VUNSET))
2158 return var_end(v->var_text);
2163 #if ENABLE_UNICODE_SUPPORT
2165 reinit_unicode_for_ash(void)
2167 /* Unicode support should be activated even if LANG is set
2168 * _during_ shell execution, not only if it was set when
2169 * shell was started. Therefore, re-check LANG every time:
2171 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2172 || ENABLE_UNICODE_USING_LOCALE
2174 const char *s = lookupvar("LC_ALL");
2175 if (!s) s = lookupvar("LC_CTYPE");
2176 if (!s) s = lookupvar("LANG");
2181 # define reinit_unicode_for_ash() ((void)0)
2185 * Search the environment of a builtin command.
2188 bltinlookup(const char *name)
2192 for (sp = cmdenviron; sp; sp = sp->next) {
2193 if (varcmp(sp->text, name) == 0)
2194 return var_end(sp->text);
2196 return lookupvar(name);
2200 * Same as setvar except that the variable and value are passed in
2201 * the first argument as name=value. Since the first argument will
2202 * be actually stored in the table, it should not be a string that
2204 * Called with interrupts off.
2207 setvareq(char *s, int flags)
2209 struct var *vp, **vpp;
2212 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2213 vp = *findvar(vpp, s);
2215 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2218 if (flags & VNOSAVE)
2222 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2228 if (vp->var_func && !(flags & VNOFUNC))
2229 vp->var_func(var_end(s));
2231 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2232 free((char*)vp->var_text);
2234 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2236 /* variable s is not found */
2239 vp = ckzalloc(sizeof(*vp));
2241 /*vp->func = NULL; - ckzalloc did it */
2244 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2251 * Set the value of a variable. The flags argument is ored with the
2252 * flags of the variable. If val is NULL, the variable is unset.
2255 setvar(const char *name, const char *val, int flags)
2263 q = endofname(name);
2264 p = strchrnul(q, '=');
2266 if (!namelen || p != q)
2267 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2272 vallen = strlen(val);
2276 nameeq = ckmalloc(namelen + vallen + 2);
2277 p = memcpy(nameeq, name, namelen) + namelen;
2280 p = memcpy(p, val, vallen) + vallen;
2283 setvareq(nameeq, flags | VNOSAVE);
2287 static void FAST_FUNC
2288 setvar0(const char *name, const char *val)
2290 setvar(name, val, 0);
2294 * Unset the specified variable.
2297 unsetvar(const char *s)
2303 vpp = findvar(hashvar(s), s);
2307 int flags = vp->flags;
2310 if (flags & VREADONLY)
2312 #if ENABLE_ASH_RANDOM_SUPPORT
2313 vp->flags &= ~VDYNAMIC;
2317 if ((flags & VSTRFIXED) == 0) {
2319 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2320 free((char*)vp->var_text);
2326 vp->flags &= ~VEXPORT;
2336 * Process a linked list of variable assignments.
2339 listsetvar(struct strlist *list_set_var, int flags)
2341 struct strlist *lp = list_set_var;
2347 setvareq(lp->text, flags);
2354 * Generate a list of variables satisfying the given conditions.
2357 listvars(int on, int off, char ***end)
2368 for (vp = *vpp; vp; vp = vp->next) {
2369 if ((vp->flags & mask) == on) {
2370 if (ep == stackstrend())
2371 ep = growstackstr();
2372 *ep++ = (char*)vp->var_text;
2375 } while (++vpp < vartab + VTABSIZE);
2376 if (ep == stackstrend())
2377 ep = growstackstr();
2381 return grabstackstr(ep);
2385 /* ============ Path search helper
2387 * The variable path (passed by reference) should be set to the start
2388 * of the path before the first call; path_advance will update
2389 * this value as it proceeds. Successive calls to path_advance will return
2390 * the possible path expansions in sequence. If an option (indicated by
2391 * a percent sign) appears in the path entry then the global variable
2392 * pathopt will be set to point to it; otherwise pathopt will be set to
2395 static const char *pathopt; /* set by path_advance */
2398 path_advance(const char **path, const char *name)
2408 for (p = start; *p && *p != ':' && *p != '%'; p++)
2410 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2411 while (stackblocksize() < len)
2415 memcpy(q, start, p - start);
2423 while (*p && *p != ':')
2430 return stalloc(len);
2434 /* ============ Prompt */
2436 static smallint doprompt; /* if set, prompt the user */
2437 static smallint needprompt; /* true if interactive and at start of line */
2439 #if ENABLE_FEATURE_EDITING
2440 static line_input_t *line_input_state;
2441 static const char *cmdedit_prompt;
2443 putprompt(const char *s)
2445 if (ENABLE_ASH_EXPAND_PRMT) {
2446 free((char*)cmdedit_prompt);
2447 cmdedit_prompt = ckstrdup(s);
2454 putprompt(const char *s)
2460 /* expandstr() needs parsing machinery, so it is far away ahead... */
2461 static const char *expandstr(const char *ps);
2464 setprompt_if(smallint do_set, int whichprompt)
2467 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2474 switch (whichprompt) {
2484 #if ENABLE_ASH_EXPAND_PRMT
2485 pushstackmark(&smark, stackblocksize());
2486 putprompt(expandstr(prompt));
2487 popstackmark(&smark);
2494 /* ============ The cd and pwd commands */
2496 #define CD_PHYSICAL 1
2506 while ((i = nextopt("LP")) != '\0') {
2508 flags ^= CD_PHYSICAL;
2517 * Update curdir (the name of the current directory) in response to a
2521 updatepwd(const char *dir)
2528 cdcomppath = sstrdup(dir);
2531 if (curdir == nullstr)
2533 new = stack_putstr(curdir, new);
2535 new = makestrspace(strlen(dir) + 2, new);
2536 lim = (char *)stackblock() + 1;
2540 if (new > lim && *lim == '/')
2545 if (dir[1] == '/' && dir[2] != '/') {
2551 p = strtok(cdcomppath, "/");
2555 if (p[1] == '.' && p[2] == '\0') {
2567 new = stack_putstr(p, new);
2570 p = strtok(NULL, "/");
2575 return stackblock();
2579 * Find out what the current directory is. If we already know the current
2580 * directory, this routine returns immediately.
2585 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2586 return dir ? dir : nullstr;
2590 setpwd(const char *val, int setold)
2594 oldcur = dir = curdir;
2597 setvar("OLDPWD", oldcur, VEXPORT);
2600 if (physdir != nullstr) {
2601 if (physdir != oldcur)
2605 if (oldcur == val || !val) {
2611 dir = ckstrdup(val);
2612 if (oldcur != dir && oldcur != nullstr) {
2617 setvar("PWD", dir, VEXPORT);
2620 static void hashcd(void);
2623 * Actually do the chdir. We also call hashcd to let other routines
2624 * know that the current directory has changed.
2627 docd(const char *dest, int flags)
2629 const char *dir = NULL;
2632 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2635 if (!(flags & CD_PHYSICAL)) {
2636 dir = updatepwd(dest);
2650 static int FAST_FUNC
2651 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2663 dest = bltinlookup("HOME");
2664 else if (LONE_DASH(dest)) {
2665 dest = bltinlookup("OLDPWD");
2687 path = bltinlookup("CDPATH");
2690 p = path_advance(&path, dest);
2691 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2695 if (!docd(p, flags))
2706 ash_msg_and_raise_error("can't cd to %s", dest);
2709 if (flags & CD_PRINT)
2710 out1fmt("%s\n", curdir);
2714 static int FAST_FUNC
2715 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2718 const char *dir = curdir;
2722 if (physdir == nullstr)
2726 out1fmt("%s\n", dir);
2731 /* ============ ... */
2734 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2736 /* Syntax classes */
2737 #define CWORD 0 /* character is nothing special */
2738 #define CNL 1 /* newline character */
2739 #define CBACK 2 /* a backslash character */
2740 #define CSQUOTE 3 /* single quote */
2741 #define CDQUOTE 4 /* double quote */
2742 #define CENDQUOTE 5 /* a terminating quote */
2743 #define CBQUOTE 6 /* backwards single quote */
2744 #define CVAR 7 /* a dollar sign */
2745 #define CENDVAR 8 /* a '}' character */
2746 #define CLP 9 /* a left paren in arithmetic */
2747 #define CRP 10 /* a right paren in arithmetic */
2748 #define CENDFILE 11 /* end of file */
2749 #define CCTL 12 /* like CWORD, except it must be escaped */
2750 #define CSPCL 13 /* these terminate a word */
2751 #define CIGN 14 /* character should be ignored */
2754 #if ENABLE_ASH_ALIAS
2758 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2760 #if ENABLE_FEATURE_SH_MATH
2761 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2763 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2765 static const uint16_t S_I_T[] ALIGN2 = {
2766 #if ENABLE_ASH_ALIAS
2767 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2769 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2770 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2771 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2772 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2773 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2774 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2775 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2776 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2777 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2778 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2779 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2780 #if !USE_SIT_FUNCTION
2781 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2782 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2783 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2787 /* Constants below must match table above */
2789 #if ENABLE_ASH_ALIAS
2790 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2792 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2793 CNL_CNL_CNL_CNL , /* 2 */
2794 CWORD_CCTL_CCTL_CWORD , /* 3 */
2795 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2796 CVAR_CVAR_CWORD_CVAR , /* 5 */
2797 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2798 CSPCL_CWORD_CWORD_CLP , /* 7 */
2799 CSPCL_CWORD_CWORD_CRP , /* 8 */
2800 CBACK_CBACK_CCTL_CBACK , /* 9 */
2801 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2802 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2803 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2804 CWORD_CWORD_CWORD_CWORD , /* 13 */
2805 CCTL_CCTL_CCTL_CCTL , /* 14 */
2808 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2809 * caller must ensure proper cast on it if c is *char_ptr!
2811 /* Values for syntax param */
2812 #define BASESYNTAX 0 /* not in quotes */
2813 #define DQSYNTAX 1 /* in double quotes */
2814 #define SQSYNTAX 2 /* in single quotes */
2815 #define ARISYNTAX 3 /* in arithmetic */
2816 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2818 #if USE_SIT_FUNCTION
2821 SIT(int c, int syntax)
2823 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2824 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2826 * This causes '/' to be prepended with CTLESC in dquoted string,
2827 * making "./file"* treated incorrectly because we feed
2828 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2829 * The "homegrown" glob implementation is okay with that,
2830 * but glibc one isn't. With '/' always treated as CWORD,
2833 # if ENABLE_ASH_ALIAS
2834 static const uint8_t syntax_index_table[] ALIGN1 = {
2835 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2836 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2837 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2841 static const uint8_t syntax_index_table[] ALIGN1 = {
2842 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2843 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2844 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2853 # if ENABLE_ASH_ALIAS
2859 /* Cast is purely for paranoia here,
2860 * just in case someone passed signed char to us */
2861 if ((unsigned char)c >= CTL_FIRST
2862 && (unsigned char)c <= CTL_LAST
2866 s = strchrnul(spec_symbls, c);
2869 indx = syntax_index_table[s - spec_symbls];
2871 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2874 #else /* !USE_SIT_FUNCTION */
2876 static const uint8_t syntax_index_table[] ALIGN1 = {
2877 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2878 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2888 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2889 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2911 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2912 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2913 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2915 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2917 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2918 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2919 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2920 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2923 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2925 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2926 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2939 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2940 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2941 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2942 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2943 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2971 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2972 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2973 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2976 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3004 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3005 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3006 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3007 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3009 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3010 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3011 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3012 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3013 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3014 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3015 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3016 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3135 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3136 # if ENABLE_ASH_ALIAS
3137 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3142 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3143 #else /* debug version, caught one signed char bug */
3144 # define SIT(c, syntax) \
3146 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3147 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3148 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3149 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3150 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3154 #endif /* !USE_SIT_FUNCTION */
3157 /* ============ Alias handling */
3159 #if ENABLE_ASH_ALIAS
3161 #define ALIASINUSE 1
3172 static struct alias **atab; // [ATABSIZE];
3173 #define INIT_G_alias() do { \
3174 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3178 static struct alias **
3179 __lookupalias(const char *name)
3181 unsigned int hashval;
3188 ch = (unsigned char)*p;
3192 ch = (unsigned char)*++p;
3194 app = &atab[hashval % ATABSIZE];
3196 for (; *app; app = &(*app)->next) {
3197 if (strcmp(name, (*app)->name) == 0) {
3205 static struct alias *
3206 lookupalias(const char *name, int check)
3208 struct alias *ap = *__lookupalias(name);
3210 if (check && ap && (ap->flag & ALIASINUSE))
3215 static struct alias *
3216 freealias(struct alias *ap)
3220 if (ap->flag & ALIASINUSE) {
3221 ap->flag |= ALIASDEAD;
3233 setalias(const char *name, const char *val)
3235 struct alias *ap, **app;
3237 app = __lookupalias(name);
3241 if (!(ap->flag & ALIASINUSE)) {
3244 ap->val = ckstrdup(val);
3245 ap->flag &= ~ALIASDEAD;
3248 ap = ckzalloc(sizeof(struct alias));
3249 ap->name = ckstrdup(name);
3250 ap->val = ckstrdup(val);
3251 /*ap->flag = 0; - ckzalloc did it */
3252 /*ap->next = NULL;*/
3259 unalias(const char *name)
3263 app = __lookupalias(name);
3267 *app = freealias(*app);
3278 struct alias *ap, **app;
3282 for (i = 0; i < ATABSIZE; i++) {
3284 for (ap = *app; ap; ap = *app) {
3285 *app = freealias(*app);
3295 printalias(const struct alias *ap)
3297 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3301 * TODO - sort output
3303 static int FAST_FUNC
3304 aliascmd(int argc UNUSED_PARAM, char **argv)
3313 for (i = 0; i < ATABSIZE; i++) {
3314 for (ap = atab[i]; ap; ap = ap->next) {
3320 while ((n = *++argv) != NULL) {
3321 v = strchr(n+1, '=');
3322 if (v == NULL) { /* n+1: funny ksh stuff */
3323 ap = *__lookupalias(n);
3325 fprintf(stderr, "%s: %s not found\n", "alias", n);
3338 static int FAST_FUNC
3339 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3343 while (nextopt("a") != '\0') {
3347 for (i = 0; *argptr; argptr++) {
3348 if (unalias(*argptr)) {
3349 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3357 #endif /* ASH_ALIAS */
3360 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3363 #define FORK_NOJOB 2
3365 /* mode flags for showjob(s) */
3366 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3367 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3368 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3369 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3372 * A job structure contains information about a job. A job is either a
3373 * single process or a set of processes contained in a pipeline. In the
3374 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3378 pid_t ps_pid; /* process id */
3379 int ps_status; /* last process status from wait() */
3380 char *ps_cmd; /* text of command being run */
3384 struct procstat ps0; /* status of process */
3385 struct procstat *ps; /* status or processes when more than one */
3387 int stopstatus; /* status of a stopped job */
3389 unsigned nprocs; /* number of processes */
3391 #define JOBRUNNING 0 /* at least one proc running */
3392 #define JOBSTOPPED 1 /* all procs are stopped */
3393 #define JOBDONE 2 /* all procs are completed */
3397 sigint: 1, /* job was killed by SIGINT */
3398 jobctl: 1, /* job running under job control */
3400 waited: 1, /* true if this entry has been waited for */
3401 used: 1, /* true if this entry is in used */
3402 changed: 1; /* true if status has changed */
3403 struct job *prev_job; /* previous job */
3406 static struct job *makejob(/*union node *,*/ int);
3407 static int forkshell(struct job *, union node *, int);
3408 static int waitforjob(struct job *);
3411 enum { doing_jobctl = 0 };
3412 #define setjobctl(on) do {} while (0)
3414 static smallint doing_jobctl; //references:8
3415 static void setjobctl(int);
3422 ignoresig(int signo)
3424 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3425 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3426 /* No, need to do it */
3427 signal(signo, SIG_IGN);
3429 sigmode[signo - 1] = S_HARD_IGN;
3433 * Only one usage site - in setsignal()
3436 signal_handler(int signo)
3438 if (signo == SIGCHLD) {
3444 gotsig[signo - 1] = 1;
3445 pending_sig = signo;
3447 if (signo == SIGINT && !trap[SIGINT]) {
3448 if (!suppress_int) {
3450 raise_interrupt(); /* does not return */
3457 * Set the signal handler for the specified signal. The routine figures
3458 * out what it should be set to.
3461 setsignal(int signo)
3464 char cur_act, new_act;
3465 struct sigaction act;
3469 if (t != NULL) { /* trap for this sig is set */
3471 if (t[0] == '\0') /* trap is "": ignore this sig */
3475 if (rootshell && new_act == S_DFL) {
3478 if (iflag || minusc || sflag == 0)
3487 * "In all cases, bash ignores SIGQUIT. Non-builtin
3488 * commands run by bash have signal handlers
3489 * set to the values inherited by the shell
3490 * from its parent". */
3506 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3507 //whereas we have to restore it to what shell got on entry
3508 //from the parent. See comment above
3510 if (signo == SIGCHLD)
3513 t = &sigmode[signo - 1];
3516 /* current setting is not yet known */
3517 if (sigaction(signo, NULL, &act)) {
3518 /* pretend it worked; maybe we should give a warning,
3519 * but other shells don't. We don't alter sigmode,
3520 * so we retry every time.
3521 * btw, in Linux it never fails. --vda */
3524 if (act.sa_handler == SIG_IGN) {
3525 cur_act = S_HARD_IGN;
3527 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3529 cur_act = S_IGN; /* don't hard ignore these */
3533 if (cur_act == S_HARD_IGN || cur_act == new_act)
3536 act.sa_handler = SIG_DFL;
3539 act.sa_handler = signal_handler;
3542 act.sa_handler = SIG_IGN;
3546 /* flags and mask matter only if !DFL and !IGN, but we do it
3547 * for all cases for more deterministic behavior:
3550 sigfillset(&act.sa_mask);
3552 sigaction_set(signo, &act);
3557 /* mode flags for set_curjob */
3558 #define CUR_DELETE 2
3559 #define CUR_RUNNING 1
3560 #define CUR_STOPPED 0
3563 /* pgrp of shell on invocation */
3564 static int initialpgrp; //references:2
3565 static int ttyfd = -1; //5
3568 static struct job *jobtab; //5
3570 static unsigned njobs; //4
3572 static struct job *curjob; //lots
3573 /* number of presumed living untracked jobs */
3574 static int jobless; //4
3577 /* Bash has a feature: it restores termios after a successful wait for
3578 * a foreground job which had at least one stopped or sigkilled member.
3579 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3580 * properly restoring tty state. Should we do this too?
3581 * A reproducer: ^Z an interactive python:
3584 * Python 2.7.12 (...)
3586 * { python leaves tty in -icanon -echo state. We do survive that... }
3587 * [1]+ Stopped python
3588 * { ...however, next program (python #2) does not survive it well: }
3590 * Python 2.7.12 (...)
3591 * >>> Traceback (most recent call last):
3592 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3593 * File "<stdin>", line 1, in <module>
3594 * NameError: name 'qwerty' is not defined
3596 * The implementation below is modeled on bash code and seems to work.
3597 * However, I'm not sure we should do this. For one: what if I'd fg
3598 * the stopped python instead? It'll be confused by "restored" tty state.
3600 static struct termios shell_tty_info;
3604 if (rootshell && ttyfd >= 0)
3605 tcgetattr(ttyfd, &shell_tty_info);
3610 /* if (rootshell) - caller ensures this */
3612 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3615 job_signal_status(struct job *jp)
3619 struct procstat *ps = jp->ps;
3620 for (i = 0; i < jp->nprocs; i++) {
3621 status = ps[i].ps_status;
3622 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3628 restore_tty_if_stopped_or_signaled(struct job *jp)
3630 //TODO: check what happens if we come from waitforjob() in expbackq()
3632 int s = job_signal_status(jp);
3633 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3638 # define get_tty_state() ((void)0)
3639 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3643 set_curjob(struct job *jp, unsigned mode)
3646 struct job **jpp, **curp;
3648 /* first remove from list */
3649 jpp = curp = &curjob;
3654 jpp = &jp1->prev_job;
3656 *jpp = jp1->prev_job;
3658 /* Then re-insert in correct position */
3666 /* job being deleted */
3669 /* newly created job or backgrounded job,
3670 * put after all stopped jobs.
3675 if (!jp1 || jp1->state != JOBSTOPPED)
3678 jpp = &jp1->prev_job;
3684 /* newly stopped job - becomes curjob */
3685 jp->prev_job = *jpp;
3693 jobno(const struct job *jp)
3695 return jp - jobtab + 1;
3700 * Convert a job name to a job structure.
3703 #define getjob(name, getctl) getjob(name)
3706 getjob(const char *name, int getctl)
3710 const char *err_msg = "%s: no such job";
3714 char *(*match)(const char *, const char *);
3729 if (c == '+' || c == '%') {
3731 err_msg = "No current job";
3737 err_msg = "No previous job";
3747 if (num > 0 && num <= njobs) {
3748 jp = jobtab + num - 1;
3763 if (match(jp->ps[0].ps_cmd, p)) {
3767 err_msg = "%s: ambiguous";
3777 err_msg = "job %s not created under job control";
3778 if (getctl && jp->jobctl == 0)
3783 ash_msg_and_raise_error(err_msg, name);
3787 * Mark a job structure as unused.
3790 freejob(struct job *jp)
3792 struct procstat *ps;
3796 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3797 if (ps->ps_cmd != nullstr)
3800 if (jp->ps != &jp->ps0)
3803 set_curjob(jp, CUR_DELETE);
3809 xtcsetpgrp(int fd, pid_t pgrp)
3811 if (tcsetpgrp(fd, pgrp))
3812 ash_msg_and_raise_error("can't set tty process group (%m)");
3816 * Turn job control on and off.
3818 * Note: This code assumes that the third arg to ioctl is a character
3819 * pointer, which is true on Berkeley systems but not System V. Since
3820 * System V doesn't have job control yet, this isn't a problem now.
3822 * Called with interrupts off.
3830 if (on == doing_jobctl || rootshell == 0)
3834 ofd = fd = open(_PATH_TTY, O_RDWR);
3836 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3837 * That sometimes helps to acquire controlling tty.
3838 * Obviously, a workaround for bugs when someone
3839 * failed to provide a controlling tty to bash! :) */
3845 /* fd is a tty at this point */
3846 fd = fcntl(fd, F_DUPFD, 10);
3847 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3850 goto out; /* F_DUPFD failed */
3851 close_on_exec_on(fd);
3852 while (1) { /* while we are in the background */
3853 pgrp = tcgetpgrp(fd);
3856 ash_msg("can't access tty; job control turned off");
3860 if (pgrp == getpgrp())
3871 xtcsetpgrp(fd, pgrp);
3873 /* turning job control off */
3876 /* was xtcsetpgrp, but this can make exiting ash
3877 * loop forever if pty is already deleted */
3878 tcsetpgrp(fd, pgrp);
3892 static int FAST_FUNC
3893 killcmd(int argc, char **argv)
3895 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3898 if (argv[i][0] == '%') {
3900 * "kill %N" - job kill
3901 * Converting to pgrp / pid kill
3907 jp = getjob(argv[i], 0);
3909 * In jobs started under job control, we signal
3910 * entire process group by kill -PGRP_ID.
3911 * This happens, f.e., in interactive shell.
3913 * Otherwise, we signal each child via
3914 * kill PID1 PID2 PID3.
3916 * sh -c 'sleep 1|sleep 1 & kill %1'
3917 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3918 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3920 n = jp->nprocs; /* can't be 0 (I hope) */
3923 dst = alloca(n * sizeof(int)*4);
3925 for (j = 0; j < n; j++) {
3926 struct procstat *ps = &jp->ps[j];
3927 /* Skip non-running and not-stopped members
3928 * (i.e. dead members) of the job
3930 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3933 * kill_main has matching code to expect
3934 * leading space. Needed to not confuse
3935 * negative pids with "kill -SIGNAL_NO" syntax
3937 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3941 } while (argv[++i]);
3943 return kill_main(argc, argv);
3947 showpipe(struct job *jp /*, FILE *out*/)
3949 struct procstat *ps;
3950 struct procstat *psend;
3952 psend = jp->ps + jp->nprocs;
3953 for (ps = jp->ps + 1; ps < psend; ps++)
3954 printf(" | %s", ps->ps_cmd);
3955 newline_and_flush(stdout);
3956 flush_stdout_stderr();
3961 restartjob(struct job *jp, int mode)
3963 struct procstat *ps;
3969 if (jp->state == JOBDONE)
3971 jp->state = JOBRUNNING;
3972 pgid = jp->ps[0].ps_pid;
3973 if (mode == FORK_FG) {
3975 xtcsetpgrp(ttyfd, pgid);
3977 killpg(pgid, SIGCONT);
3981 if (WIFSTOPPED(ps->ps_status)) {
3987 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3992 static int FAST_FUNC
3993 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3999 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4003 jp = getjob(*argv, 1);
4004 if (mode == FORK_BG) {
4005 set_curjob(jp, CUR_RUNNING);
4006 printf("[%d] ", jobno(jp));
4008 out1str(jp->ps[0].ps_cmd);
4009 showpipe(jp /*, stdout*/);
4010 retval = restartjob(jp, mode);
4011 } while (*argv && *++argv);
4017 sprint_status48(char *s, int status, int sigonly)
4023 if (!WIFEXITED(status)) {
4025 if (WIFSTOPPED(status))
4026 st = WSTOPSIG(status);
4029 st = WTERMSIG(status);
4031 if (st == SIGINT || st == SIGPIPE)
4034 if (WIFSTOPPED(status))
4039 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4040 col = fmtstr(s, 32, strsignal(st));
4041 if (WCOREDUMP(status)) {
4042 strcpy(s + col, " (core dumped)");
4043 col += sizeof(" (core dumped)")-1;
4045 } else if (!sigonly) {
4046 st = WEXITSTATUS(status);
4047 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4054 wait_block_or_sig(int *status)
4061 /* Poll all children for changes in their state */
4063 /* if job control is active, accept stopped processes too */
4064 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4066 break; /* Error (e.g. EINTR, ECHILD) or pid */
4068 /* Children exist, but none are ready. Sleep until interesting signal */
4071 sigprocmask(SIG_SETMASK, &mask, &mask);
4072 while (!got_sigchld && !pending_sig)
4074 sigprocmask(SIG_SETMASK, &mask, NULL);
4075 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4076 while (!got_sigchld && !pending_sig)
4080 /* If it was SIGCHLD, poll children again */
4081 } while (got_sigchld);
4086 #define DOWAIT_NONBLOCK 0
4087 #define DOWAIT_BLOCK 1
4088 #define DOWAIT_BLOCK_OR_SIG 2
4091 dowait(int block, struct job *job)
4096 struct job *thisjob = NULL;
4098 TRACE(("dowait(0x%x) called\n", block));
4100 /* It's wrong to call waitpid() outside of INT_OFF region:
4101 * signal can arrive just after syscall return and handler can
4102 * longjmp away, losing stop/exit notification processing.
4103 * Thus, for "jobs" builtin, and for waiting for a fg job,
4104 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4106 * However, for "wait" builtin it is wrong to simply call waitpid()
4107 * in INT_OFF region: "wait" needs to wait for any running job
4108 * to change state, but should exit on any trap too.
4109 * In INT_OFF region, a signal just before syscall entry can set
4110 * pending_sig variables, but we can't check them, and we would
4111 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4113 * Because of this, we run inside INT_OFF, but use a special routine
4114 * which combines waitpid() and sigsuspend().
4115 * This is the reason why we need to have a handler for SIGCHLD:
4116 * SIG_DFL handler does not wake sigsuspend().
4119 if (block == DOWAIT_BLOCK_OR_SIG) {
4120 pid = wait_block_or_sig(&status);
4123 if (block == DOWAIT_NONBLOCK)
4124 wait_flags = WNOHANG;
4125 /* if job control is active, accept stopped processes too */
4127 wait_flags |= WUNTRACED;
4128 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4129 pid = waitpid(-1, &status, wait_flags);
4131 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4132 pid, status, errno, strerror(errno)));
4137 for (jp = curjob; jp; jp = jp->prev_job) {
4139 struct procstat *ps;
4140 struct procstat *psend;
4141 if (jp->state == JOBDONE)
4145 psend = ps + jp->nprocs;
4147 if (ps->ps_pid == pid) {
4148 TRACE(("Job %d: changing status of proc %d "
4149 "from 0x%x to 0x%x\n",
4150 jobno(jp), pid, ps->ps_status, status));
4151 ps->ps_status = status;
4154 if (ps->ps_status == -1)
4155 jobstate = JOBRUNNING;
4157 if (jobstate == JOBRUNNING)
4159 if (WIFSTOPPED(ps->ps_status)) {
4160 jp->stopstatus = ps->ps_status;
4161 jobstate = JOBSTOPPED;
4164 } while (++ps < psend);
4168 /* Found the job where one of its processes changed its state.
4169 * Is there at least one live and running process in this job? */
4170 if (jobstate != JOBRUNNING) {
4171 /* No. All live processes in the job are stopped
4172 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4174 thisjob->changed = 1;
4175 if (thisjob->state != jobstate) {
4176 TRACE(("Job %d: changing state from %d to %d\n",
4177 jobno(thisjob), thisjob->state, jobstate));
4178 thisjob->state = jobstate;
4180 if (jobstate == JOBSTOPPED)
4181 set_curjob(thisjob, CUR_STOPPED);
4187 /* The process wasn't found in job list */
4189 if (!WIFSTOPPED(status))
4195 if (thisjob && thisjob == job) {
4199 len = sprint_status48(s, status, 1);
4211 showjob(struct job *jp, int mode)
4213 struct procstat *ps;
4214 struct procstat *psend;
4217 char s[16 + 16 + 48];
4218 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4222 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4223 /* just output process (group) id of pipeline */
4224 fprintf(out, "%d\n", ps->ps_pid);
4228 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4233 else if (curjob && jp == curjob->prev_job)
4236 if (mode & SHOW_PIDS)
4237 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4239 psend = ps + jp->nprocs;
4241 if (jp->state == JOBRUNNING) {
4242 strcpy(s + col, "Running");
4243 col += sizeof("Running") - 1;
4245 int status = psend[-1].ps_status;
4246 if (jp->state == JOBSTOPPED)
4247 status = jp->stopstatus;
4248 col += sprint_status48(s + col, status, 0);
4250 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4252 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4253 * or prints several "PID | <cmdN>" lines,
4254 * depending on SHOW_PIDS bit.
4255 * We do not print status of individual processes
4256 * between PID and <cmdN>. bash does it, but not very well:
4257 * first line shows overall job status, not process status,
4258 * making it impossible to know 1st process status.
4262 /* for each process */
4265 if (mode & SHOW_PIDS)
4266 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4268 fprintf(out, "%s%*c%s%s",
4270 33 - col >= 0 ? 33 - col : 0, ' ',
4271 ps == jp->ps ? "" : "| ",
4274 } while (++ps != psend);
4275 newline_and_flush(out);
4279 if (jp->state == JOBDONE) {
4280 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4286 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4287 * statuses have changed since the last call to showjobs.
4294 TRACE(("showjobs(0x%x) called\n", mode));
4296 /* Handle all finished jobs */
4297 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4300 for (jp = curjob; jp; jp = jp->prev_job) {
4301 if (!(mode & SHOW_CHANGED) || jp->changed) {
4307 static int FAST_FUNC
4308 jobscmd(int argc UNUSED_PARAM, char **argv)
4313 while ((m = nextopt("lp")) != '\0') {
4317 mode |= SHOW_ONLY_PGID;
4323 showjob(getjob(*argv, 0), mode);
4333 /* Called only on finished or stopped jobs (no members are running) */
4335 getstatus(struct job *job)
4339 struct procstat *ps;
4341 /* Fetch last member's status */
4342 ps = job->ps + job->nprocs - 1;
4343 status = ps->ps_status;
4345 /* "set -o pipefail" mode: use last _nonzero_ status */
4346 while (status == 0 && --ps >= job->ps)
4347 status = ps->ps_status;
4350 retval = WEXITSTATUS(status);
4351 if (!WIFEXITED(status)) {
4353 retval = WSTOPSIG(status);
4354 if (!WIFSTOPPED(status))
4357 /* XXX: limits number of signals */
4358 retval = WTERMSIG(status);
4360 if (retval == SIGINT)
4366 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4367 jobno(job), job->nprocs, status, retval));
4371 static int FAST_FUNC
4372 waitcmd(int argc UNUSED_PARAM, char **argv)
4383 /* wait for all jobs */
4387 if (!jp) /* no running procs */
4389 if (jp->state == JOBRUNNING)
4395 * "When bash is waiting for an asynchronous command via
4396 * the wait builtin, the reception of a signal for which a trap
4397 * has been set will cause the wait builtin to return immediately
4398 * with an exit status greater than 128, immediately after which
4399 * the trap is executed."
4401 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4402 /* if child sends us a signal *and immediately exits*,
4403 * dowait() returns pid > 0. Check this case,
4404 * not "if (dowait() < 0)"!
4413 if (**argv != '%') {
4414 pid_t pid = number(*argv);
4419 if (job->ps[job->nprocs - 1].ps_pid == pid)
4421 job = job->prev_job;
4424 job = getjob(*argv, 0);
4426 /* loop until process terminated or stopped */
4427 while (job->state == JOBRUNNING) {
4428 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4433 retval = getstatus(job);
4440 retval = 128 + pending_sig;
4449 struct job *jp, *jq;
4451 len = njobs * sizeof(*jp);
4453 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4455 offset = (char *)jp - (char *)jq;
4457 /* Relocate pointers */
4460 jq = (struct job *)((char *)jq + l);
4464 #define joff(p) ((struct job *)((char *)(p) + l))
4465 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4466 if (joff(jp)->ps == &jq->ps0)
4467 jmove(joff(jp)->ps);
4468 if (joff(jp)->prev_job)
4469 jmove(joff(jp)->prev_job);
4479 jp = (struct job *)((char *)jp + len);
4483 } while (--jq >= jp);
4488 * Return a new job structure.
4489 * Called with interrupts off.
4492 makejob(/*union node *node,*/ int nprocs)
4497 for (i = njobs, jp = jobtab; ; jp++) {
4504 if (jp->state != JOBDONE || !jp->waited)
4513 memset(jp, 0, sizeof(*jp));
4515 /* jp->jobctl is a bitfield.
4516 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4520 jp->prev_job = curjob;
4525 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4527 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4534 * Return a string identifying a command (to be printed by the
4537 static char *cmdnextc;
4540 cmdputs(const char *s)
4542 static const char vstype[VSTYPE + 1][3] = {
4543 "", "}", "-", "+", "?", "=",
4544 "%", "%%", "#", "##"
4545 IF_BASH_SUBSTR(, ":")
4546 IF_BASH_PATTERN_SUBST(, "/", "//")
4549 const char *p, *str;
4553 unsigned char subtype = 0;
4557 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4559 while ((c = *p++) != '\0') {
4567 if ((subtype & VSTYPE) == VSLENGTH)
4573 str = "\"}" + !(quoted & 1);
4580 #if ENABLE_FEATURE_SH_MATH
4595 if ((subtype & VSTYPE) != VSNORMAL)
4597 str = vstype[subtype & VSTYPE];
4598 if (subtype & VSNUL)
4607 /* These can only happen inside quotes */
4620 while ((c = *str++) != '\0') {
4623 } /* while *p++ not NUL */
4626 USTPUTC('"', nextc);
4632 /* cmdtxt() and cmdlist() call each other */
4633 static void cmdtxt(union node *n);
4636 cmdlist(union node *np, int sep)
4638 for (; np; np = np->narg.next) {
4642 if (sep && np->narg.next)
4648 cmdtxt(union node *n)
4651 struct nodelist *lp;
4662 lp = n->npipe.cmdlist;
4680 cmdtxt(n->nbinary.ch1);
4696 cmdtxt(n->nif.test);
4698 if (n->nif.elsepart) {
4699 cmdtxt(n->nif.ifpart);
4701 n = n->nif.elsepart;
4719 cmdtxt(n->nbinary.ch1);
4729 cmdputs(n->nfor.var);
4731 cmdlist(n->nfor.args, 1);
4736 cmdputs(n->narg.text);
4740 cmdlist(n->ncmd.args, 1);
4741 cmdlist(n->ncmd.redirect, 0);
4754 cmdputs(n->ncase.expr->narg.text);
4756 for (np = n->ncase.cases; np; np = np->nclist.next) {
4757 cmdtxt(np->nclist.pattern);
4759 cmdtxt(np->nclist.body);
4773 #if BASH_REDIR_OUTPUT
4788 cmdputs(utoa(n->nfile.fd));
4790 if (n->type == NTOFD || n->type == NFROMFD) {
4791 cmdputs(utoa(n->ndup.dupfd));
4800 commandtext(union node *n)
4804 STARTSTACKSTR(cmdnextc);
4806 name = stackblock();
4807 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4808 return ckstrdup(name);
4813 * Fork off a subshell. If we are doing job control, give the subshell its
4814 * own process group. Jp is a job structure that the job is to be added to.
4815 * N is the command that will be evaluated by the child. Both jp and n may
4816 * be NULL. The mode parameter can be one of the following:
4817 * FORK_FG - Fork off a foreground process.
4818 * FORK_BG - Fork off a background process.
4819 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4820 * process group even if job control is on.
4822 * When job control is turned off, background processes have their standard
4823 * input redirected to /dev/null (except for the second and later processes
4826 * Called with interrupts off.
4829 * Clear traps on a fork.
4837 for (tp = trap; tp < &trap[NSIG]; tp++) {
4838 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4839 if (trap_ptr == trap)
4841 /* else: it "belongs" to trap_ptr vector, don't free */
4843 if ((tp - trap) != 0)
4844 setsignal(tp - trap);
4851 /* Lives far away from here, needed for forkchild */
4852 static void closescript(void);
4854 /* Called after fork(), in child */
4855 /* jp and n are NULL when called by openhere() for heredoc support */
4856 static NOINLINE void
4857 forkchild(struct job *jp, union node *n, int mode)
4861 TRACE(("Child shell %d\n", getpid()));
4865 /* man bash: "Non-builtin commands run by bash have signal handlers
4866 * set to the values inherited by the shell from its parent".
4867 * Do we do it correctly? */
4871 if (mode == FORK_NOJOB /* is it `xxx` ? */
4872 && n && n->type == NCMD /* is it single cmd? */
4873 /* && n->ncmd.args->type == NARG - always true? */
4874 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4875 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4876 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4878 TRACE(("Trap hack\n"));
4879 /* Awful hack for `trap` or $(trap).
4881 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4882 * contains an example where "trap" is executed in a subshell:
4884 * save_traps=$(trap)
4886 * eval "$save_traps"
4888 * Standard does not say that "trap" in subshell shall print
4889 * parent shell's traps. It only says that its output
4890 * must have suitable form, but then, in the above example
4891 * (which is not supposed to be normative), it implies that.
4893 * bash (and probably other shell) does implement it
4894 * (traps are reset to defaults, but "trap" still shows them),
4895 * but as a result, "trap" logic is hopelessly messed up:
4898 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4899 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4900 * # true | trap <--- trap is in subshell - no output (ditto)
4901 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4902 * trap -- 'echo Ho' SIGWINCH
4903 * # echo `(trap)` <--- in subshell in subshell - output
4904 * trap -- 'echo Ho' SIGWINCH
4905 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4906 * trap -- 'echo Ho' SIGWINCH
4908 * The rules when to forget and when to not forget traps
4909 * get really complex and nonsensical.
4911 * Our solution: ONLY bare $(trap) or `trap` is special.
4913 /* Save trap handler strings for trap builtin to print */
4914 trap_ptr = xmemdup(trap, sizeof(trap));
4915 /* Fall through into clearing traps */
4919 /* do job control only in root shell */
4921 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4924 if (jp->nprocs == 0)
4927 pgrp = jp->ps[0].ps_pid;
4928 /* this can fail because we are doing it in the parent also */
4930 if (mode == FORK_FG)
4931 xtcsetpgrp(ttyfd, pgrp);
4936 if (mode == FORK_BG) {
4937 /* man bash: "When job control is not in effect,
4938 * asynchronous commands ignore SIGINT and SIGQUIT" */
4941 if (jp->nprocs == 0) {
4943 if (open(bb_dev_null, O_RDONLY) != 0)
4944 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4948 if (iflag) { /* why if iflag only? */
4953 * "In all cases, bash ignores SIGQUIT. Non-builtin
4954 * commands run by bash have signal handlers
4955 * set to the values inherited by the shell
4957 * Take care of the second rule: */
4961 if (n && n->type == NCMD
4962 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4964 TRACE(("Job hack\n"));
4965 /* "jobs": we do not want to clear job list for it,
4966 * instead we remove only _its_ own_ job from job list.
4967 * This makes "jobs .... | cat" more useful.
4973 for (jp = curjob; jp; jp = jp->prev_job)
4978 /* Called after fork(), in parent */
4980 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4983 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4985 TRACE(("In parent shell: child = %d\n", pid));
4987 /* jp is NULL when called by openhere() for heredoc support */
4988 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4994 if (mode != FORK_NOJOB && jp->jobctl) {
4997 if (jp->nprocs == 0)
5000 pgrp = jp->ps[0].ps_pid;
5001 /* This can fail because we are doing it in the child also */
5005 if (mode == FORK_BG) {
5006 backgndpid = pid; /* set $! */
5007 set_curjob(jp, CUR_RUNNING);
5010 struct procstat *ps = &jp->ps[jp->nprocs++];
5013 ps->ps_cmd = nullstr;
5015 if (doing_jobctl && n)
5016 ps->ps_cmd = commandtext(n);
5021 /* jp and n are NULL when called by openhere() for heredoc support */
5023 forkshell(struct job *jp, union node *n, int mode)
5027 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5030 TRACE(("Fork failed, errno=%d", errno));
5033 ash_msg_and_raise_error("can't fork");
5036 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5037 forkchild(jp, n, mode);
5039 forkparent(jp, n, mode, pid);
5045 * Wait for job to finish.
5047 * Under job control we have the problem that while a child process
5048 * is running interrupts generated by the user are sent to the child
5049 * but not to the shell. This means that an infinite loop started by
5050 * an interactive user may be hard to kill. With job control turned off,
5051 * an interactive user may place an interactive program inside a loop.
5052 * If the interactive program catches interrupts, the user doesn't want
5053 * these interrupts to also abort the loop. The approach we take here
5054 * is to have the shell ignore interrupt signals while waiting for a
5055 * foreground process to terminate, and then send itself an interrupt
5056 * signal if the child process was terminated by an interrupt signal.
5057 * Unfortunately, some programs want to do a bit of cleanup and then
5058 * exit on interrupt; unless these processes terminate themselves by
5059 * sending a signal to themselves (instead of calling exit) they will
5060 * confuse this approach.
5062 * Called with interrupts off.
5065 waitforjob(struct job *jp)
5069 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5072 while (jp->state == JOBRUNNING) {
5073 /* In non-interactive shells, we _can_ get
5074 * a keyboard signal here and be EINTRed,
5075 * but we just loop back, waiting for command to complete.
5078 * "If bash is waiting for a command to complete and receives
5079 * a signal for which a trap has been set, the trap
5080 * will not be executed until the command completes."
5082 * Reality is that even if trap is not set, bash
5083 * will not act on the signal until command completes.
5084 * Try this. sleep5intoff.c:
5085 * #include <signal.h>
5086 * #include <unistd.h>
5089 * sigemptyset(&set);
5090 * sigaddset(&set, SIGINT);
5091 * sigaddset(&set, SIGQUIT);
5092 * sigprocmask(SIG_BLOCK, &set, NULL);
5096 * $ bash -c './sleep5intoff; echo hi'
5097 * ^C^C^C^C <--- pressing ^C once a second
5099 * $ bash -c './sleep5intoff; echo hi'
5100 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5103 dowait(DOWAIT_BLOCK, jp);
5110 xtcsetpgrp(ttyfd, rootpid);
5111 restore_tty_if_stopped_or_signaled(jp);
5114 * This is truly gross.
5115 * If we're doing job control, then we did a TIOCSPGRP which
5116 * caused us (the shell) to no longer be in the controlling
5117 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5118 * intuit from the subprocess exit status whether a SIGINT
5119 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5121 if (jp->sigint) /* TODO: do the same with all signals */
5122 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5124 if (jp->state == JOBDONE)
5131 * return 1 if there are stopped jobs, otherwise 0
5143 if (jp && jp->state == JOBSTOPPED) {
5144 out2str("You have stopped jobs.\n");
5154 * Code for dealing with input/output redirection.
5159 #define EMPTY -2 /* marks an unused slot in redirtab */
5160 #define CLOSED -3 /* marks a slot of previously-closed fd */
5163 * Open a file in noclobber mode.
5164 * The code was copied from bash.
5167 noclobberopen(const char *fname)
5170 struct stat finfo, finfo2;
5173 * If the file exists and is a regular file, return an error
5176 r = stat(fname, &finfo);
5177 if (r == 0 && S_ISREG(finfo.st_mode)) {
5183 * If the file was not present (r != 0), make sure we open it
5184 * exclusively so that if it is created before we open it, our open
5185 * will fail. Make sure that we do not truncate an existing file.
5186 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5187 * file was not a regular file, we leave O_EXCL off.
5190 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5191 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5193 /* If the open failed, return the file descriptor right away. */
5198 * OK, the open succeeded, but the file may have been changed from a
5199 * non-regular file to a regular file between the stat and the open.
5200 * We are assuming that the O_EXCL open handles the case where FILENAME
5201 * did not exist and is symlinked to an existing file between the stat
5206 * If we can open it and fstat the file descriptor, and neither check
5207 * revealed that it was a regular file, and the file has not been
5208 * replaced, return the file descriptor.
5210 if (fstat(fd, &finfo2) == 0
5211 && !S_ISREG(finfo2.st_mode)
5212 && finfo.st_dev == finfo2.st_dev
5213 && finfo.st_ino == finfo2.st_ino
5218 /* The file has been replaced. badness. */
5225 * Handle here documents. Normally we fork off a process to write the
5226 * data to a pipe. If the document is short, we can stuff the data in
5227 * the pipe without forking.
5229 /* openhere needs this forward reference */
5230 static void expandhere(union node *arg, int fd);
5232 openhere(union node *redir)
5238 ash_msg_and_raise_error("pipe call failed");
5239 if (redir->type == NHERE) {
5240 len = strlen(redir->nhere.doc->narg.text);
5241 if (len <= PIPE_BUF) {
5242 full_write(pip[1], redir->nhere.doc->narg.text, len);
5246 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5249 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5250 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5251 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5252 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5253 signal(SIGPIPE, SIG_DFL);
5254 if (redir->type == NHERE)
5255 full_write(pip[1], redir->nhere.doc->narg.text, len);
5257 expandhere(redir->nhere.doc, pip[1]);
5258 _exit(EXIT_SUCCESS);
5266 openredirect(union node *redir)
5271 switch (redir->nfile.type) {
5272 /* Can't happen, our single caller does this itself */
5278 return openhere(redir);
5281 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5282 * allocated space. Do it only when we know it is safe.
5284 fname = redir->nfile.expfname;
5286 switch (redir->nfile.type) {
5292 f = open(fname, O_RDONLY);
5297 f = open(fname, O_RDWR|O_CREAT, 0666);
5302 #if BASH_REDIR_OUTPUT
5305 /* Take care of noclobber mode. */
5307 f = noclobberopen(fname);
5314 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5319 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5327 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5329 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5333 * Copy a file descriptor to be >= 10. Throws exception on error.
5341 newfd = fcntl(from, F_DUPFD, 10);
5342 err = newfd < 0 ? errno : 0;
5345 ash_msg_and_raise_error("%d: %m", from);
5347 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5353 dup2_or_raise(int from, int to)
5357 newfd = (from != to) ? dup2(from, to) : to;
5359 /* Happens when source fd is not open: try "echo >&99" */
5360 ash_msg_and_raise_error("%d: %m", from);
5365 /* Struct def and variable are moved down to the first usage site */
5370 struct redirtab *next;
5372 struct two_fd_t two_fd[];
5374 #define redirlist (G_var.redirlist)
5376 COPYFD_RESTORE = (int)~(INT_MAX),
5380 need_to_remember(struct redirtab *rp, int fd)
5384 if (!rp) /* remembering was not requested */
5387 for (i = 0; i < rp->pair_count; i++) {
5388 if (rp->two_fd[i].orig == fd) {
5389 /* already remembered */
5396 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5398 is_hidden_fd(struct redirtab *rp, int fd)
5401 struct parsefile *pf;
5405 /* Check open scripts' fds */
5408 /* We skip pf_fd == 0 case because of the following case:
5409 * $ ash # running ash interactively
5411 * and in script.sh: "exec 9>&0".
5412 * Even though top-level pf_fd _is_ 0,
5413 * it's still ok to use it: "read" builtin uses it,
5414 * why should we cripple "exec" builtin?
5416 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5424 /* Check saved fds of redirects */
5425 fd |= COPYFD_RESTORE;
5426 for (i = 0; i < rp->pair_count; i++) {
5427 if (rp->two_fd[i].copy == fd) {
5435 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5436 * old file descriptors are stashed away so that the redirection can be
5437 * undone by calling popredir.
5439 /* flags passed to redirect */
5440 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5441 #define REDIR_SAVEFD2 03 /* set preverrout */
5443 redirect(union node *redir, int flags)
5445 struct redirtab *sv;
5450 int copied_fd2 = -1;
5459 if (flags & REDIR_PUSH) {
5460 union node *tmp = redir;
5463 #if BASH_REDIR_OUTPUT
5464 if (tmp->nfile.type == NTO2)
5467 tmp = tmp->nfile.next;
5469 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5470 sv->next = redirlist;
5471 sv->pair_count = sv_pos;
5473 while (sv_pos > 0) {
5475 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5481 fd = redir->nfile.fd;
5482 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5483 right_fd = redir->ndup.dupfd;
5484 //bb_error_msg("doing %d > %d", fd, right_fd);
5485 /* redirect from/to same file descriptor? */
5488 /* "echo >&10" and 10 is a fd opened to a sh script? */
5489 if (is_hidden_fd(sv, right_fd)) {
5490 errno = EBADF; /* as if it is closed */
5491 ash_msg_and_raise_error("%d: %m", right_fd);
5495 newfd = openredirect(redir); /* always >= 0 */
5497 /* Descriptor wasn't open before redirect.
5498 * Mark it for close in the future */
5499 if (need_to_remember(sv, fd)) {
5500 goto remember_to_close;
5505 #if BASH_REDIR_OUTPUT
5508 if (need_to_remember(sv, fd)) {
5509 /* Copy old descriptor */
5510 /* Careful to not accidentally "save"
5511 * to the same fd as right side fd in N>&M */
5512 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5513 #if defined(F_DUPFD_CLOEXEC)
5514 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5516 i = fcntl(fd, F_DUPFD, minfd);
5521 /* Strange error (e.g. "too many files" EMFILE?) */
5525 ash_msg_and_raise_error("%d: %m", fd);
5528 /* EBADF: it is not open - good, remember to close it */
5531 } else { /* fd is open, save its copy */
5532 #if !defined(F_DUPFD_CLOEXEC)
5533 fcntl(i, F_SETFD, FD_CLOEXEC);
5535 /* "exec fd>&-" should not close fds
5536 * which point to script file(s).
5537 * Force them to be restored afterwards */
5538 if (is_hidden_fd(sv, fd))
5539 i |= COPYFD_RESTORE;
5543 sv->two_fd[sv_pos].orig = fd;
5544 sv->two_fd[sv_pos].copy = i;
5548 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5549 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5550 /* Don't want to trigger debugging */
5554 dup2_or_raise(redir->ndup.dupfd, fd);
5556 } else if (fd != newfd) { /* move newfd to fd */
5557 dup2_or_raise(newfd, fd);
5558 #if BASH_REDIR_OUTPUT
5559 if (!(redir->nfile.type == NTO2 && fd == 2))
5563 #if BASH_REDIR_OUTPUT
5564 if (redir->nfile.type == NTO2 && fd == 1) {
5565 /* We already redirected it to fd 1, now copy it to 2 */
5571 } while ((redir = redir->nfile.next) != NULL);
5574 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5575 preverrout_fd = copied_fd2;
5579 * Undo the effects of the last redirection.
5582 popredir(int drop, int restore)
5584 struct redirtab *rp;
5587 if (redirlist == NULL)
5591 for (i = 0; i < rp->pair_count; i++) {
5592 int fd = rp->two_fd[i].orig;
5593 int copy = rp->two_fd[i].copy;
5594 if (copy == CLOSED) {
5599 if (copy != EMPTY) {
5600 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5601 copy &= ~COPYFD_RESTORE;
5603 dup2_or_raise(copy, fd);
5605 close(copy & ~COPYFD_RESTORE);
5608 redirlist = rp->next;
5614 * Undo all redirections. Called on error or interrupt.
5618 redirectsafe(union node *redir, int flags)
5621 volatile int saveint;
5622 struct jmploc *volatile savehandler = exception_handler;
5623 struct jmploc jmploc;
5626 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5627 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5629 exception_handler = &jmploc;
5630 redirect(redir, flags);
5632 exception_handler = savehandler;
5633 if (err && exception_type != EXERROR)
5634 longjmp(exception_handler->loc, 1);
5635 RESTORE_INT(saveint);
5640 /* ============ Routines to expand arguments to commands
5642 * We have to deal with backquotes, shell variables, and file metacharacters.
5645 #if ENABLE_FEATURE_SH_MATH
5647 ash_arith(const char *s)
5649 arith_state_t math_state;
5652 math_state.lookupvar = lookupvar;
5653 math_state.setvar = setvar0;
5654 //math_state.endofname = endofname;
5657 result = arith(&math_state, s);
5658 if (math_state.errmsg)
5659 ash_msg_and_raise_error(math_state.errmsg);
5669 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5670 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5671 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5672 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5673 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5674 * POSIX says for this case:
5675 * Pathname expansion shall not be performed on the word by a
5676 * non-interactive shell; an interactive shell may perform it, but shall
5677 * do so only when the expansion would result in one word.
5678 * Currently, our code complies to the above rule by never globbing
5679 * redirection filenames.
5680 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5681 * (this means that on a typical Linux distro, bash almost always
5682 * performs globbing, and thus diverges from what we do).
5684 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5685 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5686 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5687 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5688 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5692 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5693 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5694 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5695 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5696 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5698 /* Add CTLESC when necessary. */
5699 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5700 /* Do not skip NUL characters. */
5701 #define QUOTES_KEEPNUL EXP_TILDE
5704 * Structure specifying which parts of the string should be searched
5705 * for IFS characters.
5708 struct ifsregion *next; /* next region in list */
5709 int begoff; /* offset of start of region */
5710 int endoff; /* offset of end of region */
5711 int nulonly; /* search for nul bytes only */
5715 struct strlist *list;
5716 struct strlist **lastp;
5719 /* output of current string */
5720 static char *expdest;
5721 /* list of back quote expressions */
5722 static struct nodelist *argbackq;
5723 /* first struct in list of ifs regions */
5724 static struct ifsregion ifsfirst;
5725 /* last struct in list */
5726 static struct ifsregion *ifslastp;
5727 /* holds expanded arg list */
5728 static struct arglist exparg;
5733 #if !ENABLE_FEATURE_SH_MATH
5734 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5735 typedef long arith_t;
5736 # define ARITH_FMT "%ld"
5743 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5744 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5745 STADJUST(len, expdest);
5750 * Break the argument string into pieces based upon IFS and add the
5751 * strings to the argument list. The regions of the string to be
5752 * searched for IFS characters have been stored by recordregion.
5755 ifsbreakup(char *string, struct arglist *arglist)
5757 struct ifsregion *ifsp;
5762 const char *ifs, *realifs;
5767 if (ifslastp != NULL) {
5770 realifs = ifsset() ? ifsval() : defifs;
5773 p = string + ifsp->begoff;
5774 nulonly = ifsp->nulonly;
5775 ifs = nulonly ? nullstr : realifs;
5777 while (p < string + ifsp->endoff) {
5779 if ((unsigned char)*p == CTLESC)
5781 if (!strchr(ifs, *p)) {
5786 ifsspc = (strchr(defifs, *p) != NULL);
5787 /* Ignore IFS whitespace at start */
5788 if (q == start && ifsspc) {
5794 sp = stzalloc(sizeof(*sp));
5796 *arglist->lastp = sp;
5797 arglist->lastp = &sp->next;
5801 if (p >= string + ifsp->endoff) {
5805 if ((unsigned char)*p == CTLESC)
5807 if (strchr(ifs, *p) == NULL) {
5811 if (strchr(defifs, *p) == NULL) {
5826 } while (ifsp != NULL);
5835 sp = stzalloc(sizeof(*sp));
5837 *arglist->lastp = sp;
5838 arglist->lastp = &sp->next;
5844 struct ifsregion *p = ifsfirst.next;
5851 struct ifsregion *ifsp;
5856 ifsfirst.next = NULL;
5863 esclen(const char *start, const char *p)
5867 while (p > start && (unsigned char)*--p == CTLESC) {
5874 * Remove any CTLESC characters from a string.
5877 rmescapes(char *str, int flag)
5879 static const char qchars[] ALIGN1 = {
5880 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5884 unsigned protect_against_glob;
5886 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5888 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5894 if (flag & RMESCAPE_ALLOC) {
5895 size_t len = p - str;
5896 size_t fulllen = len + strlen(p) + 1;
5898 if (flag & RMESCAPE_GROW) {
5899 int strloc = str - (char *)stackblock();
5900 r = makestrspace(fulllen, expdest);
5901 /* p and str may be invalidated by makestrspace */
5902 str = (char *)stackblock() + strloc;
5904 } else if (flag & RMESCAPE_HEAP) {
5905 r = ckmalloc(fulllen);
5907 r = stalloc(fulllen);
5911 q = (char *)memcpy(q, str, len) + len;
5916 globbing = flag & RMESCAPE_GLOB;
5917 protect_against_glob = globbing;
5919 if ((unsigned char)*p == CTLQUOTEMARK) {
5920 // Note: both inquotes and protect_against_glob only affect whether
5921 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5922 inquotes = ~inquotes;
5924 protect_against_glob = globbing;
5927 if ((unsigned char)*p == CTLESC) {
5931 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5933 if (protect_against_glob) {
5935 * We used to trust glob() and fnmatch() to eat
5936 * superfluous escapes (\z where z has no
5937 * special meaning anyway). But this causes
5938 * bugs such as string of one greek letter rho
5939 * (unicode-encoded as two bytes "cf,81")
5940 * getting encoded as "cf,CTLESC,81"
5941 * and here, converted to "cf,\,81" -
5942 * which does not go well with some flavors
5943 * of fnmatch() in unicode locales
5944 * (for example, glibc <= 2.22).
5946 * Lets add "\" only on the chars which need it.
5947 * Testcases for less obvious chars are shown.
5952 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
5953 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
5954 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
5955 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
5956 /* Some libc support [^negate], that's why "^" also needs love */
5957 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
5962 } else if (*p == '\\' && !inquotes) {
5963 /* naked back slash */
5964 protect_against_glob = 0;
5967 #if BASH_PATTERN_SUBST
5968 else if (*p == '/' && slash) {
5969 /* stop handling globbing and mark location of slash */
5970 globbing = slash = 0;
5974 protect_against_glob = globbing;
5979 if (flag & RMESCAPE_GROW) {
5981 STADJUST(q - r + 1, expdest);
5985 #define pmatch(a, b) !fnmatch((a), (b), 0)
5988 * Prepare a pattern for a expmeta (internal glob(3)) call.
5990 * Returns an stalloced string.
5993 preglob(const char *pattern, int flag)
5995 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5999 * Put a string on the stack.
6002 memtodest(const char *p, size_t len, int syntax, int quotes)
6009 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6012 unsigned char c = *p++;
6014 if (quotes & QUOTES_ESC) {
6015 int n = SIT(c, syntax);
6017 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6024 } else if (!(quotes & QUOTES_KEEPNUL))
6033 strtodest(const char *p, int syntax, int quotes)
6035 size_t len = strlen(p);
6036 memtodest(p, len, syntax, quotes);
6041 * Record the fact that we have to scan this region of the
6042 * string for IFS characters.
6045 recordregion(int start, int end, int nulonly)
6047 struct ifsregion *ifsp;
6049 if (ifslastp == NULL) {
6053 ifsp = ckzalloc(sizeof(*ifsp));
6054 /*ifsp->next = NULL; - ckzalloc did it */
6055 ifslastp->next = ifsp;
6059 ifslastp->begoff = start;
6060 ifslastp->endoff = end;
6061 ifslastp->nulonly = nulonly;
6065 removerecordregions(int endoff)
6067 if (ifslastp == NULL)
6070 if (ifsfirst.endoff > endoff) {
6071 while (ifsfirst.next) {
6072 struct ifsregion *ifsp;
6074 ifsp = ifsfirst.next->next;
6075 free(ifsfirst.next);
6076 ifsfirst.next = ifsp;
6079 if (ifsfirst.begoff > endoff) {
6082 ifslastp = &ifsfirst;
6083 ifsfirst.endoff = endoff;
6088 ifslastp = &ifsfirst;
6089 while (ifslastp->next && ifslastp->next->begoff < endoff)
6090 ifslastp = ifslastp->next;
6091 while (ifslastp->next) {
6092 struct ifsregion *ifsp;
6094 ifsp = ifslastp->next->next;
6095 free(ifslastp->next);
6096 ifslastp->next = ifsp;
6099 if (ifslastp->endoff > endoff)
6100 ifslastp->endoff = endoff;
6104 exptilde(char *startp, char *p, int flags)
6110 int quotes = flags & QUOTES_ESC;
6114 while ((c = *++p) != '\0') {
6121 if (flags & EXP_VARTILDE)
6131 if (*name == '\0') {
6132 home = lookupvar("HOME");
6134 pw = getpwnam(name);
6139 if (!home || !*home)
6142 strtodest(home, SQSYNTAX, quotes);
6150 * Execute a command inside back quotes. If it's a builtin command, we
6151 * want to save its output in a block obtained from malloc. Otherwise
6152 * we fork off a subprocess and get the output of the command via a pipe.
6153 * Should be called with interrupts off.
6155 struct backcmd { /* result of evalbackcmd */
6156 int fd; /* file descriptor to read from */
6157 int nleft; /* number of chars in buffer */
6158 char *buf; /* buffer */
6159 struct job *jp; /* job structure for command */
6162 /* These forward decls are needed to use "eval" code for backticks handling: */
6163 #define EV_EXIT 01 /* exit after evaluating tree */
6164 static int evaltree(union node *, int);
6166 static void FAST_FUNC
6167 evalbackcmd(union node *n, struct backcmd *result)
6181 ash_msg_and_raise_error("pipe call failed");
6182 jp = makejob(/*n,*/ 1);
6183 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6189 dup2_or_raise(pip[1], 1);
6192 /* TODO: eflag clearing makes the following not abort:
6193 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6194 * which is what bash does (unless it is in POSIX mode).
6195 * dash deleted "eflag = 0" line in the commit
6196 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6197 * [EVAL] Don't clear eflag in evalbackcmd
6198 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6202 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6207 result->fd = pip[0];
6211 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6212 result->fd, result->buf, result->nleft, result->jp));
6216 * Expand stuff in backwards quotes.
6219 expbackq(union node *cmd, int flag)
6227 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6228 struct stackmark smark;
6231 startloc = expdest - (char *)stackblock();
6232 pushstackmark(&smark, startloc);
6233 evalbackcmd(cmd, &in);
6234 popstackmark(&smark);
6241 memtodest(p, i, syntax, flag & QUOTES_ESC);
6245 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6246 TRACE(("expbackq: read returns %d\n", i));
6255 back_exitstatus = waitforjob(in.jp);
6259 /* Eat all trailing newlines */
6261 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6265 if (!(flag & EXP_QUOTED))
6266 recordregion(startloc, dest - (char *)stackblock(), 0);
6267 TRACE(("evalbackq: size:%d:'%.*s'\n",
6268 (int)((dest - (char *)stackblock()) - startloc),
6269 (int)((dest - (char *)stackblock()) - startloc),
6270 stackblock() + startloc));
6273 #if ENABLE_FEATURE_SH_MATH
6275 * Expand arithmetic expression. Backup to start of expression,
6276 * evaluate, place result in (backed up) result, adjust string position.
6288 * This routine is slightly over-complicated for
6289 * efficiency. Next we scan backwards looking for the
6290 * start of arithmetic.
6292 start = stackblock();
6299 while ((unsigned char)*p != CTLARI) {
6303 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6308 esc = esclen(start, p);
6318 removerecordregions(begoff);
6322 if (flag & QUOTES_ESC)
6323 rmescapes(p + 1, 0);
6325 len = cvtnum(ash_arith(p + 1));
6327 if (!(flag & EXP_QUOTED))
6328 recordregion(begoff, begoff + len, 0);
6332 /* argstr needs it */
6333 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6336 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6337 * characters to allow for further processing. Otherwise treat
6338 * $@ like $* since no splitting will be performed.
6340 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6341 * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
6342 * for correct expansion of "B=$A" word.
6345 argstr(char *p, int flags, struct strlist *var_str_list)
6347 static const char spclchars[] ALIGN1 = {
6355 #if ENABLE_FEATURE_SH_MATH
6360 const char *reject = spclchars;
6361 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6366 if (!(flags & EXP_VARTILDE)) {
6368 } else if (flags & EXP_VARTILDE2) {
6373 if (flags & EXP_TILDE) {
6376 flags &= ~EXP_TILDE;
6380 p = exptilde(p, q, flags);
6383 startloc = expdest - (char *)stackblock();
6387 length += strcspn(p + length, reject);
6391 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6393 /* c == '=' || c == ':' || c == CTLENDARI */
6399 expdest = stack_nputstr(p, length, expdest);
6400 newloc = expdest - (char *)stackblock();
6401 if (breakall && !inquotes && newloc > startloc) {
6402 recordregion(startloc, newloc, 0);
6413 if (flags & EXP_VARTILDE2) {
6417 flags |= EXP_VARTILDE2;
6422 * sort of a hack - expand tildes in variable
6423 * assignments (after the first '=' and after ':'s).
6432 case CTLENDVAR: /* ??? */
6435 inquotes ^= EXP_QUOTED;
6436 /* "$@" syntax adherence hack */
6437 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6438 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6442 if (flags & QUOTES_ESC) {
6453 * Quoted parameter expansion pattern: remove quote
6454 * unless inside inner quotes or we have a literal
6457 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6458 EXP_QPAT && *p != '\\')
6463 TRACE(("argstr: evalvar('%s')\n", p));
6464 p = evalvar(p, flags | inquotes, var_str_list);
6465 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6468 expbackq(argbackq->n, flags | inquotes);
6469 argbackq = argbackq->next;
6471 #if ENABLE_FEATURE_SH_MATH
6474 expari(flags | inquotes);
6483 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6484 char *pattern, int quotes, int zero)
6493 const char *s = loc2;
6500 match = pmatch(pattern, s);
6505 if (quotes && (unsigned char)*loc == CTLESC)
6514 scanright(char *startp, char *rmesc, char *rmescend,
6515 char *pattern, int quotes, int match_at_start)
6517 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6518 int try2optimize = match_at_start;
6524 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6525 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6526 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6528 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6529 * and on each iteration they go back two/one char until they reach the beginning.
6530 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6532 /* TODO: document in what other circumstances we are called. */
6534 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6537 const char *s = loc2;
6538 if (match_at_start) {
6542 match = pmatch(pattern, s);
6543 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6547 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6549 /* Maybe we can optimize this:
6550 * if pattern ends with unescaped *, we can avoid checking
6551 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6552 * it won't match truncated "raw_value_of_" strings too.
6554 unsigned plen = strlen(pattern);
6555 /* Does it end with "*"? */
6556 if (plen != 0 && pattern[--plen] == '*') {
6557 /* "xxxx*" is not escaped */
6558 /* "xxx\*" is escaped */
6559 /* "xx\\*" is not escaped */
6560 /* "x\\\*" is escaped */
6562 while (plen != 0 && pattern[--plen] == '\\')
6565 break; /* ends with unescaped "*" */
6573 esc = esclen(startp, loc);
6584 static void varunset(const char *, const char *, const char *, int) NORETURN;
6586 varunset(const char *end, const char *var, const char *umsg, int varflags)
6592 msg = "parameter not set";
6594 if ((unsigned char)*end == CTLENDVAR) {
6595 if (varflags & VSNUL)
6601 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6605 subevalvar(char *p, char *varname, int strloc, int subtype,
6606 int startloc, int varflags, int flag, struct strlist *var_str_list)
6608 struct nodelist *saveargbackq = argbackq;
6609 int quotes = flag & QUOTES_ESC;
6612 char *rmesc, *rmescend;
6614 int amount, resetloc;
6615 IF_BASH_PATTERN_SUBST(int workloc;)
6616 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6618 char *(*scan)(char*, char*, char*, char*, int, int);
6620 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6621 // p, varname, strloc, subtype, startloc, varflags, quotes);
6623 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6624 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6626 STPUTC('\0', expdest);
6627 argbackq = saveargbackq;
6628 startp = (char *)stackblock() + startloc;
6632 setvar0(varname, startp);
6633 amount = startp - expdest;
6634 STADJUST(amount, expdest);
6638 varunset(p, varname, startp, varflags);
6643 int pos, len, orig_len;
6646 loc = str = stackblock() + strloc;
6648 # if !ENABLE_FEATURE_SH_MATH
6649 # define ash_arith number
6651 /* Read POS in ${var:POS:LEN} */
6652 colon = strchr(loc, ':');
6653 if (colon) *colon = '\0';
6654 pos = ash_arith(loc);
6655 if (colon) *colon = ':';
6657 /* Read LEN in ${var:POS:LEN} */
6658 len = str - startp - 1;
6659 /* *loc != '\0', guaranteed by parser */
6663 /* Adjust the length by the number of escapes */
6664 for (ptr = startp; ptr < (str - 1); ptr++) {
6665 if ((unsigned char)*ptr == CTLESC) {
6672 if (*loc++ == ':') {
6674 len = ash_arith(loc);
6676 /* Skip POS in ${var:POS:LEN} */
6678 while (*loc && *loc != ':') {
6681 if (*loc++ == ':') {
6682 len = ash_arith(loc);
6688 /* ${VAR:$((-n)):l} starts n chars from the end */
6689 pos = orig_len + pos;
6691 if ((unsigned)pos >= orig_len) {
6692 /* apart from obvious ${VAR:999999:l},
6693 * covers ${VAR:$((-9999999)):l} - result is ""
6700 /* ${VAR:N:-M} sets LEN to strlen()-M */
6701 len = (orig_len - pos) + len;
6703 if ((unsigned)len > (orig_len - pos))
6704 len = orig_len - pos;
6706 for (str = startp; pos; str++, pos--) {
6707 if (quotes && (unsigned char)*str == CTLESC)
6710 for (loc = startp; len; len--) {
6711 if (quotes && (unsigned char)*str == CTLESC)
6716 amount = loc - expdest;
6717 STADJUST(amount, expdest);
6720 #endif /* BASH_SUBSTR */
6723 resetloc = expdest - (char *)stackblock();
6725 #if BASH_PATTERN_SUBST
6726 /* We'll comeback here if we grow the stack while handling
6727 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6728 * stack will need rebasing, and we'll need to remove our work
6734 amount = expdest - ((char *)stackblock() + resetloc);
6735 STADJUST(-amount, expdest);
6736 startp = (char *)stackblock() + startloc;
6739 rmescend = (char *)stackblock() + strloc;
6741 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6742 if (rmesc != startp) {
6744 startp = (char *)stackblock() + startloc;
6748 str = (char *)stackblock() + strloc;
6750 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6751 * The result is a_\_z_c (not a\_\_z_c)!
6753 * The search pattern and replace string treat backslashes differently!
6754 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6755 * and string. It's only used on the first call.
6757 preglob(str, IF_BASH_PATTERN_SUBST(
6758 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6759 RMESCAPE_SLASH : ) 0);
6761 #if BASH_PATTERN_SUBST
6762 workloc = expdest - (char *)stackblock();
6763 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6768 repl = strchr(str, CTLESC);
6774 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6776 /* If there's no pattern to match, return the expansion unmolested */
6785 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6786 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6788 /* No match, advance */
6789 char *restart_detect = stackblock();
6791 STPUTC(*idx, expdest);
6792 if (quotes && (unsigned char)*idx == CTLESC) {
6795 STPUTC(*idx, expdest);
6797 if (stackblock() != restart_detect)
6802 /* continue; - prone to quadratic behavior, smarter code: */
6805 if (str[0] == '*') {
6806 /* Pattern is "*foo". If "*foo" does not match "long_string",
6807 * it would never match "ong_string" etc, no point in trying.
6814 if (subtype == VSREPLACEALL) {
6816 if (quotes && (unsigned char)*idx == CTLESC)
6825 //bb_error_msg("repl:'%s'", repl);
6826 for (loc = (char*)repl; *loc; loc++) {
6827 char *restart_detect = stackblock();
6828 if (quotes && *loc == '\\') {
6829 STPUTC(CTLESC, expdest);
6832 STPUTC(*loc, expdest);
6833 if (stackblock() != restart_detect)
6838 if (subtype == VSREPLACE) {
6839 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6841 char *restart_detect = stackblock();
6842 STPUTC(*idx, expdest);
6843 if (stackblock() != restart_detect)
6852 /* We've put the replaced text into a buffer at workloc, now
6853 * move it to the right place and adjust the stack.
6855 STPUTC('\0', expdest);
6856 startp = (char *)stackblock() + startloc;
6857 memmove(startp, (char *)stackblock() + workloc, len + 1);
6858 //bb_error_msg("startp:'%s'", startp);
6859 amount = expdest - (startp + len);
6860 STADJUST(-amount, expdest);
6863 #endif /* BASH_PATTERN_SUBST */
6865 subtype -= VSTRIMRIGHT;
6867 if (subtype < 0 || subtype > 7)
6870 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6871 zero = subtype >> 1;
6872 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6873 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6875 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6878 memmove(startp, loc, str - loc);
6879 loc = startp + (str - loc) - 1;
6882 amount = loc - expdest;
6883 STADJUST(amount, expdest);
6889 * Add the value of a specialized variable to the stack string.
6890 * name parameter (examples):
6891 * ash -c 'echo $1' name:'1='
6892 * ash -c 'echo $qwe' name:'qwe='
6893 * ash -c 'echo $$' name:'$='
6894 * ash -c 'echo ${$}' name:'$='
6895 * ash -c 'echo ${$##q}' name:'$=q'
6896 * ash -c 'echo ${#$}' name:'$='
6897 * note: examples with bad shell syntax:
6898 * ash -c 'echo ${#$1}' name:'$=1'
6899 * ash -c 'echo ${#1#}' name:'1=#'
6901 static NOINLINE ssize_t
6902 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6909 int quoted = *quotedp;
6910 int subtype = varflags & VSTYPE;
6911 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6912 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6915 sep = (flags & EXP_FULL) << CHAR_BIT;
6916 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6926 num = shellparam.nparam;
6934 goto check_1char_name;
6936 expdest = makestrspace(NOPTS, expdest);
6937 for (i = NOPTS - 1; i >= 0; i--) {
6939 USTPUTC(optletters(i), expdest);
6945 /* handles cases similar to ${#$1} */
6946 if (name[2] != '\0')
6947 raise_error_syntax("bad substitution");
6960 sep |= ifsset() ? ifsval()[0] : ' ';
6967 while ((p = *ap++) != NULL) {
6968 len += strtodest(p, syntax, quotes);
6972 memtodest(&sepc, 1, syntax, quotes);
6987 num = atoi(name); /* number(name) fails on ${N#str} etc */
6988 if (num < 0 || num > shellparam.nparam)
6990 p = num ? shellparam.p[num - 1] : arg0;
6993 /* NB: name has form "VAR=..." */
6995 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6996 * which should be considered before we check variables. */
6998 unsigned name_len = (strchrnul(name, '=') - name) + 1;
7002 str = var_str_list->text;
7003 eq = strchr(str, '=');
7004 if (!eq) /* stop at first non-assignment */
7007 if (name_len == (unsigned)(eq - str)
7008 && strncmp(str, name, name_len) == 0
7011 /* goto value; - WRONG! */
7012 /* think "A=1 A=2 B=$A" */
7014 var_str_list = var_str_list->next;
7015 } while (var_str_list);
7019 p = lookupvar(name);
7024 len = strtodest(p, syntax, quotes);
7025 #if ENABLE_UNICODE_SUPPORT
7026 if (subtype == VSLENGTH && len > 0) {
7027 reinit_unicode_for_ash();
7028 if (unicode_status == UNICODE_ON) {
7029 STADJUST(-len, expdest);
7031 len = unicode_strlen(p);
7039 STADJUST(-len, expdest);
7044 * Expand a variable, and return a pointer to the next character in the
7048 evalvar(char *p, int flag, struct strlist *var_str_list)
7059 varflags = (unsigned char) *p++;
7060 subtype = varflags & VSTYPE;
7063 raise_error_syntax("bad substitution");
7065 quoted = flag & EXP_QUOTED;
7067 easy = (!quoted || (*var == '@' && shellparam.nparam));
7068 startloc = expdest - (char *)stackblock();
7069 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7072 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
7073 if (varflags & VSNUL)
7076 if (subtype == VSPLUS) {
7077 varlen = -1 - varlen;
7081 if (subtype == VSMINUS) {
7086 flag | EXP_TILDE | EXP_WORD,
7094 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7098 subevalvar(p, var, 0, subtype, startloc, varflags,
7099 flag & ~QUOTES_ESC, var_str_list);
7102 * Remove any recorded regions beyond
7105 removerecordregions(startloc);
7109 if (varlen < 0 && uflag)
7110 varunset(p, var, 0, 0);
7112 if (subtype == VSLENGTH) {
7113 cvtnum(varlen > 0 ? varlen : 0);
7117 if (subtype == VSNORMAL) {
7121 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7130 case VSTRIMRIGHTMAX:
7134 #if BASH_PATTERN_SUBST
7146 * Terminate the string and start recording the pattern
7149 STPUTC('\0', expdest);
7150 patloc = expdest - (char *)stackblock();
7151 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7152 startloc, varflags, flag, var_str_list)) {
7153 int amount = expdest - (
7154 (char *)stackblock() + patloc - 1
7156 STADJUST(-amount, expdest);
7158 /* Remove any recorded regions beyond start of variable */
7159 removerecordregions(startloc);
7164 if (subtype != VSNORMAL) { /* skip to end of alternative */
7167 unsigned char c = *p++;
7170 else if (c == CTLBACKQ) {
7172 argbackq = argbackq->next;
7173 } else if (c == CTLVAR) {
7174 if ((*p++ & VSTYPE) != VSNORMAL)
7176 } else if (c == CTLENDVAR) {
7186 * Add a file name to the list.
7189 addfname(const char *name)
7193 sp = stzalloc(sizeof(*sp));
7194 sp->text = sstrdup(name);
7196 exparg.lastp = &sp->next;
7199 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7201 hasmeta(const char *p)
7203 static const char chars[] ALIGN1 = {
7204 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7208 p = strpbrk(p, chars);
7211 switch ((unsigned char) *p) {
7215 if (*p == CTLQUOTEMARK)
7219 if (*p == '\0') /* huh? */
7230 if (!strchr(p + 1, ']')) {
7231 /* It's not a properly closed [] pattern,
7232 * but other metas may follow. Continue checking.
7233 * my[file* _is_ globbed by bash
7234 * and matches filenames like "my[file1".
7250 /* If we want to use glob() from libc... */
7251 #if !ENABLE_ASH_INTERNAL_GLOB
7253 /* Add the result of glob() to the list */
7255 addglob(const glob_t *pglob)
7257 char **p = pglob->gl_pathv;
7264 expandmeta(struct strlist *str /*, int flag*/)
7266 /* TODO - EXP_REDIR */
7276 if (!hasmeta(str->text))
7280 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7281 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7282 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7284 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7285 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7286 // Which means you need to unescape the string, right? Not so fast:
7287 // if there _is_ a file named "file\?" (with backslash), it is returned
7288 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7289 // You DON'T KNOW by looking at the result whether you need to unescape it.
7291 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7292 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7293 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7294 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7295 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7296 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7297 i = glob(p, 0, NULL, &pglob);
7298 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7303 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7304 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7305 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7317 *exparg.lastp = str;
7318 rmescapes(str->text, 0);
7319 exparg.lastp = &str->next;
7321 default: /* GLOB_NOSPACE */
7324 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7331 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7334 * Do metacharacter (i.e. *, ?, [...]) expansion.
7337 expmeta(char *expdir, char *enddir, char *name)
7353 for (p = name; esc = 0, *p; p += esc + 1) {
7354 if (*p == '*' || *p == '?')
7356 else if (*p == '[') {
7363 if (*q == '/' || *q == '\0')
7373 if (p[esc] == '/') {
7376 start = p + esc + 1;
7380 if (metaflag == 0) { /* we've reached the end of the file name */
7381 if (enddir != expdir)
7389 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7400 } while (p < start);
7402 if (enddir == expdir) {
7404 } else if (enddir == expdir + 1 && *expdir == '/') {
7413 if (enddir != expdir)
7415 if (*endname == 0) {
7428 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7429 if (dp->d_name[0] == '.' && !matchdot)
7431 if (pmatch(start, dp->d_name)) {
7433 strcpy(enddir, dp->d_name);
7436 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7439 expmeta(expdir, p, endname);
7445 endname[-esc - 1] = esc ? '\\' : '/';
7448 static struct strlist *
7449 msort(struct strlist *list, int len)
7451 struct strlist *p, *q = NULL;
7452 struct strlist **lpp;
7460 for (n = half; --n >= 0;) {
7464 q->next = NULL; /* terminate first half of list */
7465 q = msort(list, half); /* sort first half of list */
7466 p = msort(p, len - half); /* sort second half */
7469 #if ENABLE_LOCALE_SUPPORT
7470 if (strcoll(p->text, q->text) < 0)
7472 if (strcmp(p->text, q->text) < 0)
7496 * Sort the results of file name expansion. It calculates the number of
7497 * strings to sort and then calls msort (short for merge sort) to do the
7500 static struct strlist *
7501 expsort(struct strlist *str)
7507 for (sp = str; sp; sp = sp->next)
7509 return msort(str, len);
7513 expandmeta(struct strlist *str /*, int flag*/)
7515 /* TODO - EXP_REDIR */
7519 struct strlist **savelastp;
7525 if (!hasmeta(str->text))
7527 savelastp = exparg.lastp;
7530 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7532 int i = strlen(str->text);
7533 //BUGGY estimation of how long expanded name can be
7534 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7536 expmeta(expdir, expdir, p);
7541 if (exparg.lastp == savelastp) {
7546 *exparg.lastp = str;
7547 rmescapes(str->text, 0);
7548 exparg.lastp = &str->next;
7550 *exparg.lastp = NULL;
7551 *savelastp = sp = expsort(*savelastp);
7552 while (sp->next != NULL)
7554 exparg.lastp = &sp->next;
7559 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7562 * Perform variable substitution and command substitution on an argument,
7563 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7564 * perform splitting and file name expansion. When arglist is NULL, perform
7565 * here document expansion.
7568 expandarg(union node *arg, struct arglist *arglist, int flag)
7573 argbackq = arg->narg.backquote;
7574 STARTSTACKSTR(expdest);
7575 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7576 argstr(arg->narg.text, flag,
7577 /* var_str_list: */ arglist ? arglist->list : NULL);
7578 p = _STPUTC('\0', expdest);
7580 if (arglist == NULL) {
7581 /* here document expanded */
7584 p = grabstackstr(p);
7585 TRACE(("expandarg: p:'%s'\n", p));
7586 exparg.lastp = &exparg.list;
7590 if (flag & EXP_FULL) {
7591 ifsbreakup(p, &exparg);
7592 *exparg.lastp = NULL;
7593 exparg.lastp = &exparg.list;
7594 expandmeta(exparg.list /*, flag*/);
7596 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7598 TRACE(("expandarg: rmescapes:'%s'\n", p));
7600 sp = stzalloc(sizeof(*sp));
7603 exparg.lastp = &sp->next;
7605 *exparg.lastp = NULL;
7607 *arglist->lastp = exparg.list;
7608 arglist->lastp = exparg.lastp;
7616 * Expand shell variables and backquotes inside a here document.
7619 expandhere(union node *arg, int fd)
7621 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7622 full_write(fd, stackblock(), expdest - (char *)stackblock());
7626 * Returns true if the pattern matches the string.
7629 patmatch(char *pattern, const char *string)
7631 char *p = preglob(pattern, 0);
7632 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7633 return pmatch(p, string);
7637 * See if a pattern matches in a case statement.
7640 casematch(union node *pattern, char *val)
7642 struct stackmark smark;
7645 setstackmark(&smark);
7646 argbackq = pattern->narg.backquote;
7647 STARTSTACKSTR(expdest);
7648 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7649 /* var_str_list: */ NULL);
7650 STACKSTRNUL(expdest);
7652 result = patmatch(stackblock(), val);
7653 popstackmark(&smark);
7658 /* ============ find_command */
7662 int (*builtin)(int, char **) FAST_FUNC;
7663 /* unsigned flags; */
7665 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7666 /* "regular" builtins always take precedence over commands,
7667 * regardless of PATH=....%builtin... position */
7668 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7669 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7672 smallint cmdtype; /* CMDxxx */
7675 /* index >= 0 for commands without path (slashes) */
7676 /* (TODO: what exactly does the value mean? PATH position?) */
7677 /* index == -1 for commands with slashes */
7678 /* index == (-2 - applet_no) for NOFORK applets */
7679 const struct builtincmd *cmd;
7680 struct funcnode *func;
7683 /* values of cmdtype */
7684 #define CMDUNKNOWN -1 /* no entry in table for command */
7685 #define CMDNORMAL 0 /* command is an executable program */
7686 #define CMDFUNCTION 1 /* command is a shell function */
7687 #define CMDBUILTIN 2 /* command is a shell builtin */
7689 /* action to find_command() */
7690 #define DO_ERR 0x01 /* prints errors */
7691 #define DO_ABS 0x02 /* checks absolute paths */
7692 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7693 #define DO_ALTPATH 0x08 /* using alternate path */
7694 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7696 static void find_command(char *, struct cmdentry *, int, const char *);
7699 /* ============ Hashing commands */
7702 * When commands are first encountered, they are entered in a hash table.
7703 * This ensures that a full path search will not have to be done for them
7704 * on each invocation.
7706 * We should investigate converting to a linear search, even though that
7707 * would make the command name "hash" a misnomer.
7711 struct tblentry *next; /* next entry in hash chain */
7712 union param param; /* definition of builtin function */
7713 smallint cmdtype; /* CMDxxx */
7714 char rehash; /* if set, cd done since entry created */
7715 char cmdname[1]; /* name of command */
7718 static struct tblentry **cmdtable;
7719 #define INIT_G_cmdtable() do { \
7720 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7723 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7727 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7729 #if ENABLE_FEATURE_SH_STANDALONE
7730 if (applet_no >= 0) {
7731 if (APPLET_IS_NOEXEC(applet_no)) {
7735 run_applet_no_and_exit(applet_no, cmd, argv);
7737 /* re-exec ourselves with the new arguments */
7738 execve(bb_busybox_exec_path, argv, envp);
7739 /* If they called chroot or otherwise made the binary no longer
7740 * executable, fall through */
7747 execve(cmd, argv, envp);
7748 } while (errno == EINTR);
7750 execve(cmd, argv, envp);
7752 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7753 /* Run "cmd" as a shell script:
7754 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7755 * "If the execve() function fails with ENOEXEC, the shell
7756 * shall execute a command equivalent to having a shell invoked
7757 * with the command name as its first operand,
7758 * with any remaining arguments passed to the new shell"
7760 * That is, do not use $SHELL, user's shell, or /bin/sh;
7761 * just call ourselves.
7763 * Note that bash reads ~80 chars of the file, and if it sees
7764 * a zero byte before it sees newline, it doesn't try to
7765 * interpret it, but fails with "cannot execute binary file"
7766 * message and exit code 126. For one, this prevents attempts
7767 * to interpret foreign ELF binaries as shell scripts.
7770 cmd = (char*) bb_busybox_exec_path;
7771 /* NB: this is only possible because all callers of shellexec()
7772 * ensure that the argv[-1] slot exists!
7775 argv[0] = (char*) "ash";
7781 * Exec a program. Never returns. If you change this routine, you may
7782 * have to change the find_command routine as well.
7783 * argv[-1] must exist and be writable! See tryexec() for why.
7785 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7786 static void shellexec(char *prog, char **argv, const char *path, int idx)
7792 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7794 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7795 if (strchr(prog, '/') != NULL
7796 #if ENABLE_FEATURE_SH_STANDALONE
7797 || (applet_no = find_applet_by_name(prog)) >= 0
7800 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7801 if (applet_no >= 0) {
7802 /* We tried execing ourself, but it didn't work.
7803 * Maybe /proc/self/exe doesn't exist?
7812 while ((cmdname = path_advance(&path, prog)) != NULL) {
7813 if (--idx < 0 && pathopt == NULL) {
7814 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7815 if (errno != ENOENT && errno != ENOTDIR)
7822 /* Map to POSIX errors */
7834 exitstatus = exerrno;
7835 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7836 prog, e, suppress_int));
7837 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7842 printentry(struct tblentry *cmdp)
7848 idx = cmdp->param.index;
7851 name = path_advance(&path, cmdp->cmdname);
7853 } while (--idx >= 0);
7854 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7858 * Clear out command entries. The argument specifies the first entry in
7859 * PATH which has changed.
7862 clearcmdentry(int firstchange)
7864 struct tblentry **tblp;
7865 struct tblentry **pp;
7866 struct tblentry *cmdp;
7869 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7871 while ((cmdp = *pp) != NULL) {
7872 if ((cmdp->cmdtype == CMDNORMAL &&
7873 cmdp->param.index >= firstchange)
7874 || (cmdp->cmdtype == CMDBUILTIN &&
7875 builtinloc >= firstchange)
7888 * Locate a command in the command hash table. If "add" is nonzero,
7889 * add the command to the table if it is not already present. The
7890 * variable "lastcmdentry" is set to point to the address of the link
7891 * pointing to the entry, so that delete_cmd_entry can delete the
7894 * Interrupts must be off if called with add != 0.
7896 static struct tblentry **lastcmdentry;
7898 static struct tblentry *
7899 cmdlookup(const char *name, int add)
7901 unsigned int hashval;
7903 struct tblentry *cmdp;
7904 struct tblentry **pp;
7907 hashval = (unsigned char)*p << 4;
7909 hashval += (unsigned char)*p++;
7911 pp = &cmdtable[hashval % CMDTABLESIZE];
7912 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7913 if (strcmp(cmdp->cmdname, name) == 0)
7917 if (add && cmdp == NULL) {
7918 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7920 /* + 1 - already done because
7921 * tblentry::cmdname is char[1] */);
7922 /*cmdp->next = NULL; - ckzalloc did it */
7923 cmdp->cmdtype = CMDUNKNOWN;
7924 strcpy(cmdp->cmdname, name);
7931 * Delete the command entry returned on the last lookup.
7934 delete_cmd_entry(void)
7936 struct tblentry *cmdp;
7939 cmdp = *lastcmdentry;
7940 *lastcmdentry = cmdp->next;
7941 if (cmdp->cmdtype == CMDFUNCTION)
7942 freefunc(cmdp->param.func);
7948 * Add a new command entry, replacing any existing command entry for
7949 * the same name - except special builtins.
7952 addcmdentry(char *name, struct cmdentry *entry)
7954 struct tblentry *cmdp;
7956 cmdp = cmdlookup(name, 1);
7957 if (cmdp->cmdtype == CMDFUNCTION) {
7958 freefunc(cmdp->param.func);
7960 cmdp->cmdtype = entry->cmdtype;
7961 cmdp->param = entry->u;
7965 static int FAST_FUNC
7966 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7968 struct tblentry **pp;
7969 struct tblentry *cmdp;
7971 struct cmdentry entry;
7974 if (nextopt("r") != '\0') {
7979 if (*argptr == NULL) {
7980 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7981 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7982 if (cmdp->cmdtype == CMDNORMAL)
7990 while ((name = *argptr) != NULL) {
7991 cmdp = cmdlookup(name, 0);
7993 && (cmdp->cmdtype == CMDNORMAL
7994 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7998 find_command(name, &entry, DO_ERR, pathval());
7999 if (entry.cmdtype == CMDUNKNOWN)
8007 * Called when a cd is done. Marks all commands so the next time they
8008 * are executed they will be rehashed.
8013 struct tblentry **pp;
8014 struct tblentry *cmdp;
8016 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8017 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8018 if (cmdp->cmdtype == CMDNORMAL
8019 || (cmdp->cmdtype == CMDBUILTIN
8020 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8030 * Fix command hash table when PATH changed.
8031 * Called before PATH is changed. The argument is the new value of PATH;
8032 * pathval() still returns the old value at this point.
8033 * Called with interrupts off.
8035 static void FAST_FUNC
8036 changepath(const char *new)
8044 firstchange = 9999; /* assume no change */
8050 if ((*old == '\0' && *new == ':')
8051 || (*old == ':' && *new == '\0')
8055 old = new; /* ignore subsequent differences */
8059 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8066 if (builtinloc < 0 && idx_bltin >= 0)
8067 builtinloc = idx_bltin; /* zap builtins */
8068 if (builtinloc >= 0 && idx_bltin < 0)
8070 clearcmdentry(firstchange);
8071 builtinloc = idx_bltin;
8107 typedef smallint token_id_t;
8109 /* Nth bit indicates if token marks the end of a list */
8112 /* 0 */ | (1u << TEOF)
8113 /* 1 */ | (0u << TNL)
8114 /* 2 */ | (0u << TREDIR)
8115 /* 3 */ | (0u << TWORD)
8116 /* 4 */ | (0u << TSEMI)
8117 /* 5 */ | (0u << TBACKGND)
8118 /* 6 */ | (0u << TAND)
8119 /* 7 */ | (0u << TOR)
8120 /* 8 */ | (0u << TPIPE)
8121 /* 9 */ | (0u << TLP)
8122 /* 10 */ | (1u << TRP)
8123 /* 11 */ | (1u << TENDCASE)
8124 /* 12 */ | (1u << TENDBQUOTE)
8125 /* 13 */ | (0u << TNOT)
8126 /* 14 */ | (0u << TCASE)
8127 /* 15 */ | (1u << TDO)
8128 /* 16 */ | (1u << TDONE)
8129 /* 17 */ | (1u << TELIF)
8130 /* 18 */ | (1u << TELSE)
8131 /* 19 */ | (1u << TESAC)
8132 /* 20 */ | (1u << TFI)
8133 /* 21 */ | (0u << TFOR)
8135 /* 22 */ | (0u << TFUNCTION)
8137 /* 23 */ | (0u << TIF)
8138 /* 24 */ | (0u << TIN)
8139 /* 25 */ | (1u << TTHEN)
8140 /* 26 */ | (0u << TUNTIL)
8141 /* 27 */ | (0u << TWHILE)
8142 /* 28 */ | (0u << TBEGIN)
8143 /* 29 */ | (1u << TEND)
8144 , /* thus far 29 bits used */
8147 static const char *const tokname_array[] = {
8161 #define KWDOFFSET 13
8162 /* the following are keywords */
8184 /* Wrapper around strcmp for qsort/bsearch/... */
8186 pstrcmp(const void *a, const void *b)
8188 return strcmp((char*)a, *(char**)b);
8191 static const char *const *
8192 findkwd(const char *s)
8194 return bsearch(s, tokname_array + KWDOFFSET,
8195 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8196 sizeof(tokname_array[0]), pstrcmp);
8200 * Locate and print what a word is...
8203 describe_command(char *command, const char *path, int describe_command_verbose)
8205 struct cmdentry entry;
8206 #if ENABLE_ASH_ALIAS
8207 const struct alias *ap;
8210 path = path ? path : pathval();
8212 if (describe_command_verbose) {
8216 /* First look at the keywords */
8217 if (findkwd(command)) {
8218 out1str(describe_command_verbose ? " is a shell keyword" : command);
8222 #if ENABLE_ASH_ALIAS
8223 /* Then look at the aliases */
8224 ap = lookupalias(command, 0);
8226 if (!describe_command_verbose) {
8231 out1fmt(" is an alias for %s", ap->val);
8236 find_command(command, &entry, DO_ABS, path);
8238 switch (entry.cmdtype) {
8240 int j = entry.u.index;
8246 p = path_advance(&path, command);
8250 if (describe_command_verbose) {
8251 out1fmt(" is %s", p);
8259 if (describe_command_verbose) {
8260 out1str(" is a shell function");
8267 if (describe_command_verbose) {
8268 out1fmt(" is a %sshell builtin",
8269 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8270 "special " : nullstr
8278 if (describe_command_verbose) {
8279 out1str(": not found\n");
8288 static int FAST_FUNC
8289 typecmd(int argc UNUSED_PARAM, char **argv)
8295 /* type -p ... ? (we don't bother checking for 'p') */
8296 if (argv[1] && argv[1][0] == '-') {
8301 err |= describe_command(argv[i++], NULL, verbose);
8306 #if ENABLE_ASH_CMDCMD
8307 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8309 parse_command_args(char **argv, const char **path)
8322 if (c == '-' && !*cp) {
8330 *path = bb_default_path;
8333 /* run 'typecmd' for other options */
8342 static int FAST_FUNC
8343 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8351 const char *path = NULL;
8353 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8354 * never reaches this function.
8357 while ((c = nextopt("pvV")) != '\0')
8359 verify |= VERIFY_VERBOSE;
8361 /*verify |= VERIFY_BRIEF*/;
8367 path = bb_default_path;
8369 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8371 if (/*verify && */ cmd)
8372 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8379 /*static int funcblocksize; // size of structures in function */
8380 /*static int funcstringsize; // size of strings in node */
8381 static void *funcblock; /* block to allocate function from */
8382 static char *funcstring_end; /* end of block to allocate strings from */
8384 /* flags in argument to evaltree */
8385 #define EV_EXIT 01 /* exit after evaluating tree */
8386 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8388 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8389 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8390 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8391 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8392 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8393 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8394 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8395 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8396 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8397 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8398 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8399 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8400 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8401 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8402 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8403 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8404 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8405 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8406 #if BASH_REDIR_OUTPUT
8407 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8409 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8410 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8411 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8412 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8413 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8414 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8415 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8416 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8417 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8420 static int calcsize(int funcblocksize, union node *n);
8423 sizenodelist(int funcblocksize, struct nodelist *lp)
8426 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8427 funcblocksize = calcsize(funcblocksize, lp->n);
8430 return funcblocksize;
8434 calcsize(int funcblocksize, union node *n)
8437 return funcblocksize;
8438 funcblocksize += nodesize[n->type];
8441 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8442 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8443 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8446 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8451 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8452 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8459 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8460 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8463 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8464 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8465 funcblocksize = calcsize(funcblocksize, n->nif.test);
8468 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8469 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8470 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8473 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8474 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8477 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8478 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8479 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8483 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8484 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8485 funcblocksize = calcsize(funcblocksize, n->narg.next);
8488 #if BASH_REDIR_OUTPUT
8495 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8496 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8500 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8501 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8505 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8506 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8509 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8512 return funcblocksize;
8516 nodeckstrdup(char *s)
8518 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8519 return strcpy(funcstring_end, s);
8522 static union node *copynode(union node *);
8524 static struct nodelist *
8525 copynodelist(struct nodelist *lp)
8527 struct nodelist *start;
8528 struct nodelist **lpp;
8533 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8534 (*lpp)->n = copynode(lp->n);
8536 lpp = &(*lpp)->next;
8543 copynode(union node *n)
8550 funcblock = (char *) funcblock + nodesize[n->type];
8554 new->ncmd.redirect = copynode(n->ncmd.redirect);
8555 new->ncmd.args = copynode(n->ncmd.args);
8556 new->ncmd.assign = copynode(n->ncmd.assign);
8559 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8560 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8565 new->nredir.redirect = copynode(n->nredir.redirect);
8566 new->nredir.n = copynode(n->nredir.n);
8573 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8574 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8577 new->nif.elsepart = copynode(n->nif.elsepart);
8578 new->nif.ifpart = copynode(n->nif.ifpart);
8579 new->nif.test = copynode(n->nif.test);
8582 new->nfor.var = nodeckstrdup(n->nfor.var);
8583 new->nfor.body = copynode(n->nfor.body);
8584 new->nfor.args = copynode(n->nfor.args);
8587 new->ncase.cases = copynode(n->ncase.cases);
8588 new->ncase.expr = copynode(n->ncase.expr);
8591 new->nclist.body = copynode(n->nclist.body);
8592 new->nclist.pattern = copynode(n->nclist.pattern);
8593 new->nclist.next = copynode(n->nclist.next);
8597 new->narg.backquote = copynodelist(n->narg.backquote);
8598 new->narg.text = nodeckstrdup(n->narg.text);
8599 new->narg.next = copynode(n->narg.next);
8602 #if BASH_REDIR_OUTPUT
8609 new->nfile.fname = copynode(n->nfile.fname);
8610 new->nfile.fd = n->nfile.fd;
8611 new->nfile.next = copynode(n->nfile.next);
8615 new->ndup.vname = copynode(n->ndup.vname);
8616 new->ndup.dupfd = n->ndup.dupfd;
8617 new->ndup.fd = n->ndup.fd;
8618 new->ndup.next = copynode(n->ndup.next);
8622 new->nhere.doc = copynode(n->nhere.doc);
8623 new->nhere.fd = n->nhere.fd;
8624 new->nhere.next = copynode(n->nhere.next);
8627 new->nnot.com = copynode(n->nnot.com);
8630 new->type = n->type;
8635 * Make a copy of a parse tree.
8637 static struct funcnode *
8638 copyfunc(union node *n)
8643 /*funcstringsize = 0;*/
8644 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8645 f = ckzalloc(blocksize /* + funcstringsize */);
8646 funcblock = (char *) f + offsetof(struct funcnode, n);
8647 funcstring_end = (char *) f + blocksize;
8649 /* f->count = 0; - ckzalloc did it */
8654 * Define a shell function.
8657 defun(union node *func)
8659 struct cmdentry entry;
8662 entry.cmdtype = CMDFUNCTION;
8663 entry.u.func = copyfunc(func);
8664 addcmdentry(func->narg.text, &entry);
8668 /* Reasons for skipping commands (see comment on breakcmd routine) */
8669 #define SKIPBREAK (1 << 0)
8670 #define SKIPCONT (1 << 1)
8671 #define SKIPFUNC (1 << 2)
8672 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8673 static int skipcount; /* number of levels to skip */
8674 static int funcnest; /* depth of function calls */
8675 static int loopnest; /* current loop nesting level */
8677 /* Forward decl way out to parsing code - dotrap needs it */
8678 static int evalstring(char *s, int flags);
8680 /* Called to execute a trap.
8681 * Single callsite - at the end of evaltree().
8682 * If we return non-zero, evaltree raises EXEXIT exception.
8684 * Perhaps we should avoid entering new trap handlers
8685 * while we are executing a trap handler. [is it a TODO?]
8692 uint8_t last_status;
8697 last_status = exitstatus;
8701 TRACE(("dotrap entered\n"));
8702 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8714 /* non-trapped SIGINT is handled separately by raise_interrupt,
8715 * don't upset it by resetting gotsig[SIGINT-1] */
8716 if (sig == SIGINT && !p)
8719 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8725 exitstatus = last_status;
8726 TRACE(("dotrap returns\n"));
8729 /* forward declarations - evaluation is fairly recursive business... */
8730 static int evalloop(union node *, int);
8731 static int evalfor(union node *, int);
8732 static int evalcase(union node *, int);
8733 static int evalsubshell(union node *, int);
8734 static void expredir(union node *);
8735 static int evalpipe(union node *, int);
8736 static int evalcommand(union node *, int);
8737 static int evalbltin(const struct builtincmd *, int, char **, int);
8738 static void prehash(union node *);
8741 * Evaluate a parse tree. The value is left in the global variable
8745 evaltree(union node *n, int flags)
8748 int (*evalfn)(union node *, int);
8752 TRACE(("evaltree(NULL) called\n"));
8755 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8762 out1fmt("Node type = %d\n", n->type);
8767 status = !evaltree(n->nnot.com, EV_TESTED);
8770 expredir(n->nredir.redirect);
8771 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8773 status = evaltree(n->nredir.n, flags & EV_TESTED);
8775 if (n->nredir.redirect)
8776 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8779 evalfn = evalcommand;
8781 if (eflag && !(flags & EV_TESTED))
8793 evalfn = evalsubshell;
8806 #error NAND + 1 != NOR
8808 #if NOR + 1 != NSEMI
8809 #error NOR + 1 != NSEMI
8811 unsigned is_or = n->type - NAND;
8814 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8816 if ((!status) == is_or || evalskip)
8822 status = evalfn(n, flags);
8826 status = evaltree(n->nif.test, EV_TESTED);
8833 if (n->nif.elsepart) {
8834 n = n->nif.elsepart;
8841 /* Not necessary. To test it:
8842 * "false; f() { qwerty; }; echo $?" should print 0.
8846 exitstatus = status;
8850 /* Order of checks below is important:
8851 * signal handlers trigger before exit caused by "set -e".
8855 if (checkexit & status)
8856 raise_exception(EXEXIT);
8857 if (flags & EV_EXIT)
8858 raise_exception(EXEXIT);
8860 TRACE(("leaving evaltree (no interrupts)\n"));
8864 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8867 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8872 int skip = evalskip;
8879 if (--skipcount <= 0) {
8890 evalloop(union node *n, int flags)
8901 i = evaltree(n->nbinary.ch1, EV_TESTED);
8903 if (skip == SKIPFUNC)
8907 if (n->type != NWHILE)
8911 status = evaltree(n->nbinary.ch2, flags);
8913 } while (!(skip & ~SKIPCONT));
8920 evalfor(union node *n, int flags)
8922 struct arglist arglist;
8925 struct stackmark smark;
8928 setstackmark(&smark);
8929 arglist.list = NULL;
8930 arglist.lastp = &arglist.list;
8931 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8932 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8934 *arglist.lastp = NULL;
8938 for (sp = arglist.list; sp; sp = sp->next) {
8939 setvar0(n->nfor.var, sp->text);
8940 status = evaltree(n->nfor.body, flags);
8941 if (skiploop() & ~SKIPCONT)
8945 popstackmark(&smark);
8951 evalcase(union node *n, int flags)
8955 struct arglist arglist;
8956 struct stackmark smark;
8959 setstackmark(&smark);
8960 arglist.list = NULL;
8961 arglist.lastp = &arglist.list;
8962 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8963 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8964 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8965 if (casematch(patp, arglist.list->text)) {
8966 /* Ensure body is non-empty as otherwise
8967 * EV_EXIT may prevent us from setting the
8970 if (evalskip == 0 && cp->nclist.body) {
8971 status = evaltree(cp->nclist.body, flags);
8978 popstackmark(&smark);
8984 * Kick off a subshell to evaluate a tree.
8987 evalsubshell(union node *n, int flags)
8990 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8993 expredir(n->nredir.redirect);
8994 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8997 if (backgnd == FORK_FG)
8999 jp = makejob(/*n,*/ 1);
9000 if (forkshell(jp, n, backgnd) == 0) {
9005 flags &= ~EV_TESTED;
9007 redirect(n->nredir.redirect, 0);
9008 evaltreenr(n->nredir.n, flags);
9013 if (backgnd == FORK_FG)
9014 status = waitforjob(jp);
9020 * Compute the names of the files in a redirection list.
9022 static void fixredir(union node *, const char *, int);
9024 expredir(union node *n)
9028 for (redir = n; redir; redir = redir->nfile.next) {
9032 fn.lastp = &fn.list;
9033 switch (redir->type) {
9037 #if BASH_REDIR_OUTPUT
9042 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9043 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9044 #if BASH_REDIR_OUTPUT
9048 // By the design of stack allocator, the loop of this kind:
9049 // while true; do while true; do break; done </dev/null; done
9050 // will look like a memory leak: ash plans to free expfname's
9051 // of "/dev/null" as soon as it finishes running the loop
9052 // (in this case, never).
9053 // This "fix" is wrong:
9054 if (redir->nfile.expfname)
9055 stunalloc(redir->nfile.expfname);
9056 // It results in corrupted state of stacked allocations.
9058 redir->nfile.expfname = fn.list->text;
9061 case NTOFD: /* >& */
9062 if (redir->ndup.vname) {
9063 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9064 if (fn.list == NULL)
9065 ash_msg_and_raise_error("redir error");
9066 #if BASH_REDIR_OUTPUT
9067 //FIXME: we used expandarg with different args!
9068 if (!isdigit_str9(fn.list->text)) {
9069 /* >&file, not >&fd */
9070 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9071 ash_msg_and_raise_error("redir error");
9073 goto store_expfname;
9076 fixredir(redir, fn.list->text, 1);
9084 * Evaluate a pipeline. All the processes in the pipeline are children
9085 * of the process creating the pipeline. (This differs from some versions
9086 * of the shell, which make the last process in a pipeline the parent
9090 evalpipe(union node *n, int flags)
9093 struct nodelist *lp;
9099 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9101 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9105 if (n->npipe.pipe_backgnd == 0)
9107 jp = makejob(/*n,*/ pipelen);
9109 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9113 if (pipe(pip) < 0) {
9115 ash_msg_and_raise_error("pipe call failed");
9118 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9132 evaltreenr(lp->n, flags);
9139 /* Don't want to trigger debugging */
9143 if (n->npipe.pipe_backgnd == 0) {
9144 status = waitforjob(jp);
9145 TRACE(("evalpipe: job done exit status %d\n", status));
9153 * Controls whether the shell is interactive or not.
9156 setinteractive(int on)
9158 static smallint is_interactive;
9160 if (++on == is_interactive)
9162 is_interactive = on;
9166 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9167 if (is_interactive > 1) {
9168 /* Looks like they want an interactive shell */
9169 static smallint did_banner;
9172 /* note: ash and hush share this string */
9173 out1fmt("\n\n%s %s\n"
9174 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9177 "built-in shell (ash)"
9191 setinteractive(iflag);
9193 #if ENABLE_FEATURE_EDITING_VI
9195 line_input_state->flags |= VI_MODE;
9197 line_input_state->flags &= ~VI_MODE;
9199 viflag = 0; /* forcibly keep the option off */
9203 static struct localvar *localvars;
9206 * Called after a function returns.
9207 * Interrupts must be off.
9212 struct localvar *lvp;
9215 while ((lvp = localvars) != NULL) {
9216 localvars = lvp->next;
9218 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9219 if (vp == NULL) { /* $- saved */
9220 memcpy(optlist, lvp->text, sizeof(optlist));
9221 free((char*)lvp->text);
9223 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9224 unsetvar(vp->var_text);
9227 vp->var_func(var_end(lvp->text));
9228 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9229 free((char*)vp->var_text);
9230 vp->flags = lvp->flags;
9231 vp->var_text = lvp->text;
9238 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9240 volatile struct shparam saveparam;
9241 struct localvar *volatile savelocalvars;
9242 struct jmploc *volatile savehandler;
9243 struct jmploc jmploc;
9246 saveparam = shellparam;
9247 savelocalvars = localvars;
9248 savehandler = exception_handler;
9249 e = setjmp(jmploc.loc);
9254 exception_handler = &jmploc;
9256 shellparam.malloced = 0;
9260 shellparam.nparam = argc - 1;
9261 shellparam.p = argv + 1;
9262 #if ENABLE_ASH_GETOPTS
9263 shellparam.optind = 1;
9264 shellparam.optoff = -1;
9266 evaltree(func->n.narg.next, flags & EV_TESTED);
9272 localvars = savelocalvars;
9273 freeparam(&shellparam);
9274 shellparam = saveparam;
9275 exception_handler = savehandler;
9277 evalskip &= ~SKIPFUNC;
9282 * Make a variable a local variable. When a variable is made local, it's
9283 * value and flags are saved in a localvar structure. The saved values
9284 * will be restored when the shell function returns. We handle the name
9285 * "-" as a special case: it makes changes to "set +-options" local
9286 * (options will be restored on return from the function).
9291 struct localvar *lvp;
9294 char *eq = strchr(name, '=');
9297 /* Cater for duplicate "local". Examples:
9298 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9299 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9303 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9307 * it's a duplicate "local VAR" declaration, do nothing
9314 lvp = ckzalloc(sizeof(*lvp));
9315 if (LONE_DASH(name)) {
9317 p = ckmalloc(sizeof(optlist));
9318 lvp->text = memcpy(p, optlist, sizeof(optlist));
9321 vpp = hashvar(name);
9322 vp = *findvar(vpp, name);
9324 /* variable did not exist yet */
9326 setvareq(name, VSTRFIXED);
9328 setvar(name, NULL, VSTRFIXED);
9329 vp = *vpp; /* the new variable */
9330 lvp->flags = VUNSET;
9332 lvp->text = vp->var_text;
9333 lvp->flags = vp->flags;
9334 /* make sure neither "struct var" nor string gets freed
9335 * during (un)setting:
9337 vp->flags |= VSTRFIXED|VTEXTFIXED;
9341 /* "local VAR" unsets VAR: */
9342 setvar0(name, NULL);
9346 lvp->next = localvars;
9353 * The "local" command.
9355 static int FAST_FUNC
9356 localcmd(int argc UNUSED_PARAM, char **argv)
9361 ash_msg_and_raise_error("not in a function");
9364 while ((name = *argv++) != NULL) {
9370 static int FAST_FUNC
9371 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9376 static int FAST_FUNC
9377 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9382 static int FAST_FUNC
9383 execcmd(int argc UNUSED_PARAM, char **argv)
9386 while (nextopt("a:") != '\0')
9387 /* nextopt() sets optionarg to "-a ARGV0" */;
9393 iflag = 0; /* exit on error */
9396 /* We should set up signals for "exec CMD"
9397 * the same way as for "CMD" without "exec".
9398 * But optschanged->setinteractive->setsignal
9399 * still thought we are a root shell. Therefore, for example,
9400 * SIGQUIT is still set to IGN. Fix it:
9404 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9405 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9406 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9410 argv[0] = optionarg;
9411 shellexec(prog, argv, pathval(), 0);
9418 * The return command.
9420 static int FAST_FUNC
9421 returncmd(int argc UNUSED_PARAM, char **argv)
9424 * If called outside a function, do what ksh does;
9425 * skip the rest of the file.
9427 evalskip = SKIPFUNC;
9428 return argv[1] ? number(argv[1]) : exitstatus;
9431 /* Forward declarations for builtintab[] */
9432 static int breakcmd(int, char **) FAST_FUNC;
9433 static int dotcmd(int, char **) FAST_FUNC;
9434 static int evalcmd(int, char **, int) FAST_FUNC;
9435 static int exitcmd(int, char **) FAST_FUNC;
9436 static int exportcmd(int, char **) FAST_FUNC;
9437 #if ENABLE_ASH_GETOPTS
9438 static int getoptscmd(int, char **) FAST_FUNC;
9441 static int helpcmd(int, char **) FAST_FUNC;
9444 static int historycmd(int, char **) FAST_FUNC;
9446 #if ENABLE_FEATURE_SH_MATH
9447 static int letcmd(int, char **) FAST_FUNC;
9449 static int readcmd(int, char **) FAST_FUNC;
9450 static int setcmd(int, char **) FAST_FUNC;
9451 static int shiftcmd(int, char **) FAST_FUNC;
9452 static int timescmd(int, char **) FAST_FUNC;
9453 static int trapcmd(int, char **) FAST_FUNC;
9454 static int umaskcmd(int, char **) FAST_FUNC;
9455 static int unsetcmd(int, char **) FAST_FUNC;
9456 static int ulimitcmd(int, char **) FAST_FUNC;
9458 #define BUILTIN_NOSPEC "0"
9459 #define BUILTIN_SPECIAL "1"
9460 #define BUILTIN_REGULAR "2"
9461 #define BUILTIN_SPEC_REG "3"
9462 #define BUILTIN_ASSIGN "4"
9463 #define BUILTIN_SPEC_ASSG "5"
9464 #define BUILTIN_REG_ASSG "6"
9465 #define BUILTIN_SPEC_REG_ASSG "7"
9467 /* Stubs for calling non-FAST_FUNC's */
9469 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9471 #if ENABLE_ASH_PRINTF
9472 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9474 #if ENABLE_ASH_TEST || BASH_TEST2
9475 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9478 /* Keep these in proper order since it is searched via bsearch() */
9479 static const struct builtincmd builtintab[] = {
9480 { BUILTIN_SPEC_REG "." , dotcmd },
9481 { BUILTIN_SPEC_REG ":" , truecmd },
9483 { BUILTIN_REGULAR "[" , testcmd },
9486 { BUILTIN_REGULAR "[[" , testcmd },
9488 #if ENABLE_ASH_ALIAS
9489 { BUILTIN_REG_ASSG "alias" , aliascmd },
9492 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9494 { BUILTIN_SPEC_REG "break" , breakcmd },
9495 { BUILTIN_REGULAR "cd" , cdcmd },
9496 { BUILTIN_NOSPEC "chdir" , cdcmd },
9497 #if ENABLE_ASH_CMDCMD
9498 { BUILTIN_REGULAR "command" , commandcmd },
9500 { BUILTIN_SPEC_REG "continue", breakcmd },
9502 { BUILTIN_REGULAR "echo" , echocmd },
9504 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9505 { BUILTIN_SPEC_REG "exec" , execcmd },
9506 { BUILTIN_SPEC_REG "exit" , exitcmd },
9507 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9508 { BUILTIN_REGULAR "false" , falsecmd },
9510 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9512 #if ENABLE_ASH_GETOPTS
9513 { BUILTIN_REGULAR "getopts" , getoptscmd },
9515 { BUILTIN_NOSPEC "hash" , hashcmd },
9517 { BUILTIN_NOSPEC "help" , helpcmd },
9520 { BUILTIN_NOSPEC "history" , historycmd },
9523 { BUILTIN_REGULAR "jobs" , jobscmd },
9524 { BUILTIN_REGULAR "kill" , killcmd },
9526 #if ENABLE_FEATURE_SH_MATH
9527 { BUILTIN_NOSPEC "let" , letcmd },
9529 { BUILTIN_ASSIGN "local" , localcmd },
9530 #if ENABLE_ASH_PRINTF
9531 { BUILTIN_REGULAR "printf" , printfcmd },
9533 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9534 { BUILTIN_REGULAR "read" , readcmd },
9535 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9536 { BUILTIN_SPEC_REG "return" , returncmd },
9537 { BUILTIN_SPEC_REG "set" , setcmd },
9538 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9540 { BUILTIN_SPEC_REG "source" , dotcmd },
9543 { BUILTIN_REGULAR "test" , testcmd },
9545 { BUILTIN_SPEC_REG "times" , timescmd },
9546 { BUILTIN_SPEC_REG "trap" , trapcmd },
9547 { BUILTIN_REGULAR "true" , truecmd },
9548 { BUILTIN_NOSPEC "type" , typecmd },
9549 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9550 { BUILTIN_REGULAR "umask" , umaskcmd },
9551 #if ENABLE_ASH_ALIAS
9552 { BUILTIN_REGULAR "unalias" , unaliascmd },
9554 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9555 { BUILTIN_REGULAR "wait" , waitcmd },
9558 /* Should match the above table! */
9559 #define COMMANDCMD (builtintab + \
9561 /* [ */ 1 * ENABLE_ASH_TEST + \
9562 /* [[ */ 1 * BASH_TEST2 + \
9563 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9564 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9565 /* break cd cddir */ 3)
9566 #define EVALCMD (COMMANDCMD + \
9567 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9568 /* continue */ 1 + \
9569 /* echo */ 1 * ENABLE_ASH_ECHO + \
9571 #define EXECCMD (EVALCMD + \
9575 * Search the table of builtin commands.
9578 pstrcmp1(const void *a, const void *b)
9580 return strcmp((char*)a, *(char**)b + 1);
9582 static struct builtincmd *
9583 find_builtin(const char *name)
9585 struct builtincmd *bp;
9588 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9595 * Execute a simple command.
9598 isassignment(const char *p)
9600 const char *q = endofname(p);
9605 static int FAST_FUNC
9606 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9608 /* Preserve exitstatus of a previous possible redirection
9609 * as POSIX mandates */
9610 return back_exitstatus;
9613 evalcommand(union node *cmd, int flags)
9615 static const struct builtincmd null_bltin = {
9616 "\0\0", bltincmd /* why three NULs? */
9618 struct stackmark smark;
9620 struct arglist arglist;
9621 struct arglist varlist;
9624 const struct strlist *sp;
9625 struct cmdentry cmdentry;
9632 struct builtincmd *bcmd;
9633 smallint cmd_is_exec;
9634 smallint pseudovarflag = 0;
9636 /* First expand the arguments. */
9637 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9638 setstackmark(&smark);
9639 back_exitstatus = 0;
9641 cmdentry.cmdtype = CMDBUILTIN;
9642 cmdentry.u.cmd = &null_bltin;
9643 varlist.lastp = &varlist.list;
9644 *varlist.lastp = NULL;
9645 arglist.lastp = &arglist.list;
9646 *arglist.lastp = NULL;
9649 if (cmd->ncmd.args) {
9650 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9651 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9654 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9655 struct strlist **spp;
9657 spp = arglist.lastp;
9658 if (pseudovarflag && isassignment(argp->narg.text))
9659 expandarg(argp, &arglist, EXP_VARTILDE);
9661 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9663 for (sp = *spp; sp; sp = sp->next)
9667 /* Reserve one extra spot at the front for shellexec. */
9668 nargv = stalloc(sizeof(char *) * (argc + 2));
9670 for (sp = arglist.list; sp; sp = sp->next) {
9671 TRACE(("evalcommand arg: %s\n", sp->text));
9672 *nargv++ = sp->text;
9677 if (iflag && funcnest == 0 && argc > 0)
9678 lastarg = nargv[-1];
9681 expredir(cmd->ncmd.redirect);
9682 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9684 path = vpath.var_text;
9685 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9686 struct strlist **spp;
9689 spp = varlist.lastp;
9690 expandarg(argp, &varlist, EXP_VARTILDE);
9693 * Modify the command lookup path, if a PATH= assignment
9697 if (varcmp(p, path) == 0)
9701 /* Print the command if xflag is set. */
9704 const char *p = " %s" + 1;
9706 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9708 for (n = 0; n < 2; n++) {
9710 fdprintf(preverrout_fd, p, sp->text);
9716 safe_write(preverrout_fd, "\n", 1);
9722 /* Now locate the command. */
9724 int cmd_flag = DO_ERR;
9725 #if ENABLE_ASH_CMDCMD
9726 const char *oldpath = path + 5;
9730 find_command(argv[0], &cmdentry, cmd_flag, path);
9731 if (cmdentry.cmdtype == CMDUNKNOWN) {
9732 flush_stdout_stderr();
9737 /* implement bltin and command here */
9738 if (cmdentry.cmdtype != CMDBUILTIN)
9741 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9742 if (cmdentry.u.cmd == EXECCMD)
9744 #if ENABLE_ASH_CMDCMD
9745 if (cmdentry.u.cmd == COMMANDCMD) {
9747 nargv = parse_command_args(argv, &path);
9750 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9751 * nargv => "PROG". path is updated if -p.
9753 argc -= nargv - argv;
9755 cmd_flag |= DO_NOFUNC;
9764 exitstatus = status;
9766 /* We have a redirection error. */
9768 raise_exception(EXERROR);
9773 /* Execute the command. */
9774 switch (cmdentry.cmdtype) {
9777 #if ENABLE_FEATURE_SH_NOFORK
9778 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9779 * around run_nofork_applet() call.
9780 * (2) Should this check also be done in forkshell()?
9781 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9783 /* find_command() encodes applet_no as (-2 - applet_no) */
9784 int applet_no = (- cmdentry.u.index - 2);
9785 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9786 listsetvar(varlist.list, VEXPORT|VSTACK);
9787 /* run <applet>_main() */
9788 status = run_nofork_applet(applet_no, argv);
9792 /* Can we avoid forking off? For example, very last command
9793 * in a script or a subshell does not need forking,
9794 * we can just exec it.
9796 if (!(flags & EV_EXIT) || may_have_traps) {
9797 /* No, forking off a child is necessary */
9800 jp = makejob(/*cmd,*/ 1);
9801 if (forkshell(jp, cmd, FORK_FG) != 0) {
9803 status = waitforjob(jp);
9805 TRACE(("forked child exited with %d\n", status));
9810 /* fall through to exec'ing external program */
9812 listsetvar(varlist.list, VEXPORT|VSTACK);
9813 shellexec(argv[0], argv, path, cmdentry.u.index);
9817 cmdenviron = varlist.list;
9819 struct strlist *list = cmdenviron;
9821 if (spclbltin > 0 || argc == 0) {
9823 if (cmd_is_exec && argc > 1)
9826 listsetvar(list, i);
9828 /* Tight loop with builtins only:
9829 * "while kill -0 $child; do true; done"
9830 * will never exit even if $child died, unless we do this
9831 * to reap the zombie and make kill detect that it's gone: */
9832 dowait(DOWAIT_NONBLOCK, NULL);
9834 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9835 if (exception_type == EXERROR && spclbltin <= 0) {
9840 longjmp(exception_handler->loc, 1);
9845 listsetvar(varlist.list, 0);
9846 /* See above for the rationale */
9847 dowait(DOWAIT_NONBLOCK, NULL);
9848 if (evalfun(cmdentry.u.func, argc, argv, flags))
9851 status = exitstatus;
9856 if (cmd->ncmd.redirect)
9857 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9859 /* dsl: I think this is intended to be used to support
9860 * '_' in 'vi' command mode during line editing...
9861 * However I implemented that within libedit itself.
9863 setvar0("_", lastarg);
9865 popstackmark(&smark);
9871 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9873 char *volatile savecmdname;
9874 struct jmploc *volatile savehandler;
9875 struct jmploc jmploc;
9879 savecmdname = commandname;
9880 savehandler = exception_handler;
9881 i = setjmp(jmploc.loc);
9884 exception_handler = &jmploc;
9885 commandname = argv[0];
9887 optptr = NULL; /* initialize nextopt */
9889 status = evalcmd(argc, argv, flags);
9891 status = (*cmd->builtin)(argc, argv);
9892 flush_stdout_stderr();
9893 status |= ferror(stdout);
9894 exitstatus = status;
9897 commandname = savecmdname;
9898 exception_handler = savehandler;
9904 goodname(const char *p)
9906 return endofname(p)[0] == '\0';
9911 * Search for a command. This is called before we fork so that the
9912 * location of the command will be available in the parent as well as
9913 * the child. The check for "goodname" is an overly conservative
9914 * check that the name will not be subject to expansion.
9917 prehash(union node *n)
9919 struct cmdentry entry;
9921 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9922 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9926 /* ============ Builtin commands
9928 * Builtin commands whose functions are closely tied to evaluation
9929 * are implemented here.
9933 * Handle break and continue commands. Break, continue, and return are
9934 * all handled by setting the evalskip flag. The evaluation routines
9935 * above all check this flag, and if it is set they start skipping
9936 * commands rather than executing them. The variable skipcount is
9937 * the number of loops to break/continue, or the number of function
9938 * levels to return. (The latter is always 1.) It should probably
9939 * be an error to break out of more loops than exist, but it isn't
9940 * in the standard shell so we don't make it one here.
9942 static int FAST_FUNC
9943 breakcmd(int argc UNUSED_PARAM, char **argv)
9945 int n = argv[1] ? number(argv[1]) : 1;
9948 ash_msg_and_raise_error(msg_illnum, argv[1]);
9952 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9960 * This implements the input routines used by the parser.
9964 INPUT_PUSH_FILE = 1,
9965 INPUT_NOFILE_OK = 2,
9968 static smallint checkkwd;
9969 /* values of checkkwd variable */
9970 #define CHKALIAS 0x1
9975 * Push a string back onto the input at this current parsefile level.
9976 * We handle aliases this way.
9978 #if !ENABLE_ASH_ALIAS
9979 #define pushstring(s, ap) pushstring(s)
9982 pushstring(char *s, struct alias *ap)
9989 if (g_parsefile->strpush) {
9990 sp = ckzalloc(sizeof(*sp));
9991 sp->prev = g_parsefile->strpush;
9993 sp = &(g_parsefile->basestrpush);
9995 g_parsefile->strpush = sp;
9996 sp->prev_string = g_parsefile->next_to_pgetc;
9997 sp->prev_left_in_line = g_parsefile->left_in_line;
9998 sp->unget = g_parsefile->unget;
9999 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10000 #if ENABLE_ASH_ALIAS
10003 ap->flag |= ALIASINUSE;
10007 g_parsefile->next_to_pgetc = s;
10008 g_parsefile->left_in_line = len;
10009 g_parsefile->unget = 0;
10016 struct strpush *sp = g_parsefile->strpush;
10019 #if ENABLE_ASH_ALIAS
10021 if (g_parsefile->next_to_pgetc[-1] == ' '
10022 || g_parsefile->next_to_pgetc[-1] == '\t'
10024 checkkwd |= CHKALIAS;
10026 if (sp->string != sp->ap->val) {
10029 sp->ap->flag &= ~ALIASINUSE;
10030 if (sp->ap->flag & ALIASDEAD) {
10031 unalias(sp->ap->name);
10035 g_parsefile->next_to_pgetc = sp->prev_string;
10036 g_parsefile->left_in_line = sp->prev_left_in_line;
10037 g_parsefile->unget = sp->unget;
10038 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10039 g_parsefile->strpush = sp->prev;
10040 if (sp != &(g_parsefile->basestrpush))
10049 char *buf = g_parsefile->buf;
10051 g_parsefile->next_to_pgetc = buf;
10052 #if ENABLE_FEATURE_EDITING
10054 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10055 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10058 # if ENABLE_ASH_IDLE_TIMEOUT
10060 const char *tmout_var = lookupvar("TMOUT");
10062 timeout = atoi(tmout_var) * 1000;
10068 # if ENABLE_FEATURE_TAB_COMPLETION
10069 line_input_state->path_lookup = pathval();
10071 reinit_unicode_for_ash();
10072 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10074 /* ^C pressed, "convert" to SIGINT */
10075 write(STDOUT_FILENO, "^C", 2);
10076 if (trap[SIGINT]) {
10082 exitstatus = 128 + SIGINT;
10088 /* Ctrl+D pressed */
10091 # if ENABLE_ASH_IDLE_TIMEOUT
10092 else if (errno == EAGAIN && timeout > 0) {
10093 puts("\007timed out waiting for input: auto-logout");
10100 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10103 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10105 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10106 int flags = fcntl(0, F_GETFL);
10107 if (flags >= 0 && (flags & O_NONBLOCK)) {
10108 flags &= ~O_NONBLOCK;
10109 if (fcntl(0, F_SETFL, flags) >= 0) {
10110 out2str("sh: turning off NDELAY mode\n");
10121 * Refill the input buffer and return the next input character:
10123 * 1) If a string was pushed back on the input, pop it;
10124 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10125 * or we are reading from a string so we can't refill the buffer,
10127 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10128 * 4) Process input up to the next newline, deleting nul characters.
10130 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10131 #define pgetc_debug(...) ((void)0)
10132 static int pgetc(void);
10139 if (g_parsefile->strpush) {
10140 #if ENABLE_ASH_ALIAS
10141 if (g_parsefile->left_in_line == -1
10142 && g_parsefile->strpush->ap
10143 && g_parsefile->next_to_pgetc[-1] != ' '
10144 && g_parsefile->next_to_pgetc[-1] != '\t'
10146 pgetc_debug("preadbuffer PEOA");
10153 /* on both branches above g_parsefile->left_in_line < 0.
10154 * "pgetc" needs refilling.
10157 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10158 * pungetc() may increment it a few times.
10159 * Assuming it won't increment it to less than -90.
10161 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10162 pgetc_debug("preadbuffer PEOF1");
10163 /* even in failure keep left_in_line and next_to_pgetc
10164 * in lock step, for correct multi-layer pungetc.
10165 * left_in_line was decremented before preadbuffer(),
10166 * must inc next_to_pgetc: */
10167 g_parsefile->next_to_pgetc++;
10171 more = g_parsefile->left_in_buffer;
10173 flush_stdout_stderr();
10177 /* don't try reading again */
10178 g_parsefile->left_in_line = -99;
10179 pgetc_debug("preadbuffer PEOF2");
10180 g_parsefile->next_to_pgetc++;
10185 /* Find out where's the end of line.
10186 * Set g_parsefile->left_in_line
10187 * and g_parsefile->left_in_buffer acordingly.
10188 * NUL chars are deleted.
10190 q = g_parsefile->next_to_pgetc;
10198 memmove(q, q + 1, more);
10202 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10208 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10209 if (g_parsefile->left_in_line < 0)
10214 g_parsefile->left_in_buffer = more;
10219 out2str(g_parsefile->next_to_pgetc);
10223 pgetc_debug("preadbuffer at %d:%p'%s'",
10224 g_parsefile->left_in_line,
10225 g_parsefile->next_to_pgetc,
10226 g_parsefile->next_to_pgetc);
10227 return (unsigned char)*g_parsefile->next_to_pgetc++;
10233 g_parsefile->linno++;
10234 setprompt_if(doprompt, 2);
10239 g_parsefile->linno++;
10240 needprompt = doprompt;
10248 pgetc_debug("pgetc at %d:%p'%s'",
10249 g_parsefile->left_in_line,
10250 g_parsefile->next_to_pgetc,
10251 g_parsefile->next_to_pgetc);
10252 if (g_parsefile->unget)
10253 return g_parsefile->lastc[--g_parsefile->unget];
10255 if (--g_parsefile->left_in_line >= 0)
10256 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10260 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10261 g_parsefile->lastc[0] = c;
10266 #if ENABLE_ASH_ALIAS
10268 pgetc_without_PEOA(void)
10272 pgetc_debug("pgetc at %d:%p'%s'",
10273 g_parsefile->left_in_line,
10274 g_parsefile->next_to_pgetc,
10275 g_parsefile->next_to_pgetc);
10277 } while (c == PEOA);
10281 # define pgetc_without_PEOA() pgetc()
10285 * Read a line from the script.
10288 pfgets(char *line, int len)
10294 while (--nleft > 0) {
10295 c = pgetc_without_PEOA();
10310 * Undo a call to pgetc. Only two characters may be pushed back.
10311 * PEOF may be pushed back.
10316 g_parsefile->unget++;
10319 /* This one eats backslash+newline */
10325 while ((c = pgetc()) == '\\') {
10326 if (pgetc() != '\n') {
10338 * To handle the "." command, a stack of input files is used. Pushfile
10339 * adds a new entry to the stack and popfile restores the previous level.
10344 struct parsefile *pf;
10346 pf = ckzalloc(sizeof(*pf));
10347 pf->prev = g_parsefile;
10349 /*pf->strpush = NULL; - ckzalloc did it */
10350 /*pf->basestrpush.prev = NULL;*/
10358 struct parsefile *pf = g_parsefile;
10364 if (pf->pf_fd >= 0)
10367 while (pf->strpush)
10369 g_parsefile = pf->prev;
10375 * Return to top level.
10380 while (g_parsefile != &basepf)
10385 * Close the file(s) that the shell is reading commands from. Called
10386 * after a fork is done.
10392 if (g_parsefile->pf_fd > 0) {
10393 close(g_parsefile->pf_fd);
10394 g_parsefile->pf_fd = 0;
10399 * Like setinputfile, but takes an open file descriptor. Call this with
10403 setinputfd(int fd, int push)
10407 g_parsefile->buf = NULL;
10409 g_parsefile->pf_fd = fd;
10410 if (g_parsefile->buf == NULL)
10411 g_parsefile->buf = ckmalloc(IBUFSIZ);
10412 g_parsefile->left_in_buffer = 0;
10413 g_parsefile->left_in_line = 0;
10414 g_parsefile->linno = 1;
10418 * Set the input to take input from a file. If push is set, push the
10419 * old input onto the stack first.
10422 setinputfile(const char *fname, int flags)
10427 fd = open(fname, O_RDONLY);
10429 if (flags & INPUT_NOFILE_OK)
10432 ash_msg_and_raise_error("can't open '%s'", fname);
10437 close_on_exec_on(fd);
10438 setinputfd(fd, flags & INPUT_PUSH_FILE);
10445 * Like setinputfile, but takes input from a string.
10448 setinputstring(char *string)
10452 g_parsefile->next_to_pgetc = string;
10453 g_parsefile->left_in_line = strlen(string);
10454 g_parsefile->buf = NULL;
10455 g_parsefile->linno = 1;
10461 * Routines to check for mail.
10464 #if ENABLE_ASH_MAIL
10466 /* Hash of mtimes of mailboxes */
10467 static unsigned mailtime_hash;
10468 /* Set if MAIL or MAILPATH is changed. */
10469 static smallint mail_var_path_changed;
10472 * Print appropriate message(s) if mail has arrived.
10473 * If mail_var_path_changed is set,
10474 * then the value of MAIL has mail_var_path_changed,
10475 * so we just update the values.
10484 struct stackmark smark;
10487 setstackmark(&smark);
10488 mpath = mpathset() ? mpathval() : mailval();
10491 p = path_advance(&mpath, nullstr);
10496 for (q = p; *q; q++)
10502 q[-1] = '\0'; /* delete trailing '/' */
10503 if (stat(p, &statb) < 0) {
10506 /* Very simplistic "hash": just a sum of all mtimes */
10507 new_hash += (unsigned)statb.st_mtime;
10509 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10510 if (mailtime_hash != 0)
10511 out2str("you have mail\n");
10512 mailtime_hash = new_hash;
10514 mail_var_path_changed = 0;
10515 popstackmark(&smark);
10518 static void FAST_FUNC
10519 changemail(const char *val UNUSED_PARAM)
10521 mail_var_path_changed = 1;
10524 #endif /* ASH_MAIL */
10527 /* ============ ??? */
10530 * Set the shell parameters.
10533 setparam(char **argv)
10539 for (nparam = 0; argv[nparam]; nparam++)
10541 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10543 *ap++ = ckstrdup(*argv++);
10546 freeparam(&shellparam);
10547 shellparam.malloced = 1;
10548 shellparam.nparam = nparam;
10549 shellparam.p = newparam;
10550 #if ENABLE_ASH_GETOPTS
10551 shellparam.optind = 1;
10552 shellparam.optoff = -1;
10557 * Process shell options. The global variable argptr contains a pointer
10558 * to the argument list; we advance it past the options.
10560 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10561 * For a non-interactive shell, an error condition encountered
10562 * by a special built-in ... shall cause the shell to write a diagnostic message
10563 * to standard error and exit as shown in the following table:
10564 * Error Special Built-In
10566 * Utility syntax error (option or operand error) Shall exit
10568 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10569 * we see that bash does not do that (set "finishes" with error code 1 instead,
10570 * and shell continues), and people rely on this behavior!
10572 * set -o barfoo 2>/dev/null
10575 * Oh well. Let's mimic that.
10578 plus_minus_o(char *name, int val)
10583 for (i = 0; i < NOPTS; i++) {
10584 if (strcmp(name, optnames(i)) == 0) {
10589 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10592 for (i = 0; i < NOPTS; i++) {
10594 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10596 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10602 setoption(int flag, int val)
10606 for (i = 0; i < NOPTS; i++) {
10607 if (optletters(i) == flag) {
10612 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10616 options(int cmdline)
10624 while ((p = *argptr) != NULL) {
10626 if (c != '-' && c != '+')
10629 val = 0; /* val = 0 if c == '+' */
10632 if (p[0] == '\0' || LONE_DASH(p)) {
10634 /* "-" means turn off -x and -v */
10637 /* "--" means reset params */
10638 else if (*argptr == NULL)
10641 break; /* "-" or "--" terminates options */
10644 /* first char was + or - */
10645 while ((c = *p++) != '\0') {
10646 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10647 if (c == 'c' && cmdline) {
10648 minusc = p; /* command is after shell args */
10649 } else if (c == 'o') {
10650 if (plus_minus_o(*argptr, val)) {
10651 /* it already printed err message */
10652 return 1; /* error */
10656 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10658 /* bash does not accept +-login, we also won't */
10659 } else if (cmdline && val && (c == '-')) { /* long options */
10660 if (strcmp(p, "login") == 0)
10672 * The shift builtin command.
10674 static int FAST_FUNC
10675 shiftcmd(int argc UNUSED_PARAM, char **argv)
10682 n = number(argv[1]);
10683 if (n > shellparam.nparam)
10684 n = 0; /* bash compat, was = shellparam.nparam; */
10686 shellparam.nparam -= n;
10687 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10688 if (shellparam.malloced)
10691 ap2 = shellparam.p;
10692 while ((*ap2++ = *ap1++) != NULL)
10694 #if ENABLE_ASH_GETOPTS
10695 shellparam.optind = 1;
10696 shellparam.optoff = -1;
10703 * POSIX requires that 'set' (but not export or readonly) output the
10704 * variables in lexicographic order - by the locale's collating order (sigh).
10705 * Maybe we could keep them in an ordered balanced binary tree
10706 * instead of hashed lists.
10707 * For now just roll 'em through qsort for printing...
10710 showvars(const char *sep_prefix, int on, int off)
10713 char **ep, **epend;
10715 ep = listvars(on, off, &epend);
10716 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10718 sep = *sep_prefix ? " " : sep_prefix;
10720 for (; ep < epend; ep++) {
10724 p = strchrnul(*ep, '=');
10727 q = single_quote(++p);
10728 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10734 * The set command builtin.
10736 static int FAST_FUNC
10737 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10742 return showvars(nullstr, 0, VUNSET);
10745 retval = options(/*cmdline:*/ 0);
10746 if (retval == 0) { /* if no parse error... */
10748 if (*argptr != NULL) {
10756 #if ENABLE_ASH_RANDOM_SUPPORT
10757 static void FAST_FUNC
10758 change_random(const char *value)
10762 if (value == NULL) {
10763 /* "get", generate */
10764 t = next_random(&random_gen);
10765 /* set without recursion */
10766 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10767 vrandom.flags &= ~VNOFUNC;
10770 t = strtoul(value, NULL, 10);
10771 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10776 #if ENABLE_ASH_GETOPTS
10778 getopts(char *optstr, char *optvar, char **optfirst)
10785 int ind = shellparam.optind;
10786 int off = shellparam.optoff;
10790 shellparam.optind = -1;
10791 optnext = optfirst + ind - 1;
10793 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10796 p = optnext[-1] + off;
10797 if (p == NULL || *p == '\0') {
10798 /* Current word is done, advance */
10800 if (p == NULL || *p != '-' || *++p == '\0') {
10807 if (LONE_DASH(p)) /* check for "--" */
10812 for (q = optstr; *q != c;) {
10814 if (optstr[0] == ':') {
10816 /*sbuf[1] = '\0'; - already is */
10817 setvar0("OPTARG", sbuf);
10819 fprintf(stderr, "Illegal option -%c\n", c);
10820 unsetvar("OPTARG");
10830 if (*p == '\0' && (p = *optnext) == NULL) {
10831 if (optstr[0] == ':') {
10833 /*sbuf[1] = '\0'; - already is */
10834 setvar0("OPTARG", sbuf);
10837 fprintf(stderr, "No arg for -%c option\n", c);
10838 unsetvar("OPTARG");
10846 setvar0("OPTARG", p);
10849 setvar0("OPTARG", nullstr);
10851 ind = optnext - optfirst + 1;
10852 setvar("OPTIND", itoa(ind), VNOFUNC);
10854 /*sbuf[1] = '\0'; - already is */
10855 setvar0(optvar, sbuf);
10857 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10858 shellparam.optind = ind;
10864 * The getopts builtin. Shellparam.optnext points to the next argument
10865 * to be processed. Shellparam.optptr points to the next character to
10866 * be processed in the current argument. If shellparam.optnext is NULL,
10867 * then it's the first time getopts has been called.
10869 static int FAST_FUNC
10870 getoptscmd(int argc, char **argv)
10875 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10877 optbase = shellparam.p;
10878 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10879 shellparam.optind = 1;
10880 shellparam.optoff = -1;
10883 optbase = &argv[3];
10884 if ((unsigned)shellparam.optind > argc - 2) {
10885 shellparam.optind = 1;
10886 shellparam.optoff = -1;
10890 return getopts(argv[1], argv[2], optbase);
10892 #endif /* ASH_GETOPTS */
10895 /* ============ Shell parser */
10898 struct heredoc *next; /* next here document in list */
10899 union node *here; /* redirection node */
10900 char *eofmark; /* string indicating end of input */
10901 smallint striptabs; /* if set, strip leading tabs */
10904 static smallint tokpushback; /* last token pushed back */
10905 static smallint quoteflag; /* set if (part of) last token was quoted */
10906 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10907 static struct heredoc *heredoclist; /* list of here documents to read */
10908 static char *wordtext; /* text of last word returned by readtoken */
10909 static struct nodelist *backquotelist;
10910 static union node *redirnode;
10911 static struct heredoc *heredoc;
10913 static const char *
10914 tokname(char *buf, int tok)
10917 return tokname_array[tok];
10918 sprintf(buf, "\"%s\"", tokname_array[tok]);
10922 /* raise_error_unexpected_syntax:
10923 * Called when an unexpected token is read during the parse. The argument
10924 * is the token that is expected, or -1 if more than one type of token can
10925 * occur at this point.
10927 static void raise_error_unexpected_syntax(int) NORETURN;
10929 raise_error_unexpected_syntax(int token)
10935 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10937 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10938 raise_error_syntax(msg);
10942 #define EOFMARKLEN 79
10944 /* parsing is heavily cross-recursive, need these forward decls */
10945 static union node *andor(void);
10946 static union node *pipeline(void);
10947 static union node *parse_command(void);
10948 static void parseheredoc(void);
10949 static int peektoken(void);
10950 static int readtoken(void);
10952 static union node *
10955 union node *n1, *n2, *n3;
10960 switch (peektoken()) {
10968 if (!n1 && (nlflag & 1))
10974 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10975 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10981 if (tok == TBACKGND) {
10982 if (n2->type == NPIPE) {
10983 n2->npipe.pipe_backgnd = 1;
10985 if (n2->type != NREDIR) {
10986 n3 = stzalloc(sizeof(struct nredir));
10988 /*n3->nredir.redirect = NULL; - stzalloc did it */
10991 n2->type = NBACKGND;
10997 n3 = stzalloc(sizeof(struct nbinary));
10999 n3->nbinary.ch1 = n1;
11000 n3->nbinary.ch2 = n2;
11013 raise_error_unexpected_syntax(-1);
11020 static union node *
11023 union node *n1, *n2, *n3;
11031 } else if (t == TOR) {
11037 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11039 n3 = stzalloc(sizeof(struct nbinary));
11041 n3->nbinary.ch1 = n1;
11042 n3->nbinary.ch2 = n2;
11047 static union node *
11050 union node *n1, *n2, *pipenode;
11051 struct nodelist *lp, *prev;
11055 TRACE(("pipeline: entered\n"));
11056 if (readtoken() == TNOT) {
11058 checkkwd = CHKKWD | CHKALIAS;
11061 n1 = parse_command();
11062 if (readtoken() == TPIPE) {
11063 pipenode = stzalloc(sizeof(struct npipe));
11064 pipenode->type = NPIPE;
11065 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11066 lp = stzalloc(sizeof(struct nodelist));
11067 pipenode->npipe.cmdlist = lp;
11071 lp = stzalloc(sizeof(struct nodelist));
11072 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11073 lp->n = parse_command();
11075 } while (readtoken() == TPIPE);
11081 n2 = stzalloc(sizeof(struct nnot));
11089 static union node *
11094 n = stzalloc(sizeof(struct narg));
11096 /*n->narg.next = NULL; - stzalloc did it */
11097 n->narg.text = wordtext;
11098 n->narg.backquote = backquotelist;
11103 fixredir(union node *n, const char *text, int err)
11107 TRACE(("Fix redir %s %d\n", text, err));
11109 n->ndup.vname = NULL;
11111 fd = bb_strtou(text, NULL, 10);
11112 if (!errno && fd >= 0)
11113 n->ndup.dupfd = fd;
11114 else if (LONE_DASH(text))
11115 n->ndup.dupfd = -1;
11118 raise_error_syntax("bad fd number");
11119 n->ndup.vname = makename();
11124 * Returns true if the text contains nothing to expand (no dollar signs
11128 noexpand(const char *text)
11132 while ((c = *text++) != '\0') {
11133 if (c == CTLQUOTEMARK)
11137 else if (SIT(c, BASESYNTAX) == CCTL)
11146 union node *n = redirnode;
11148 if (readtoken() != TWORD)
11149 raise_error_unexpected_syntax(-1);
11150 if (n->type == NHERE) {
11151 struct heredoc *here = heredoc;
11155 if (quoteflag == 0)
11157 TRACE(("Here document %d\n", n->type));
11158 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11159 raise_error_syntax("illegal eof marker for << redirection");
11160 rmescapes(wordtext, 0);
11161 here->eofmark = wordtext;
11163 if (heredoclist == NULL)
11164 heredoclist = here;
11166 for (p = heredoclist; p->next; p = p->next)
11170 } else if (n->type == NTOFD || n->type == NFROMFD) {
11171 fixredir(n, wordtext, 0);
11173 n->nfile.fname = makename();
11177 static union node *
11180 union node *args, **app;
11181 union node *n = NULL;
11182 union node *vars, **vpp;
11183 union node **rpp, *redir;
11186 smallint double_brackets_flag = 0;
11188 IF_BASH_FUNCTION(smallint function_flag = 0;)
11197 savecheckkwd = CHKALIAS;
11200 checkkwd = savecheckkwd;
11205 if (peektoken() != TWORD)
11206 raise_error_unexpected_syntax(TWORD);
11211 case TAND: /* "&&" */
11212 case TOR: /* "||" */
11213 if (!double_brackets_flag) {
11217 wordtext = (char *) (t == TAND ? "-a" : "-o");
11220 n = stzalloc(sizeof(struct narg));
11222 /*n->narg.next = NULL; - stzalloc did it */
11223 n->narg.text = wordtext;
11225 if (strcmp("[[", wordtext) == 0)
11226 double_brackets_flag = 1;
11227 else if (strcmp("]]", wordtext) == 0)
11228 double_brackets_flag = 0;
11230 n->narg.backquote = backquotelist;
11231 if (savecheckkwd && isassignment(wordtext)) {
11233 vpp = &n->narg.next;
11236 app = &n->narg.next;
11240 if (function_flag) {
11241 checkkwd = CHKNL | CHKKWD;
11242 switch (peektoken()) {
11254 if (strcmp("[[", wordtext) == 0)
11258 raise_error_unexpected_syntax(-1);
11264 *rpp = n = redirnode;
11265 rpp = &n->nfile.next;
11266 parsefname(); /* read name of redirection file */
11269 IF_BASH_FUNCTION(do_func:)
11270 if (args && app == &args->narg.next
11273 struct builtincmd *bcmd;
11276 /* We have a function */
11277 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11278 raise_error_unexpected_syntax(TRP);
11279 name = n->narg.text;
11280 if (!goodname(name)
11281 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11283 raise_error_syntax("bad function name");
11286 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11287 n->narg.next = parse_command();
11290 IF_BASH_FUNCTION(function_flag = 0;)
11301 n = stzalloc(sizeof(struct ncmd));
11303 n->ncmd.args = args;
11304 n->ncmd.assign = vars;
11305 n->ncmd.redirect = redir;
11309 static union node *
11310 parse_command(void)
11312 union node *n1, *n2;
11313 union node *ap, **app;
11314 union node *cp, **cpp;
11315 union node *redir, **rpp;
11322 switch (readtoken()) {
11324 raise_error_unexpected_syntax(-1);
11327 n1 = stzalloc(sizeof(struct nif));
11329 n1->nif.test = list(0);
11330 if (readtoken() != TTHEN)
11331 raise_error_unexpected_syntax(TTHEN);
11332 n1->nif.ifpart = list(0);
11334 while (readtoken() == TELIF) {
11335 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11336 n2 = n2->nif.elsepart;
11338 n2->nif.test = list(0);
11339 if (readtoken() != TTHEN)
11340 raise_error_unexpected_syntax(TTHEN);
11341 n2->nif.ifpart = list(0);
11343 if (lasttoken == TELSE)
11344 n2->nif.elsepart = list(0);
11346 n2->nif.elsepart = NULL;
11354 n1 = stzalloc(sizeof(struct nbinary));
11355 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11356 n1->nbinary.ch1 = list(0);
11359 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11360 got == TWORD ? wordtext : ""));
11361 raise_error_unexpected_syntax(TDO);
11363 n1->nbinary.ch2 = list(0);
11368 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11369 raise_error_syntax("bad for loop variable");
11370 n1 = stzalloc(sizeof(struct nfor));
11372 n1->nfor.var = wordtext;
11373 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11374 if (readtoken() == TIN) {
11376 while (readtoken() == TWORD) {
11377 n2 = stzalloc(sizeof(struct narg));
11379 /*n2->narg.next = NULL; - stzalloc did it */
11380 n2->narg.text = wordtext;
11381 n2->narg.backquote = backquotelist;
11383 app = &n2->narg.next;
11386 n1->nfor.args = ap;
11387 if (lasttoken != TNL && lasttoken != TSEMI)
11388 raise_error_unexpected_syntax(-1);
11390 n2 = stzalloc(sizeof(struct narg));
11392 /*n2->narg.next = NULL; - stzalloc did it */
11393 n2->narg.text = (char *)dolatstr;
11394 /*n2->narg.backquote = NULL;*/
11395 n1->nfor.args = n2;
11397 * Newline or semicolon here is optional (but note
11398 * that the original Bourne shell only allowed NL).
11400 if (lasttoken != TSEMI)
11403 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11404 if (readtoken() != TDO)
11405 raise_error_unexpected_syntax(TDO);
11406 n1->nfor.body = list(0);
11410 n1 = stzalloc(sizeof(struct ncase));
11412 if (readtoken() != TWORD)
11413 raise_error_unexpected_syntax(TWORD);
11414 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11416 /*n2->narg.next = NULL; - stzalloc did it */
11417 n2->narg.text = wordtext;
11418 n2->narg.backquote = backquotelist;
11419 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11420 if (readtoken() != TIN)
11421 raise_error_unexpected_syntax(TIN);
11422 cpp = &n1->ncase.cases;
11424 checkkwd = CHKNL | CHKKWD;
11426 while (t != TESAC) {
11427 if (lasttoken == TLP)
11429 *cpp = cp = stzalloc(sizeof(struct nclist));
11431 app = &cp->nclist.pattern;
11433 *app = ap = stzalloc(sizeof(struct narg));
11435 /*ap->narg.next = NULL; - stzalloc did it */
11436 ap->narg.text = wordtext;
11437 ap->narg.backquote = backquotelist;
11438 if (readtoken() != TPIPE)
11440 app = &ap->narg.next;
11443 //ap->narg.next = NULL;
11444 if (lasttoken != TRP)
11445 raise_error_unexpected_syntax(TRP);
11446 cp->nclist.body = list(2);
11448 cpp = &cp->nclist.next;
11450 checkkwd = CHKNL | CHKKWD;
11454 raise_error_unexpected_syntax(TENDCASE);
11461 n1 = stzalloc(sizeof(struct nredir));
11462 n1->type = NSUBSHELL;
11463 n1->nredir.n = list(0);
11464 /*n1->nredir.redirect = NULL; - stzalloc did it */
11471 IF_BASH_FUNCTION(case TFUNCTION:)
11475 return simplecmd();
11478 if (readtoken() != t)
11479 raise_error_unexpected_syntax(t);
11482 /* Now check for redirection which may follow command */
11483 checkkwd = CHKKWD | CHKALIAS;
11485 while (readtoken() == TREDIR) {
11486 *rpp = n2 = redirnode;
11487 rpp = &n2->nfile.next;
11493 if (n1->type != NSUBSHELL) {
11494 n2 = stzalloc(sizeof(struct nredir));
11499 n1->nredir.redirect = redir;
11504 #if BASH_DOLLAR_SQUOTE
11506 decode_dollar_squote(void)
11508 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11514 p = strchr(C_escapes, c);
11519 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11523 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11525 } else if (c == 'x') { /* \xHH */
11529 } while (isxdigit(c) && --cnt);
11531 if (cnt == 3) { /* \x but next char is "bad" */
11535 } else { /* simple seq like \\ or \t */
11540 c = bb_process_escape_sequence((void*)&p);
11541 } else { /* unrecognized "\z": print both chars unless ' or " */
11542 if (c != '\'' && c != '"') {
11544 c |= 0x100; /* "please encode \, then me" */
11552 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11553 * is not NULL, read a here document. In the latter case, eofmark is the
11554 * word which marks the end of the document and striptabs is true if
11555 * leading tabs should be stripped from the document. The argument c
11556 * is the first character of the input token or document.
11558 * Because C does not have internal subroutines, I have simulated them
11559 * using goto's to implement the subroutine linkage. The following macros
11560 * will run code that appears at the end of readtoken1.
11562 #define CHECKEND() {goto checkend; checkend_return:;}
11563 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11564 #define PARSESUB() {goto parsesub; parsesub_return:;}
11565 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11566 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11567 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11569 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11571 /* NB: syntax parameter fits into smallint */
11572 /* c parameter is an unsigned char or PEOF or PEOA */
11575 char line[EOFMARKLEN + 1];
11576 struct nodelist *bqlist;
11580 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11581 smallint pssyntax; /* we are expanding a prompt string */
11582 int varnest; /* levels of variables expansion */
11583 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11584 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11585 int dqvarnest; /* levels of variables expansion within double quotes */
11587 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11589 startlinno = g_parsefile->linno;
11592 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11593 pssyntax = (syntax == PSSYNTAX);
11596 dblquote = (syntax == DQSYNTAX);
11598 IF_FEATURE_SH_MATH(arinest = 0;)
11599 IF_FEATURE_SH_MATH(parenlevel = 0;)
11602 STARTSTACKSTR(out);
11604 /* For each line, until end of word */
11605 CHECKEND(); /* set c to PEOF if at end of here document */
11606 for (;;) { /* until end of line or end of word */
11607 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11608 switch (SIT(c, syntax)) {
11609 case CNL: /* '\n' */
11610 if (syntax == BASESYNTAX)
11611 goto endword; /* exit outer loop */
11615 goto loop; /* continue outer loop */
11620 #if BASH_DOLLAR_SQUOTE
11621 if (c == '\\' && bash_dollar_squote) {
11622 c = decode_dollar_squote();
11624 /* skip $'\000', $'\x00' (like bash) */
11628 /* Unknown escape. Encode as '\z' */
11629 c = (unsigned char)c;
11630 if (eofmark == NULL || dblquote)
11631 USTPUTC(CTLESC, out);
11632 USTPUTC('\\', out);
11636 if (eofmark == NULL || dblquote)
11637 USTPUTC(CTLESC, out);
11640 case CBACK: /* backslash */
11641 c = pgetc_without_PEOA();
11643 USTPUTC(CTLESC, out);
11644 USTPUTC('\\', out);
11646 } else if (c == '\n') {
11649 if (c == '$' && pssyntax) {
11650 USTPUTC(CTLESC, out);
11651 USTPUTC('\\', out);
11653 /* Backslash is retained if we are in "str" and next char isn't special */
11658 && (c != '"' || eofmark != NULL)
11660 USTPUTC('\\', out);
11662 USTPUTC(CTLESC, out);
11670 if (eofmark == NULL) {
11671 USTPUTC(CTLQUOTEMARK, out);
11679 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11680 if (eofmark != NULL && varnest == 0) {
11683 if (dqvarnest == 0) {
11684 syntax = BASESYNTAX;
11691 case CVAR: /* '$' */
11692 PARSESUB(); /* parse substitution */
11694 case CENDVAR: /* '}' */
11697 if (dqvarnest > 0) {
11704 #if ENABLE_FEATURE_SH_MATH
11705 case CLP: /* '(' in arithmetic */
11709 case CRP: /* ')' in arithmetic */
11710 if (parenlevel > 0) {
11713 if (pgetc_eatbnl() == ')') {
11715 if (--arinest == 0) {
11716 syntax = prevsyntax;
11720 * unbalanced parens
11721 * (don't 2nd guess - no error)
11729 case CBQUOTE: /* '`' */
11733 goto endword; /* exit outer loop */
11737 if (varnest == 0) {
11738 #if BASH_REDIR_OUTPUT
11740 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11741 if (pgetc() == '>')
11742 c = 0x100 + '>'; /* flag &> */
11746 goto endword; /* exit outer loop */
11748 IF_ASH_ALIAS(if (c != PEOA))
11755 #if ENABLE_FEATURE_SH_MATH
11756 if (syntax == ARISYNTAX)
11757 raise_error_syntax("missing '))'");
11759 if (syntax != BASESYNTAX && eofmark == NULL)
11760 raise_error_syntax("unterminated quoted string");
11761 if (varnest != 0) {
11762 startlinno = g_parsefile->linno;
11764 raise_error_syntax("missing '}'");
11766 USTPUTC('\0', out);
11767 len = out - (char *)stackblock();
11768 out = stackblock();
11769 if (eofmark == NULL) {
11770 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11773 if (isdigit_str9(out)) {
11774 PARSEREDIR(); /* passed as params: out, c */
11775 lasttoken = TREDIR;
11778 /* else: non-number X seen, interpret it
11779 * as "NNNX>file" = "NNNX >file" */
11783 quoteflag = quotef;
11784 backquotelist = bqlist;
11785 grabstackblock(len);
11789 /* end of readtoken routine */
11792 * Check to see whether we are at the end of the here document. When this
11793 * is called, c is set to the first character of the next input line. If
11794 * we are at the end of the here document, this routine sets the c to PEOF.
11798 #if ENABLE_ASH_ALIAS
11800 c = pgetc_without_PEOA();
11803 while (c == '\t') {
11804 c = pgetc_without_PEOA();
11807 if (c == *eofmark) {
11808 if (pfgets(line, sizeof(line)) != NULL) {
11813 for (q = eofmark + 1;; p++, q++) {
11817 if (!*q || cc != *q)
11824 pushstring(line, NULL);
11829 goto checkend_return;
11833 * Parse a redirection operator. The variable "out" points to a string
11834 * specifying the fd to be redirected. The variable "c" contains the
11835 * first character of the redirection operator.
11838 /* out is already checked to be a valid number or "" */
11839 int fd = (*out == '\0' ? -1 : atoi(out));
11842 np = stzalloc(sizeof(struct nfile));
11847 np->type = NAPPEND;
11849 np->type = NCLOBBER;
11852 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11858 #if BASH_REDIR_OUTPUT
11859 else if (c == 0x100 + '>') { /* this flags &> redirection */
11861 pgetc(); /* this is '>', no need to check */
11865 else { /* c == '<' */
11866 /*np->nfile.fd = 0; - stzalloc did it */
11870 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11871 np = stzalloc(sizeof(struct nhere));
11872 /*np->nfile.fd = 0; - stzalloc did it */
11875 heredoc = stzalloc(sizeof(struct heredoc));
11876 heredoc->here = np;
11879 heredoc->striptabs = 1;
11881 /*heredoc->striptabs = 0; - stzalloc did it */
11887 np->type = NFROMFD;
11891 np->type = NFROMTO;
11903 goto parseredir_return;
11907 * Parse a substitution. At this point, we have read the dollar sign
11908 * and nothing else.
11911 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11912 * (assuming ascii char codes, as the original implementation did) */
11913 #define is_special(c) \
11914 (((unsigned)(c) - 33 < 32) \
11915 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11917 unsigned char subtype;
11920 c = pgetc_eatbnl();
11921 if (c > 255 /* PEOA or PEOF */
11922 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11924 #if BASH_DOLLAR_SQUOTE
11925 if (syntax != DQSYNTAX && c == '\'')
11926 bash_dollar_squote = 1;
11931 } else if (c == '(') {
11932 /* $(command) or $((arith)) */
11933 if (pgetc_eatbnl() == '(') {
11934 #if ENABLE_FEATURE_SH_MATH
11937 raise_error_syntax("support for $((arith)) is disabled");
11944 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11945 USTPUTC(CTLVAR, out);
11946 typeloc = out - (char *)stackblock();
11948 subtype = VSNORMAL;
11950 c = pgetc_eatbnl();
11955 /* $[{[#]]NAME[}] */
11958 c = pgetc_eatbnl();
11959 } while (is_in_name(c));
11960 } else if (isdigit(c)) {
11961 /* $[{[#]]NUM[}] */
11964 c = pgetc_eatbnl();
11965 } while (isdigit(c));
11966 } else if (is_special(c)) {
11967 /* $[{[#]]<specialchar>[}] */
11970 c = pgetc_eatbnl();
11971 if (!subtype && cc == '#') {
11972 subtype = VSLENGTH;
11973 if (c == '_' || isalnum(c))
11976 c = pgetc_eatbnl();
11977 if (cc == '}' || c != '}') {
11988 if (c != '}' && subtype == VSLENGTH) {
11989 /* ${#VAR didn't end with } */
11993 if (subtype == 0) {
11994 static const char types[] ALIGN1 = "}-+?=";
11995 /* ${VAR...} but not $VAR or ${#VAR} */
11996 /* c == first char after VAR */
11999 c = pgetc_eatbnl();
12001 /* This check is only needed to not misinterpret
12002 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12005 if (!strchr(types, c)) {
12006 subtype = VSSUBSTR;
12008 break; /* "goto badsub" is bigger (!) */
12014 const char *p = strchr(types, c);
12017 subtype |= p - types + VSNORMAL;
12023 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12024 c = pgetc_eatbnl();
12030 #if BASH_PATTERN_SUBST
12032 /* ${v/[/]pattern/repl} */
12033 //TODO: encode pattern and repl separately.
12034 // Currently ${v/$var_with_slash/repl} is horribly broken
12035 subtype = VSREPLACE;
12036 c = pgetc_eatbnl();
12039 subtype++; /* VSREPLACEALL */
12047 ((unsigned char *)stackblock())[typeloc] = subtype;
12048 if (subtype != VSNORMAL) {
12055 goto parsesub_return;
12059 * Called to parse command substitutions. Newstyle is set if the command
12060 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12061 * list of commands (passed by reference), and savelen is the number of
12062 * characters on the top of the stack which must be preserved.
12065 struct nodelist **nlpp;
12069 smallint saveprompt = 0;
12072 savelen = out - (char *)stackblock();
12075 * FIXME: this can allocate very large block on stack and SEGV.
12077 * echo "..<100kbytes>..`true` $(true) `true` ..."
12078 * allocates 100kb for every command subst. With about
12079 * a hundred command substitutions stack overflows.
12080 * With larger prepended string, SEGV happens sooner.
12082 str = alloca(savelen);
12083 memcpy(str, stackblock(), savelen);
12087 /* We must read until the closing backquote, giving special
12088 * treatment to some slashes, and then push the string and
12089 * reread it as input, interpreting it normally.
12095 STARTSTACKSTR(pout);
12099 setprompt_if(needprompt, 2);
12110 * If eating a newline, avoid putting
12111 * the newline into the new character
12112 * stream (via the STPUTC after the
12117 if (pc != '\\' && pc != '`' && pc != '$'
12118 && (!dblquote || pc != '"')
12120 STPUTC('\\', pout);
12122 if (pc <= 255 /* not PEOA or PEOF */) {
12128 IF_ASH_ALIAS(case PEOA:)
12129 startlinno = g_parsefile->linno;
12130 raise_error_syntax("EOF in backquote substitution");
12142 STPUTC('\0', pout);
12143 psavelen = pout - (char *)stackblock();
12144 if (psavelen > 0) {
12145 pstr = grabstackstr(pout);
12146 setinputstring(pstr);
12151 nlpp = &(*nlpp)->next;
12152 *nlpp = stzalloc(sizeof(**nlpp));
12153 /* (*nlpp)->next = NULL; - stzalloc did it */
12156 saveprompt = doprompt;
12163 doprompt = saveprompt;
12164 else if (readtoken() != TRP)
12165 raise_error_unexpected_syntax(TRP);
12170 * Start reading from old file again, ignoring any pushed back
12171 * tokens left from the backquote parsing
12176 while (stackblocksize() <= savelen)
12178 STARTSTACKSTR(out);
12180 memcpy(out, str, savelen);
12181 STADJUST(savelen, out);
12183 USTPUTC(CTLBACKQ, out);
12185 goto parsebackq_oldreturn;
12186 goto parsebackq_newreturn;
12189 #if ENABLE_FEATURE_SH_MATH
12191 * Parse an arithmetic expansion (indicate start of one and set state)
12194 if (++arinest == 1) {
12195 prevsyntax = syntax;
12196 syntax = ARISYNTAX;
12198 USTPUTC(CTLARI, out);
12199 goto parsearith_return;
12202 } /* end of readtoken */
12205 * Read the next input token.
12206 * If the token is a word, we set backquotelist to the list of cmds in
12207 * backquotes. We set quoteflag to true if any part of the word was
12209 * If the token is TREDIR, then we set redirnode to a structure containing
12211 * In all cases, the variable startlinno is set to the number of the line
12212 * on which the token starts.
12214 * [Change comment: here documents and internal procedures]
12215 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12216 * word parsing code into a separate routine. In this case, readtoken
12217 * doesn't need to have any internal procedures, but parseword does.
12218 * We could also make parseoperator in essence the main routine, and
12219 * have parseword (readtoken1?) handle both words and redirection.]
12221 #define NEW_xxreadtoken
12222 #ifdef NEW_xxreadtoken
12223 /* singles must be first! */
12224 static const char xxreadtoken_chars[7] ALIGN1 = {
12225 '\n', '(', ')', /* singles */
12226 '&', '|', ';', /* doubles */
12230 #define xxreadtoken_singles 3
12231 #define xxreadtoken_doubles 3
12233 static const char xxreadtoken_tokens[] ALIGN1 = {
12234 TNL, TLP, TRP, /* only single occurrence allowed */
12235 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12236 TEOF, /* corresponds to trailing nul */
12237 TAND, TOR, TENDCASE /* if double occurrence */
12249 setprompt_if(needprompt, 2);
12250 startlinno = g_parsefile->linno;
12251 for (;;) { /* until token or start of word found */
12253 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12257 while ((c = pgetc()) != '\n' && c != PEOF)
12260 } else if (c == '\\') {
12261 if (pgetc() != '\n') {
12263 break; /* return readtoken1(...) */
12269 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12275 p = strchr(xxreadtoken_chars, c);
12277 break; /* return readtoken1(...) */
12279 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12281 if (cc == c) { /* double occurrence? */
12282 p += xxreadtoken_doubles + 1;
12285 #if BASH_REDIR_OUTPUT
12286 if (c == '&' && cc == '>') /* &> */
12287 break; /* return readtoken1(...) */
12292 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12297 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12299 #else /* old xxreadtoken */
12300 #define RETURN(token) return lasttoken = token
12310 setprompt_if(needprompt, 2);
12311 startlinno = g_parsefile->linno;
12312 for (;;) { /* until token or start of word found */
12315 case ' ': case '\t':
12316 IF_ASH_ALIAS(case PEOA:)
12319 while ((c = pgetc()) != '\n' && c != PEOF)
12324 if (pgetc() == '\n') {
12336 if (pgetc() == '&')
12341 if (pgetc() == '|')
12346 if (pgetc() == ';')
12359 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12362 #endif /* old xxreadtoken */
12368 int kwd = checkkwd;
12370 smallint alreadyseen = tokpushback;
12373 #if ENABLE_ASH_ALIAS
12389 if (t != TWORD || quoteflag) {
12394 * check for keywords
12396 if (kwd & CHKKWD) {
12397 const char *const *pp;
12399 pp = findkwd(wordtext);
12401 lasttoken = t = pp - tokname_array;
12402 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12407 if (checkkwd & CHKALIAS) {
12408 #if ENABLE_ASH_ALIAS
12410 ap = lookupalias(wordtext, 1);
12413 pushstring(ap->val, ap);
12423 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12425 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12441 * Read and parse a command. Returns NODE_EOF on end of file.
12442 * (NULL is a valid parse tree indicating a blank line.)
12444 static union node *
12445 parsecmd(int interact)
12450 doprompt = interact;
12451 setprompt_if(doprompt, doprompt);
12457 * Input any here documents.
12462 struct heredoc *here;
12465 here = heredoclist;
12466 heredoclist = NULL;
12469 setprompt_if(needprompt, 2);
12470 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12471 here->eofmark, here->striptabs);
12472 n = stzalloc(sizeof(struct narg));
12473 n->narg.type = NARG;
12474 /*n->narg.next = NULL; - stzalloc did it */
12475 n->narg.text = wordtext;
12476 n->narg.backquote = backquotelist;
12477 here->here->nhere.doc = n;
12484 * called by editline -- any expansions to the prompt should be added here.
12486 static const char *
12487 expandstr(const char *ps)
12492 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12493 * and token processing _can_ alter it (delete NULs etc). */
12494 setinputstring((char *)ps);
12496 saveprompt = doprompt;
12498 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12499 doprompt = saveprompt;
12503 n.narg.type = NARG;
12504 n.narg.next = NULL;
12505 n.narg.text = wordtext;
12506 n.narg.backquote = backquotelist;
12508 expandarg(&n, NULL, EXP_QUOTED);
12509 return stackblock();
12513 * Execute a command or commands contained in a string.
12516 evalstring(char *s, int flags)
12518 struct jmploc *volatile savehandler;
12519 struct jmploc jmploc;
12523 struct stackmark smark;
12528 setstackmark(&smark);
12531 /* On exception inside execution loop, we must popfile().
12532 * Try interactively:
12534 * command eval "a=b" # throws "is read only" error
12535 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12536 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12538 savehandler = exception_handler;
12539 ex = setjmp(jmploc.loc);
12542 exception_handler = &jmploc;
12544 while ((n = parsecmd(0)) != NODE_EOF) {
12547 i = evaltree(n, flags);
12550 popstackmark(&smark);
12555 popstackmark(&smark);
12559 exception_handler = savehandler;
12561 longjmp(exception_handler->loc, ex);
12567 * The eval command.
12569 static int FAST_FUNC
12570 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12579 STARTSTACKSTR(concat);
12581 concat = stack_putstr(p, concat);
12585 STPUTC(' ', concat);
12587 STPUTC('\0', concat);
12588 p = grabstackstr(concat);
12590 return evalstring(p, flags & EV_TESTED);
12596 * Read and execute commands.
12597 * "Top" is nonzero for the top level command loop;
12598 * it turns on prompting if the shell is interactive.
12604 struct stackmark smark;
12609 TRACE(("cmdloop(%d) called\n", top));
12613 setstackmark(&smark);
12616 showjobs(SHOW_CHANGED|SHOW_STDERR);
12619 if (iflag && top) {
12623 n = parsecmd(inter);
12625 if (DEBUG > 2 && debug && (n != NODE_EOF))
12628 if (n == NODE_EOF) {
12629 if (!top || numeof >= 50)
12631 if (!stoppedjobs()) {
12634 out2str("\nUse \"exit\" to leave shell.\n");
12637 } else if (nflag == 0) {
12640 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12643 i = evaltree(n, 0);
12647 popstackmark(&smark);
12651 evalskip &= ~SKIPFUNC;
12659 * Take commands from a file. To be compatible we should do a path
12660 * search for the file, which is necessary to find sub-commands.
12663 find_dot_file(char *name)
12666 const char *path = pathval();
12669 /* don't try this for absolute or relative paths */
12670 if (strchr(name, '/'))
12673 while ((fullname = path_advance(&path, name)) != NULL) {
12674 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12676 * Don't bother freeing here, since it will
12677 * be freed by the caller.
12681 if (fullname != name)
12682 stunalloc(fullname);
12685 /* not found in the PATH */
12686 ash_msg_and_raise_error("%s: not found", name);
12690 static int FAST_FUNC
12691 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12693 /* "false; . empty_file; echo $?" should print 0, not 1: */
12697 char *args_need_save;
12698 struct strlist *sp;
12699 volatile struct shparam saveparam;
12701 for (sp = cmdenviron; sp; sp = sp->next)
12702 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12704 nextopt(nullstr); /* handle possible "--" */
12708 /* bash says: "bash: .: filename argument required" */
12709 return 2; /* bash compat */
12712 /* This aborts if file isn't found, which is POSIXly correct.
12713 * bash returns exitcode 1 instead.
12715 fullname = find_dot_file(argv[0]);
12717 args_need_save = argv[0];
12718 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12720 saveparam = shellparam;
12721 shellparam.malloced = 0;
12725 shellparam.nparam = argc;
12726 shellparam.p = argv;
12729 /* This aborts if file can't be opened, which is POSIXly correct.
12730 * bash returns exitcode 1 instead.
12732 setinputfile(fullname, INPUT_PUSH_FILE);
12733 commandname = fullname;
12734 status = cmdloop(0);
12737 if (args_need_save) {
12738 freeparam(&shellparam);
12739 shellparam = saveparam;
12745 static int FAST_FUNC
12746 exitcmd(int argc UNUSED_PARAM, char **argv)
12751 exitstatus = number(argv[1]);
12752 raise_exception(EXEXIT);
12757 * Read a file containing shell functions.
12760 readcmdfile(char *name)
12762 setinputfile(name, INPUT_PUSH_FILE);
12768 /* ============ find_command inplementation */
12771 * Resolve a command name. If you change this routine, you may have to
12772 * change the shellexec routine as well.
12775 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12777 struct tblentry *cmdp;
12784 struct builtincmd *bcmd;
12786 /* If name contains a slash, don't use PATH or hash table */
12787 if (strchr(name, '/') != NULL) {
12788 entry->u.index = -1;
12789 if (act & DO_ABS) {
12790 while (stat(name, &statb) < 0) {
12792 if (errno == EINTR)
12795 entry->cmdtype = CMDUNKNOWN;
12799 entry->cmdtype = CMDNORMAL;
12803 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12805 updatetbl = (path == pathval());
12808 if (strstr(path, "%builtin") != NULL)
12809 act |= DO_ALTBLTIN;
12812 /* If name is in the table, check answer will be ok */
12813 cmdp = cmdlookup(name, 0);
12814 if (cmdp != NULL) {
12817 switch (cmdp->cmdtype) {
12835 } else if (cmdp->rehash == 0)
12836 /* if not invalidated by cd, we're done */
12840 /* If %builtin not in path, check for builtin next */
12841 bcmd = find_builtin(name);
12843 if (IS_BUILTIN_REGULAR(bcmd))
12844 goto builtin_success;
12845 if (act & DO_ALTPATH) {
12846 if (!(act & DO_ALTBLTIN))
12847 goto builtin_success;
12848 } else if (builtinloc <= 0) {
12849 goto builtin_success;
12853 #if ENABLE_FEATURE_SH_STANDALONE
12855 int applet_no = find_applet_by_name(name);
12856 if (applet_no >= 0) {
12857 entry->cmdtype = CMDNORMAL;
12858 entry->u.index = -2 - applet_no;
12864 /* We have to search path. */
12865 prev = -1; /* where to start */
12866 if (cmdp && cmdp->rehash) { /* doing a rehash */
12867 if (cmdp->cmdtype == CMDBUILTIN)
12870 prev = cmdp->param.index;
12876 while ((fullname = path_advance(&path, name)) != NULL) {
12877 stunalloc(fullname);
12878 /* NB: code below will still use fullname
12879 * despite it being "unallocated" */
12882 if (prefix(pathopt, "builtin")) {
12884 goto builtin_success;
12887 if ((act & DO_NOFUNC)
12888 || !prefix(pathopt, "func")
12889 ) { /* ignore unimplemented options */
12893 /* if rehash, don't redo absolute path names */
12894 if (fullname[0] == '/' && idx <= prev) {
12897 TRACE(("searchexec \"%s\": no change\n", name));
12900 while (stat(fullname, &statb) < 0) {
12902 if (errno == EINTR)
12905 if (errno != ENOENT && errno != ENOTDIR)
12909 e = EACCES; /* if we fail, this will be the error */
12910 if (!S_ISREG(statb.st_mode))
12912 if (pathopt) { /* this is a %func directory */
12913 stalloc(strlen(fullname) + 1);
12914 /* NB: stalloc will return space pointed by fullname
12915 * (because we don't have any intervening allocations
12916 * between stunalloc above and this stalloc) */
12917 readcmdfile(fullname);
12918 cmdp = cmdlookup(name, 0);
12919 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12920 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12921 stunalloc(fullname);
12924 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12926 entry->cmdtype = CMDNORMAL;
12927 entry->u.index = idx;
12931 cmdp = cmdlookup(name, 1);
12932 cmdp->cmdtype = CMDNORMAL;
12933 cmdp->param.index = idx;
12938 /* We failed. If there was an entry for this command, delete it */
12939 if (cmdp && updatetbl)
12940 delete_cmd_entry();
12942 ash_msg("%s: %s", name, errmsg(e, "not found"));
12943 entry->cmdtype = CMDUNKNOWN;
12948 entry->cmdtype = CMDBUILTIN;
12949 entry->u.cmd = bcmd;
12953 cmdp = cmdlookup(name, 1);
12954 cmdp->cmdtype = CMDBUILTIN;
12955 cmdp->param.cmd = bcmd;
12959 entry->cmdtype = cmdp->cmdtype;
12960 entry->u = cmdp->param;
12965 * The trap builtin.
12967 static int FAST_FUNC
12968 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12972 int signo, exitcode;
12977 for (signo = 0; signo < NSIG; signo++) {
12978 char *tr = trap_ptr[signo];
12980 /* note: bash adds "SIG", but only if invoked
12981 * as "bash". If called as "sh", or if set -o posix,
12982 * then it prints short signal names.
12983 * We are printing short names: */
12984 out1fmt("trap -- %s %s\n",
12986 get_signame(signo));
12987 /* trap_ptr != trap only if we are in special-cased `trap` code.
12988 * In this case, we will exit very soon, no need to free(). */
12989 /* if (trap_ptr != trap && tp[0]) */
12994 if (trap_ptr != trap) {
13007 signo = get_signum(*ap);
13008 if (signo < 0 || signo >= NSIG) {
13009 /* Mimic bash message exactly */
13010 ash_msg("%s: invalid signal specification", *ap);
13016 if (LONE_DASH(action))
13019 if (action[0]) /* not NULL and not "" and not "-" */
13020 may_have_traps = 1;
13021 action = ckstrdup(action);
13025 trap[signo] = action;
13036 /* ============ Builtins */
13038 #if ENABLE_ASH_HELP
13039 static int FAST_FUNC
13040 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13046 "Built-in commands:\n"
13047 "------------------\n");
13048 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13049 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13050 builtintab[i].name + 1);
13056 # if ENABLE_FEATURE_SH_STANDALONE
13058 const char *a = applet_names;
13060 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13065 while (*a++ != '\0')
13070 newline_and_flush(stdout);
13071 return EXIT_SUCCESS;
13076 static int FAST_FUNC
13077 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13079 show_history(line_input_state);
13080 return EXIT_SUCCESS;
13085 * The export and readonly commands.
13087 static int FAST_FUNC
13088 exportcmd(int argc UNUSED_PARAM, char **argv)
13098 /* "readonly" in bash accepts, but ignores -n.
13099 * We do the same: it saves a conditional in nextopt's param.
13102 while ((opt = nextopt("np")) != '\0') {
13104 flag_off = VEXPORT;
13107 if (argv[0][0] == 'r') {
13109 flag_off = 0; /* readonly ignores -n */
13111 flag_off = ~flag_off;
13113 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13119 p = strchr(name, '=');
13123 vp = *findvar(hashvar(name), name);
13125 vp->flags = ((vp->flags | flag) & flag_off);
13129 setvar(name, p, (flag & flag_off));
13130 } while ((name = *++aptr) != NULL);
13135 /* No arguments. Show the list of exported or readonly vars.
13138 showvars(argv[0], flag, 0);
13143 * Delete a function if it exists.
13146 unsetfunc(const char *name)
13148 struct tblentry *cmdp;
13150 cmdp = cmdlookup(name, 0);
13151 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13152 delete_cmd_entry();
13156 * The unset builtin command. We unset the function before we unset the
13157 * variable to allow a function to be unset when there is a readonly variable
13158 * with the same name.
13160 static int FAST_FUNC
13161 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13168 while ((i = nextopt("vf")) != 0) {
13172 for (ap = argptr; *ap; ap++) {
13185 static const unsigned char timescmd_str[] ALIGN1 = {
13186 ' ', offsetof(struct tms, tms_utime),
13187 '\n', offsetof(struct tms, tms_stime),
13188 ' ', offsetof(struct tms, tms_cutime),
13189 '\n', offsetof(struct tms, tms_cstime),
13192 static int FAST_FUNC
13193 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13195 unsigned long clk_tck, s, t;
13196 const unsigned char *p;
13199 clk_tck = bb_clk_tck();
13204 t = *(clock_t *)(((char *) &buf) + p[1]);
13207 out1fmt("%lum%lu.%03lus%c",
13209 (t * 1000) / clk_tck,
13217 #if ENABLE_FEATURE_SH_MATH
13219 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13220 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13222 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13224 static int FAST_FUNC
13225 letcmd(int argc UNUSED_PARAM, char **argv)
13231 ash_msg_and_raise_error("expression expected");
13233 i = ash_arith(*argv);
13241 * The read builtin. Options:
13242 * -r Do not interpret '\' specially
13243 * -s Turn off echo (tty only)
13244 * -n NCHARS Read NCHARS max
13245 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13246 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13247 * -u FD Read from given FD instead of fd 0
13248 * This uses unbuffered input, which may be avoidable in some cases.
13249 * TODO: bash also has:
13250 * -a ARRAY Read into array[0],[1],etc
13251 * -d DELIM End on DELIM char, not newline
13252 * -e Use line editing (tty only)
13254 static int FAST_FUNC
13255 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13257 char *opt_n = NULL;
13258 char *opt_p = NULL;
13259 char *opt_t = NULL;
13260 char *opt_u = NULL;
13261 int read_flags = 0;
13265 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13274 read_flags |= BUILTIN_READ_SILENT;
13280 read_flags |= BUILTIN_READ_RAW;
13290 /* "read -s" needs to save/restore termios, can't allow ^C
13291 * to jump out of it.
13295 r = shell_builtin_read(setvar0,
13297 bltinlookup("IFS"), /* can be NULL */
13306 if ((uintptr_t)r == 1 && errno == EINTR) {
13307 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13308 if (pending_sig == 0)
13312 if ((uintptr_t)r > 1)
13313 ash_msg_and_raise_error(r);
13315 return (uintptr_t)r;
13318 static int FAST_FUNC
13319 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13321 static const char permuser[3] ALIGN1 = "ogu";
13324 int symbolic_mode = 0;
13326 while (nextopt("S") != '\0') {
13335 if (*argptr == NULL) {
13336 if (symbolic_mode) {
13337 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13344 *p++ = permuser[i];
13346 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13347 if (!(mask & 0400)) *p++ = 'r';
13348 if (!(mask & 0200)) *p++ = 'w';
13349 if (!(mask & 0100)) *p++ = 'x';
13357 out1fmt("%04o\n", mask);
13360 char *modestr = *argptr;
13361 /* numeric umasks are taken as-is */
13362 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13363 if (!isdigit(modestr[0]))
13365 mask = bb_parse_mode(modestr, mask);
13366 if ((unsigned)mask > 0777) {
13367 ash_msg_and_raise_error("illegal mode: %s", modestr);
13369 if (!isdigit(modestr[0]))
13376 static int FAST_FUNC
13377 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13379 return shell_builtin_ulimit(argv);
13382 /* ============ main() and helpers */
13385 * Called to exit the shell.
13394 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13395 save_history(line_input_state);
13397 status = exitstatus;
13398 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13399 if (setjmp(loc.loc)) {
13400 if (exception_type == EXEXIT)
13401 status = exitstatus;
13404 exception_handler = &loc;
13410 /*free(p); - we'll exit soon */
13413 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13414 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13417 flush_stdout_stderr();
13425 /* we will never free this */
13426 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13428 sigmode[SIGCHLD - 1] = S_DFL;
13429 setsignal(SIGCHLD);
13431 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13432 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13434 signal(SIGHUP, SIG_DFL);
13439 struct stat st1, st2;
13442 for (envp = environ; envp && *envp; envp++) {
13443 p = endofname(*envp);
13444 if (p != *envp && *p == '=') {
13445 setvareq(*envp, VEXPORT|VTEXTFIXED);
13449 setvareq((char*)defoptindvar, VTEXTFIXED);
13451 setvar0("PPID", utoa(getppid()));
13453 p = lookupvar("SHLVL");
13454 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13456 #if BASH_HOSTNAME_VAR
13457 if (!lookupvar("HOSTNAME")) {
13458 struct utsname uts;
13460 setvar0("HOSTNAME", uts.nodename);
13463 p = lookupvar("PWD");
13465 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13466 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13476 //usage:#define ash_trivial_usage
13477 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13478 //usage:#define ash_full_usage "\n\n"
13479 //usage: "Unix shell interpreter"
13482 * Process the shell command line arguments.
13485 procargs(char **argv)
13488 const char *xminusc;
13493 /* if (xargv[0]) - mmm, this is always true! */
13495 for (i = 0; i < NOPTS; i++)
13498 if (options(/*cmdline:*/ 1)) {
13499 /* it already printed err message */
13500 raise_exception(EXERROR);
13504 if (*xargv == NULL) {
13506 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13509 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13513 for (i = 0; i < NOPTS; i++)
13514 if (optlist[i] == 2)
13519 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13524 } else if (!sflag) {
13525 setinputfile(*xargv, 0);
13528 commandname = arg0;
13531 shellparam.p = xargv;
13532 #if ENABLE_ASH_GETOPTS
13533 shellparam.optind = 1;
13534 shellparam.optoff = -1;
13536 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13538 shellparam.nparam++;
13545 * Read /etc/profile, ~/.profile, $ENV.
13548 read_profile(const char *name)
13550 name = expandstr(name);
13551 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13558 * This routine is called when an error or an interrupt occurs in an
13559 * interactive shell and control is returned to the main command loop.
13560 * (In dash, this function is auto-generated by build machinery).
13569 /* from expand.c: */
13572 /* from input.c: */
13573 g_parsefile->left_in_buffer = 0;
13574 g_parsefile->left_in_line = 0; /* clear input buffer */
13577 /* from redir.c: */
13579 popredir(/*drop:*/ 0, /*restore:*/ 0);
13583 static short profile_buf[16384];
13584 extern int etext();
13588 * Main routine. We initialize things, parse the arguments, execute
13589 * profiles if we're a login shell, and then call cmdloop to execute
13590 * commands. The setjmp call sets up the location to jump to when an
13591 * exception occurs. When an exception occurs the variable "state"
13592 * is used to figure out how far we had gotten.
13594 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13595 int ash_main(int argc UNUSED_PARAM, char **argv)
13597 volatile smallint state;
13598 struct jmploc jmploc;
13599 struct stackmark smark;
13601 /* Initialize global data */
13605 #if ENABLE_ASH_ALIAS
13611 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13614 #if ENABLE_FEATURE_EDITING
13615 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13618 if (setjmp(jmploc.loc)) {
13624 e = exception_type;
13626 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13630 newline_and_flush(stderr);
13633 popstackmark(&smark);
13634 FORCE_INT_ON; /* enable interrupts */
13643 exception_handler = &jmploc;
13644 rootpid = getpid();
13647 setstackmark(&smark);
13650 TRACE(("Shell args: "));
13651 trace_puts_args(argv);
13654 if (argv[0] && argv[0][0] == '-')
13660 read_profile("/etc/profile");
13663 hp = lookupvar("HOME");
13665 read_profile("$HOME/.profile");
13671 getuid() == geteuid() && getgid() == getegid() &&
13675 const char *shinit = lookupvar("ENV");
13676 if (shinit != NULL && *shinit != '\0')
13677 read_profile(shinit);
13679 popstackmark(&smark);
13683 /* evalstring pushes parsefile stack.
13684 * Ensure we don't falsely claim that 0 (stdin)
13685 * is one of stacked source fds.
13686 * Testcase: ash -c 'exec 1>&0' must not complain. */
13687 // if (!sflag) g_parsefile->pf_fd = -1;
13688 // ^^ not necessary since now we special-case fd 0
13689 // in is_hidden_fd() to not be considered "hidden fd"
13690 evalstring(minusc, 0);
13693 if (sflag || minusc == NULL) {
13694 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13696 const char *hp = lookupvar("HISTFILE");
13698 hp = lookupvar("HOME");
13701 hp = concat_path_file(hp, ".ash_history");
13702 setvar0("HISTFILE", hp);
13705 hp = lookupvar("HISTFILE");
13709 line_input_state->hist_file = hp;
13710 # if ENABLE_FEATURE_SH_HISTFILESIZE
13711 hp = lookupvar("HISTFILESIZE");
13712 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13716 state4: /* XXX ??? - why isn't this before the "if" statement */
13724 extern void _mcleanup(void);
13728 TRACE(("End of main reached\n"));
13735 * Copyright (c) 1989, 1991, 1993, 1994
13736 * The Regents of the University of California. All rights reserved.
13738 * This code is derived from software contributed to Berkeley by
13739 * Kenneth Almquist.
13741 * Redistribution and use in source and binary forms, with or without
13742 * modification, are permitted provided that the following conditions
13744 * 1. Redistributions of source code must retain the above copyright
13745 * notice, this list of conditions and the following disclaimer.
13746 * 2. Redistributions in binary form must reproduce the above copyright
13747 * notice, this list of conditions and the following disclaimer in the
13748 * documentation and/or other materials provided with the distribution.
13749 * 3. Neither the name of the University nor the names of its contributors
13750 * may be used to endorse or promote products derived from this software
13751 * without specific prior written permission.
13753 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13754 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13755 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13756 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13757 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13758 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13759 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13760 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13761 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13762 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF