1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_BASH_SOURCE_CURDIR
55 //config: bool "'source' and '.' builtins search current directory after $PATH"
56 //config: default n # do not encourage non-standard behavior
57 //config: depends on ASH_BASH_COMPAT
59 //config: This is not compliant with standards. Avoid if possible.
61 //config:config ASH_BASH_NOT_FOUND_HOOK
62 //config: bool "command_not_found_handle hook support"
64 //config: depends on ASH_BASH_COMPAT
66 //config: Enable support for the 'command_not_found_handle' hook function,
67 //config: from GNU bash, which allows for alternative command not found
70 //config:config ASH_JOB_CONTROL
71 //config: bool "Job control"
73 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
75 //config:config ASH_ALIAS
76 //config: bool "Alias support"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config:config ASH_RANDOM_SUPPORT
81 //config: bool "Pseudorandom generator and $RANDOM variable"
83 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
85 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
86 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
87 //config: You can reset the generator by using a specified start value.
88 //config: After "unset RANDOM" the generator will switch off and this
89 //config: variable will no longer have special treatment.
91 //config:config ASH_EXPAND_PRMT
92 //config: bool "Expand prompt string"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: $PS# may contain volatile content, such as backquote commands.
97 //config: This option recreates the prompt string from the environment
98 //config: variable each time it is displayed.
100 //config:config ASH_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable $TMOUT"
103 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_MAIL
108 //config: bool "Check for new mail in interactive shell"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config: Enable "check for new mail" function:
113 //config: if set, $MAIL file and $MAILPATH list of files
114 //config: are checked for mtime changes, and "you have mail"
115 //config: message is printed if change is detected.
117 //config:config ASH_ECHO
118 //config: bool "echo builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_PRINTF
123 //config: bool "printf builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_TEST
128 //config: bool "test builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config:config ASH_HELP
133 //config: bool "help builtin"
135 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
137 //config:config ASH_GETOPTS
138 //config: bool "getopts builtin"
140 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
142 //config:config ASH_CMDCMD
143 //config: bool "command builtin"
145 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
147 //config: Enable support for the 'command' builtin, which allows
148 //config: you to run the specified command or builtin,
149 //config: even when there is a function with the same name.
151 //config:endif # ash options
153 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
154 // APPLET_ODDNAME:name main location suid_type help
155 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
156 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
158 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
159 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
160 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
161 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
164 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
165 * DEBUG=2 to compile in and turn on debugging.
166 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
167 * debugging info is written to ./trace, quit signal generates core dump.
170 /* Tweak debug output verbosity here */
174 #define DEBUG_INTONOFF 0
178 #define JOBS ENABLE_ASH_JOB_CONTROL
182 #include <sys/times.h>
183 #include <sys/utsname.h> /* for setting $HOSTNAME */
184 #include "busybox.h" /* for applet_names */
186 /* So far, all bash compat is controlled by one config option */
187 /* Separate defines document which part of code implements what */
188 /* function keyword */
189 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
190 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
192 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
193 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
195 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
196 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
197 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
198 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
199 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
200 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
202 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
203 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
204 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
205 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
206 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
207 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
208 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
209 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
211 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
212 /* Bionic at least up to version 24 has no glob() */
213 # undef ENABLE_ASH_INTERNAL_GLOB
214 # define ENABLE_ASH_INTERNAL_GLOB 1
217 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
218 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
219 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
220 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
221 # error glob() should unbackslash them and match. uClibc does not unbackslash,
222 # error fails to match dirname, subsequently not expanding <pattern> in it.
224 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
225 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
228 #if !ENABLE_ASH_INTERNAL_GLOB
233 #include "shell_common.h"
234 #if ENABLE_FEATURE_SH_MATH
237 typedef long arith_t;
238 # define ARITH_FMT "%ld"
240 #if ENABLE_ASH_RANDOM_SUPPORT
243 # define CLEAR_RANDOM_T(rnd) ((void)0)
246 #include "NUM_APPLETS.h"
248 /* STANDALONE does not make sense, and won't compile */
249 # undef CONFIG_FEATURE_SH_STANDALONE
250 # undef ENABLE_FEATURE_SH_STANDALONE
251 # undef IF_FEATURE_SH_STANDALONE
252 # undef IF_NOT_FEATURE_SH_STANDALONE
253 # define ENABLE_FEATURE_SH_STANDALONE 0
254 # define IF_FEATURE_SH_STANDALONE(...)
255 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
259 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
263 # error "Do not even bother, ash will not run on NOMMU machine"
267 /* ============ Hash table sizes. Configurable. */
271 #define CMDTABLESIZE 31 /* should be prime */
274 /* ============ Shell options */
276 static const char *const optletters_optnames[] = {
300 #define optletters(n) optletters_optnames[n][0]
301 #define optnames(n) (optletters_optnames[n] + 1)
303 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
306 /* ============ Misc data */
308 #define msg_illnum "Illegal number: %s"
311 * We enclose jmp_buf in a structure so that we can declare pointers to
312 * jump locations. The global variable handler contains the location to
313 * jump to when an exception occurs, and the global variable exception_type
314 * contains a code identifying the exception. To implement nested
315 * exception handlers, the user should save the value of handler on entry
316 * to an inner scope, set handler to point to a jmploc structure for the
317 * inner scope, and restore handler on exit from the scope.
323 struct globals_misc {
324 uint8_t exitstatus; /* exit status of last command */
325 uint8_t back_exitstatus;/* exit status of backquoted command */
326 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
327 int rootpid; /* pid of main shell */
328 /* shell level: 0 for the main shell, 1 for its children, and so on */
330 #define rootshell (!shlvl)
333 char *minusc; /* argument to -c option */
335 char *curdir; // = nullstr; /* current working directory */
336 char *physdir; // = nullstr; /* physical working directory */
338 char *arg0; /* value of $0 */
340 struct jmploc *exception_handler;
342 volatile int suppress_int; /* counter */
343 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
344 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
345 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
346 smallint exception_type; /* kind of exception (0..5) */
348 #define EXINT 0 /* SIGINT received */
349 #define EXERROR 1 /* a generic error */
350 #define EXEXIT 4 /* exit the shell */
352 char nullstr[1]; /* zero length string */
355 #define eflag optlist[0]
356 #define fflag optlist[1]
357 #define Iflag optlist[2]
358 #define iflag optlist[3]
359 #define mflag optlist[4]
360 #define nflag optlist[5]
361 #define sflag optlist[6]
362 #define xflag optlist[7]
363 #define vflag optlist[8]
364 #define Cflag optlist[9]
365 #define aflag optlist[10]
366 #define bflag optlist[11]
367 #define uflag optlist[12]
368 #define viflag optlist[13]
370 # define pipefail optlist[14]
375 # define nolog optlist[14 + BASH_PIPEFAIL]
376 # define debug optlist[15 + BASH_PIPEFAIL]
379 /* trap handler commands */
381 * Sigmode records the current value of the signal handlers for the various
382 * modes. A value of zero means that the current handler is not known.
383 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
385 char sigmode[NSIG - 1];
386 #define S_DFL 1 /* default signal handling (SIG_DFL) */
387 #define S_CATCH 2 /* signal is caught */
388 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
389 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
391 /* indicates specified signal received */
392 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
393 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
395 char **trap_ptr; /* used only by "trap hack" */
397 /* Rarely referenced stuff */
398 #if ENABLE_ASH_RANDOM_SUPPORT
401 pid_t backgndpid; /* pid of last background process */
403 extern struct globals_misc *const ash_ptr_to_globals_misc;
404 #define G_misc (*ash_ptr_to_globals_misc)
405 #define exitstatus (G_misc.exitstatus )
406 #define back_exitstatus (G_misc.back_exitstatus )
407 #define job_warning (G_misc.job_warning)
408 #define rootpid (G_misc.rootpid )
409 #define shlvl (G_misc.shlvl )
410 #define errlinno (G_misc.errlinno )
411 #define minusc (G_misc.minusc )
412 #define curdir (G_misc.curdir )
413 #define physdir (G_misc.physdir )
414 #define arg0 (G_misc.arg0 )
415 #define exception_handler (G_misc.exception_handler)
416 #define exception_type (G_misc.exception_type )
417 #define suppress_int (G_misc.suppress_int )
418 #define pending_int (G_misc.pending_int )
419 #define got_sigchld (G_misc.got_sigchld )
420 #define pending_sig (G_misc.pending_sig )
421 #define nullstr (G_misc.nullstr )
422 #define optlist (G_misc.optlist )
423 #define sigmode (G_misc.sigmode )
424 #define gotsig (G_misc.gotsig )
425 #define may_have_traps (G_misc.may_have_traps )
426 #define trap (G_misc.trap )
427 #define trap_ptr (G_misc.trap_ptr )
428 #define random_gen (G_misc.random_gen )
429 #define backgndpid (G_misc.backgndpid )
430 #define INIT_G_misc() do { \
431 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
439 /* ============ DEBUG */
441 static void trace_printf(const char *fmt, ...);
442 static void trace_vprintf(const char *fmt, va_list va);
443 # define TRACE(param) trace_printf param
444 # define TRACEV(param) trace_vprintf param
445 # define close(fd) do { \
447 if (close(dfd) < 0) \
448 bb_error_msg("bug on %d: closing %d(0x%x)", \
449 __LINE__, dfd, dfd); \
452 # define TRACE(param)
453 # define TRACEV(param)
457 /* ============ Utility functions */
458 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
459 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
462 isdigit_str9(const char *str)
464 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
465 while (--maxlen && isdigit(*str))
467 return (*str == '\0');
471 var_end(const char *var)
480 /* ============ Interrupts / exceptions */
482 static void exitshell(void) NORETURN;
485 * These macros allow the user to suspend the handling of interrupt signals
486 * over a period of time. This is similar to SIGHOLD or to sigblock, but
487 * much more efficient and portable. (But hacking the kernel is so much
488 * more fun than worrying about efficiency and portability. :-))
491 # define INT_OFF do { \
492 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
497 # define INT_OFF do { \
504 * Called to raise an exception. Since C doesn't include exceptions, we
505 * just do a longjmp to the exception handler. The type of exception is
506 * stored in the global variable "exception_type".
508 static void raise_exception(int) NORETURN;
510 raise_exception(int e)
513 if (exception_handler == NULL)
518 longjmp(exception_handler->loc, 1);
521 #define raise_exception(e) do { \
522 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
523 raise_exception(e); \
528 * Called when a SIGINT is received. (If the user specifies
529 * that SIGINT is to be trapped or ignored using the trap builtin, then
530 * this routine is not called.) Suppressint is nonzero when interrupts
531 * are held using the INT_OFF macro. (The test for iflag is just
532 * defensive programming.)
534 static void raise_interrupt(void) NORETURN;
536 raise_interrupt(void)
539 /* Signal is not automatically unmasked after it is raised,
540 * do it ourself - unmask all signals */
541 sigprocmask_allsigs(SIG_UNBLOCK);
542 /* pending_sig = 0; - now done in signal_handler() */
544 if (!(rootshell && iflag)) {
545 /* Kill ourself with SIGINT */
546 signal(SIGINT, SIG_DFL);
549 /* bash: ^C even on empty command line sets $? */
550 exitstatus = SIGINT + 128;
551 raise_exception(EXINT);
555 #define raise_interrupt() do { \
556 TRACE(("raising interrupt on line %d\n", __LINE__)); \
561 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
565 if (--suppress_int == 0 && pending_int) {
570 # define INT_ON do { \
571 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
575 # define INT_ON int_on()
577 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
585 #define FORCE_INT_ON force_int_on()
587 #define SAVE_INT(v) ((v) = suppress_int)
589 #define RESTORE_INT(v) do { \
591 suppress_int = (v); \
592 if (suppress_int == 0 && pending_int) \
597 /* ============ Stdout/stderr output */
600 outstr(const char *p, FILE *file)
608 flush_stdout_stderr(void)
615 /* Was called outcslow(c,FILE*), but c was always '\n' */
617 newline_and_flush(FILE *dest)
625 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
627 out1fmt(const char *fmt, ...)
634 r = vprintf(fmt, ap);
640 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
642 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
649 ret = vsnprintf(outbuf, length, fmt, ap);
656 out1str(const char *p)
662 out2str(const char *p)
665 flush_stdout_stderr();
669 /* ============ Parser structures */
671 /* control characters in argument strings */
672 #define CTL_FIRST CTLESC
673 #define CTLESC ((unsigned char)'\201') /* escape next character */
674 #define CTLVAR ((unsigned char)'\202') /* variable defn */
675 #define CTLENDVAR ((unsigned char)'\203')
676 #define CTLBACKQ ((unsigned char)'\204')
677 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
678 #define CTLENDARI ((unsigned char)'\207')
679 #define CTLQUOTEMARK ((unsigned char)'\210')
680 #define CTL_LAST CTLQUOTEMARK
682 /* variable substitution byte (follows CTLVAR) */
683 #define VSTYPE 0x0f /* type of variable substitution */
684 #define VSNUL 0x10 /* colon--treat the empty string as unset */
686 /* values of VSTYPE field */
687 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
688 #define VSMINUS 0x2 /* ${var-text} */
689 #define VSPLUS 0x3 /* ${var+text} */
690 #define VSQUESTION 0x4 /* ${var?message} */
691 #define VSASSIGN 0x5 /* ${var=text} */
692 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
693 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
694 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
695 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
696 #define VSLENGTH 0xa /* ${#var} */
698 #define VSSUBSTR 0xc /* ${var:position:length} */
700 #if BASH_PATTERN_SUBST
701 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
702 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
705 static const char dolatstr[] ALIGN1 = {
706 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
708 #define DOLATSTRLEN 6
727 #if BASH_REDIR_OUTPUT
744 smallint type; /* Nxxxx */
748 union node *redirect;
753 smallint pipe_backgnd;
754 struct nodelist *cmdlist;
761 union node *redirect;
774 union node *elsepart;
810 struct nodelist *backquote;
813 /* nfile and ndup layout must match!
814 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
815 * that it is actually NTO2 (>&file), and change its type.
832 char *_unused_expfname;
851 struct nredir nredir;
852 struct nbinary nbinary;
856 struct nclist nclist;
857 struct ndefun ndefun;
866 * NODE_EOF is returned by parsecmd when it encounters an end of file.
867 * It must be distinct from NULL.
869 #define NODE_EOF ((union node *) -1L)
872 struct nodelist *next;
885 freefunc(struct funcnode *f)
887 if (f && --f->count < 0)
892 /* ============ Debugging output */
896 static FILE *tracefile;
899 trace_printf(const char *fmt, ...)
906 fprintf(tracefile, "%u ", (int) time(NULL));
908 fprintf(tracefile, "[%u] ", (int) getpid());
910 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
912 vfprintf(tracefile, fmt, va);
917 trace_vprintf(const char *fmt, va_list va)
921 vfprintf(tracefile, fmt, va);
922 fprintf(tracefile, "\n");
926 trace_puts(const char *s)
934 trace_puts_quoted(char *s)
941 putc('"', tracefile);
942 for (p = s; *p; p++) {
943 switch ((unsigned char)*p) {
944 case '\n': c = 'n'; goto backslash;
945 case '\t': c = 't'; goto backslash;
946 case '\r': c = 'r'; goto backslash;
947 case '\"': c = '\"'; goto backslash;
948 case '\\': c = '\\'; goto backslash;
949 case CTLESC: c = 'e'; goto backslash;
950 case CTLVAR: c = 'v'; goto backslash;
951 case CTLBACKQ: c = 'q'; goto backslash;
953 putc('\\', tracefile);
957 if (*p >= ' ' && *p <= '~')
960 putc('\\', tracefile);
961 putc((*p >> 6) & 03, tracefile);
962 putc((*p >> 3) & 07, tracefile);
963 putc(*p & 07, tracefile);
968 putc('"', tracefile);
972 trace_puts_args(char **ap)
979 trace_puts_quoted(*ap);
981 putc('\n', tracefile);
984 putc(' ', tracefile);
999 /* leave open because libedit might be using it */
1002 strcpy(s, "./trace");
1004 if (!freopen(s, "a", tracefile)) {
1005 fprintf(stderr, "Can't re-open %s\n", s);
1010 tracefile = fopen(s, "a");
1011 if (tracefile == NULL) {
1012 fprintf(stderr, "Can't open %s\n", s);
1018 flags = fcntl(fileno(tracefile), F_GETFL);
1020 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1022 setlinebuf(tracefile);
1023 fputs("\nTracing started.\n", tracefile);
1027 indent(int amount, char *pfx, FILE *fp)
1031 for (i = 0; i < amount; i++) {
1032 if (pfx && i == amount - 1)
1038 /* little circular references here... */
1039 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1042 sharg(union node *arg, FILE *fp)
1045 struct nodelist *bqlist;
1046 unsigned char subtype;
1048 if (arg->type != NARG) {
1049 out1fmt("<node type %d>\n", arg->type);
1052 bqlist = arg->narg.backquote;
1053 for (p = arg->narg.text; *p; p++) {
1054 switch ((unsigned char)*p) {
1063 if (subtype == VSLENGTH)
1071 if (subtype & VSNUL)
1074 switch (subtype & VSTYPE) {
1100 case VSTRIMRIGHTMAX:
1107 out1fmt("<subtype %d>", subtype);
1116 shtree(bqlist->n, -1, NULL, fp);
1127 shcmd(union node *cmd, FILE *fp)
1135 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1141 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1145 switch (np->nfile.type) {
1146 case NTO: s = ">>"+1; dftfd = 1; break;
1147 case NCLOBBER: s = ">|"; dftfd = 1; break;
1148 case NAPPEND: s = ">>"; dftfd = 1; break;
1149 #if BASH_REDIR_OUTPUT
1152 case NTOFD: s = ">&"; dftfd = 1; break;
1153 case NFROM: s = "<"; break;
1154 case NFROMFD: s = "<&"; break;
1155 case NFROMTO: s = "<>"; break;
1156 default: s = "*error*"; break;
1158 if (np->nfile.fd != dftfd)
1159 fprintf(fp, "%d", np->nfile.fd);
1161 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1162 fprintf(fp, "%d", np->ndup.dupfd);
1164 sharg(np->nfile.fname, fp);
1171 shtree(union node *n, int ind, char *pfx, FILE *fp)
1173 struct nodelist *lp;
1179 indent(ind, pfx, fp);
1181 if (n == NODE_EOF) {
1196 shtree(n->nbinary.ch1, ind, NULL, fp);
1199 shtree(n->nbinary.ch2, ind, NULL, fp);
1207 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1208 shtree(lp->n, 0, NULL, fp);
1212 if (n->npipe.pipe_backgnd)
1218 fprintf(fp, "<node type %d>", n->type);
1226 showtree(union node *n)
1228 trace_puts("showtree called\n");
1229 shtree(n, 1, NULL, stderr);
1235 /* ============ Parser data */
1238 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1241 struct strlist *next;
1248 struct strpush *prev; /* preceding string on stack */
1250 int prev_left_in_line;
1251 #if ENABLE_ASH_ALIAS
1252 struct alias *ap; /* if push was associated with an alias */
1254 char *string; /* remember the string since it may change */
1256 /* Remember last two characters for pungetc. */
1259 /* Number of outstanding calls to pungetc. */
1264 * The parsefile structure pointed to by the global variable parsefile
1265 * contains information about the current file being read.
1268 struct parsefile *prev; /* preceding file on stack */
1269 int linno; /* current line */
1270 int pf_fd; /* file descriptor (or -1 if string) */
1271 int left_in_line; /* number of chars left in this line */
1272 int left_in_buffer; /* number of chars left in this buffer past the line */
1273 char *next_to_pgetc; /* next char in buffer */
1274 char *buf; /* input buffer */
1275 struct strpush *strpush; /* for pushing strings at this level */
1276 struct strpush basestrpush; /* so pushing one is fast */
1278 /* Remember last two characters for pungetc. */
1281 /* Number of outstanding calls to pungetc. */
1285 static struct parsefile basepf; /* top level input file */
1286 static struct parsefile *g_parsefile = &basepf; /* current input file */
1287 static char *commandname; /* currently executing command */
1290 /* ============ Message printing */
1293 ash_vmsg(const char *msg, va_list ap)
1295 fprintf(stderr, "%s: ", arg0);
1297 if (strcmp(arg0, commandname))
1298 fprintf(stderr, "%s: ", commandname);
1299 if (!iflag || g_parsefile->pf_fd > 0)
1300 fprintf(stderr, "line %d: ", errlinno);
1302 vfprintf(stderr, msg, ap);
1303 newline_and_flush(stderr);
1307 * Exverror is called to raise the error exception. If the second argument
1308 * is not NULL then error prints an error message using printf style
1309 * formatting. It then raises the error exception.
1311 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1313 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1317 TRACE(("ash_vmsg_and_raise(%d):", cond));
1320 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1325 flush_stdout_stderr();
1326 raise_exception(cond);
1330 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1332 ash_msg_and_raise_error(const char *msg, ...)
1339 ash_vmsg_and_raise(EXERROR, msg, ap);
1345 * 'fmt' must be a string literal.
1347 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1349 static void raise_error_syntax(const char *) NORETURN;
1351 raise_error_syntax(const char *msg)
1353 errlinno = g_parsefile->linno;
1354 ash_msg_and_raise_error("syntax error: %s", msg);
1358 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1360 ash_msg_and_raise(int cond, const char *msg, ...)
1365 ash_vmsg_and_raise(cond, msg, ap);
1371 * error/warning routines for external builtins
1374 ash_msg(const char *fmt, ...)
1384 * Return a string describing an error. The returned string may be a
1385 * pointer to a static buffer that will be overwritten on the next call.
1386 * Action describes the operation that got the error.
1389 errmsg(int e, const char *em)
1391 if (e == ENOENT || e == ENOTDIR) {
1398 /* ============ Memory allocation */
1401 /* I consider these wrappers nearly useless:
1402 * ok, they return you to nearest exception handler, but
1403 * how much memory do you leak in the process, making
1404 * memory starvation worse?
1407 ckrealloc(void * p, size_t nbytes)
1409 p = realloc(p, nbytes);
1411 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1416 ckmalloc(size_t nbytes)
1418 return ckrealloc(NULL, nbytes);
1422 ckzalloc(size_t nbytes)
1424 return memset(ckmalloc(nbytes), 0, nbytes);
1428 ckstrdup(const char *s)
1430 char *p = strdup(s);
1432 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1436 /* Using bbox equivalents. They exit if out of memory */
1437 # define ckrealloc xrealloc
1438 # define ckmalloc xmalloc
1439 # define ckzalloc xzalloc
1440 # define ckstrdup xstrdup
1444 * It appears that grabstackstr() will barf with such alignments
1445 * because stalloc() will return a string allocated in a new stackblock.
1447 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1449 /* Most machines require the value returned from malloc to be aligned
1450 * in some way. The following macro will get this right
1451 * on many machines. */
1452 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1453 /* Minimum size of a block */
1454 MINSIZE = SHELL_ALIGN(504),
1457 struct stack_block {
1458 struct stack_block *prev;
1459 char space[MINSIZE];
1463 struct stack_block *stackp;
1469 struct globals_memstack {
1470 struct stack_block *g_stackp; // = &stackbase;
1471 char *g_stacknxt; // = stackbase.space;
1472 char *sstrend; // = stackbase.space + MINSIZE;
1473 size_t g_stacknleft; // = MINSIZE;
1474 struct stack_block stackbase;
1476 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1477 #define G_memstack (*ash_ptr_to_globals_memstack)
1478 #define g_stackp (G_memstack.g_stackp )
1479 #define g_stacknxt (G_memstack.g_stacknxt )
1480 #define sstrend (G_memstack.sstrend )
1481 #define g_stacknleft (G_memstack.g_stacknleft)
1482 #define stackbase (G_memstack.stackbase )
1483 #define INIT_G_memstack() do { \
1484 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1486 g_stackp = &stackbase; \
1487 g_stacknxt = stackbase.space; \
1488 g_stacknleft = MINSIZE; \
1489 sstrend = stackbase.space + MINSIZE; \
1493 #define stackblock() ((void *)g_stacknxt)
1494 #define stackblocksize() g_stacknleft
1497 * Parse trees for commands are allocated in lifo order, so we use a stack
1498 * to make this more efficient, and also to avoid all sorts of exception
1499 * handling code to handle interrupts in the middle of a parse.
1501 * The size 504 was chosen because the Ultrix malloc handles that size
1505 stalloc(size_t nbytes)
1510 aligned = SHELL_ALIGN(nbytes);
1511 if (aligned > g_stacknleft) {
1514 struct stack_block *sp;
1516 blocksize = aligned;
1517 if (blocksize < MINSIZE)
1518 blocksize = MINSIZE;
1519 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1520 if (len < blocksize)
1521 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1524 sp->prev = g_stackp;
1525 g_stacknxt = sp->space;
1526 g_stacknleft = blocksize;
1527 sstrend = g_stacknxt + blocksize;
1532 g_stacknxt += aligned;
1533 g_stacknleft -= aligned;
1538 stzalloc(size_t nbytes)
1540 return memset(stalloc(nbytes), 0, nbytes);
1547 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1548 write(STDERR_FILENO, "stunalloc\n", 10);
1552 g_stacknleft += g_stacknxt - (char *)p;
1557 * Like strdup but works with the ash stack.
1560 sstrdup(const char *p)
1562 size_t len = strlen(p) + 1;
1563 return memcpy(stalloc(len), p, len);
1566 static ALWAYS_INLINE void
1567 grabstackblock(size_t len)
1573 pushstackmark(struct stackmark *mark, size_t len)
1575 mark->stackp = g_stackp;
1576 mark->stacknxt = g_stacknxt;
1577 mark->stacknleft = g_stacknleft;
1578 grabstackblock(len);
1582 setstackmark(struct stackmark *mark)
1584 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1588 popstackmark(struct stackmark *mark)
1590 struct stack_block *sp;
1596 while (g_stackp != mark->stackp) {
1598 g_stackp = sp->prev;
1601 g_stacknxt = mark->stacknxt;
1602 g_stacknleft = mark->stacknleft;
1603 sstrend = mark->stacknxt + mark->stacknleft;
1608 * When the parser reads in a string, it wants to stick the string on the
1609 * stack and only adjust the stack pointer when it knows how big the
1610 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1611 * of space on top of the stack and stackblocklen returns the length of
1612 * this block. Growstackblock will grow this space by at least one byte,
1613 * possibly moving it (like realloc). Grabstackblock actually allocates the
1614 * part of the block that has been used.
1617 growstackblock(void)
1621 newlen = g_stacknleft * 2;
1622 if (newlen < g_stacknleft)
1623 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1627 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1628 struct stack_block *sp;
1629 struct stack_block *prevstackp;
1634 prevstackp = sp->prev;
1635 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1636 sp = ckrealloc(sp, grosslen);
1637 sp->prev = prevstackp;
1639 g_stacknxt = sp->space;
1640 g_stacknleft = newlen;
1641 sstrend = sp->space + newlen;
1644 char *oldspace = g_stacknxt;
1645 size_t oldlen = g_stacknleft;
1646 char *p = stalloc(newlen);
1648 /* free the space we just allocated */
1649 g_stacknxt = memcpy(p, oldspace, oldlen);
1650 g_stacknleft += newlen;
1655 * The following routines are somewhat easier to use than the above.
1656 * The user declares a variable of type STACKSTR, which may be declared
1657 * to be a register. The macro STARTSTACKSTR initializes things. Then
1658 * the user uses the macro STPUTC to add characters to the string. In
1659 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1660 * grown as necessary. When the user is done, she can just leave the
1661 * string there and refer to it using stackblock(). Or she can allocate
1662 * the space for it using grabstackstr(). If it is necessary to allow
1663 * someone else to use the stack temporarily and then continue to grow
1664 * the string, the user should use grabstack to allocate the space, and
1665 * then call ungrabstr(p) to return to the previous mode of operation.
1667 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1668 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1669 * is space for at least one character.
1674 size_t len = stackblocksize();
1676 return (char *)stackblock() + len;
1680 * Called from CHECKSTRSPACE.
1683 makestrspace(size_t newlen, char *p)
1685 size_t len = p - g_stacknxt;
1691 size = stackblocksize();
1693 if (nleft >= newlen)
1697 return (char *)stackblock() + len;
1701 stack_nputstr(const char *s, size_t n, char *p)
1703 p = makestrspace(n, p);
1704 p = (char *)mempcpy(p, s, n);
1709 stack_putstr(const char *s, char *p)
1711 return stack_nputstr(s, strlen(s), p);
1715 _STPUTC(int c, char *p)
1723 #define STARTSTACKSTR(p) ((p) = stackblock())
1724 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1725 #define CHECKSTRSPACE(n, p) do { \
1728 size_t m = sstrend - q; \
1730 (p) = makestrspace(l, q); \
1732 #define USTPUTC(c, p) (*(p)++ = (c))
1733 #define STACKSTRNUL(p) do { \
1734 if ((p) == sstrend) \
1735 (p) = growstackstr(); \
1738 #define STUNPUTC(p) (--(p))
1739 #define STTOPC(p) ((p)[-1])
1740 #define STADJUST(amount, p) ((p) += (amount))
1742 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1743 #define ungrabstackstr(s, p) stunalloc(s)
1744 #define stackstrend() ((void *)sstrend)
1747 /* ============ String helpers */
1750 * prefix -- see if pfx is a prefix of string.
1753 prefix(const char *string, const char *pfx)
1756 if (*pfx++ != *string++)
1759 return (char *) string;
1763 * Check for a valid number. This should be elsewhere.
1766 is_number(const char *p)
1771 } while (*++p != '\0');
1776 * Convert a string of digits to an integer, printing an error message on
1780 number(const char *s)
1783 ash_msg_and_raise_error(msg_illnum, s);
1788 * Produce a single quoted string suitable as input to the shell.
1789 * The return string is allocated on the stack.
1792 single_quote(const char *s)
1802 len = strchrnul(s, '\'') - s;
1804 q = p = makestrspace(len + 3, p);
1807 q = (char *)mempcpy(q, s, len);
1816 do len++; while (*++s == '\'');
1818 q = p = makestrspace(len + 3, p);
1821 q = (char *)mempcpy(q, s - len, len);
1829 return stackblock();
1833 * Produce a possibly single quoted string suitable as input to the shell.
1834 * If quoting was done, the return string is allocated on the stack,
1835 * otherwise a pointer to the original string is returned.
1838 maybe_single_quote(const char *s)
1843 /* Assuming ACSII */
1844 /* quote ctrl_chars space !"#$%&'()* */
1848 if (*p >= ';' && *p <= '?')
1857 /* quote {|}~ DEL and high bytes */
1860 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1861 /* TODO: maybe avoid quoting % */
1867 return single_quote(s);
1871 /* ============ nextopt */
1873 static char **argptr; /* argument list for builtin commands */
1874 static char *optionarg; /* set by nextopt (like getopt) */
1875 static char *optptr; /* used by nextopt */
1878 * XXX - should get rid of. Have all builtins use getopt(3).
1879 * The library getopt must have the BSD extension static variable
1880 * "optreset", otherwise it can't be used within the shell safely.
1882 * Standard option processing (a la getopt) for builtin routines.
1883 * The only argument that is passed to nextopt is the option string;
1884 * the other arguments are unnecessary. It returns the character,
1885 * or '\0' on end of input.
1888 nextopt(const char *optstring)
1895 if (p == NULL || *p == '\0') {
1896 /* We ate entire "-param", take next one */
1902 if (*++p == '\0') /* just "-" ? */
1905 if (LONE_DASH(p)) /* "--" ? */
1907 /* p => next "-param" */
1909 /* p => some option char in the middle of a "-param" */
1911 for (q = optstring; *q != c;) {
1913 ash_msg_and_raise_error("illegal option -%c", c);
1921 ash_msg_and_raise_error("no arg for -%c option", c);
1931 /* ============ Shell variables */
1934 int nparam; /* # of positional parameters (without $0) */
1935 #if ENABLE_ASH_GETOPTS
1936 int optind; /* next parameter to be processed by getopts */
1937 int optoff; /* used by getopts */
1939 unsigned char malloced; /* if parameter list dynamically allocated */
1940 char **p; /* parameter list */
1944 * Free the list of positional parameters.
1947 freeparam(volatile struct shparam *param)
1949 if (param->malloced) {
1951 ap = ap1 = param->p;
1958 #if ENABLE_ASH_GETOPTS
1959 static void FAST_FUNC getoptsreset(const char *value);
1963 struct var *next; /* next entry in hash list */
1964 int flags; /* flags are defined above */
1965 const char *var_text; /* name=value */
1966 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1967 /* the variable gets set/unset */
1971 struct localvar *next; /* next local variable in list */
1972 struct var *vp; /* the variable that was made local */
1973 int flags; /* saved flags */
1974 const char *text; /* saved text */
1978 #define VEXPORT 0x01 /* variable is exported */
1979 #define VREADONLY 0x02 /* variable cannot be modified */
1980 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1981 #define VTEXTFIXED 0x08 /* text is statically allocated */
1982 #define VSTACK 0x10 /* text is allocated on the stack */
1983 #define VUNSET 0x20 /* the variable is not set */
1984 #define VNOFUNC 0x40 /* don't call the callback function */
1985 #define VNOSET 0x80 /* do not set variable - just readonly test */
1986 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1987 #if ENABLE_ASH_RANDOM_SUPPORT
1988 # define VDYNAMIC 0x200 /* dynamic variable */
1994 /* Need to be before varinit_data[] */
1995 #if ENABLE_LOCALE_SUPPORT
1996 static void FAST_FUNC
1997 change_lc_all(const char *value)
1999 if (value && *value != '\0')
2000 setlocale(LC_ALL, value);
2002 static void FAST_FUNC
2003 change_lc_ctype(const char *value)
2005 if (value && *value != '\0')
2006 setlocale(LC_CTYPE, value);
2010 static void chkmail(void);
2011 static void changemail(const char *var_value) FAST_FUNC;
2013 # define chkmail() ((void)0)
2015 static void changepath(const char *) FAST_FUNC;
2016 #if ENABLE_ASH_RANDOM_SUPPORT
2017 static void change_random(const char *) FAST_FUNC;
2020 static const struct {
2022 const char *var_text;
2023 void (*var_func)(const char *) FAST_FUNC;
2024 } varinit_data[] = {
2026 * Note: VEXPORT would not work correctly here for NOFORK applets:
2027 * some environment strings may be constant.
2029 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2031 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2032 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2034 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2035 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2036 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2037 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2038 #if ENABLE_ASH_GETOPTS
2039 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2041 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2042 #if ENABLE_ASH_RANDOM_SUPPORT
2043 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2045 #if ENABLE_LOCALE_SUPPORT
2046 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2047 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2049 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2050 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2056 struct globals_var {
2057 struct shparam shellparam; /* $@ current positional parameters */
2058 struct redirtab *redirlist;
2059 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2060 struct var *vartab[VTABSIZE];
2061 struct var varinit[ARRAY_SIZE(varinit_data)];
2063 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2065 extern struct globals_var *const ash_ptr_to_globals_var;
2066 #define G_var (*ash_ptr_to_globals_var)
2067 #define shellparam (G_var.shellparam )
2068 //#define redirlist (G_var.redirlist )
2069 #define preverrout_fd (G_var.preverrout_fd)
2070 #define vartab (G_var.vartab )
2071 #define varinit (G_var.varinit )
2072 #define lineno (G_var.lineno )
2073 #define linenovar (G_var.linenovar )
2074 #define vifs varinit[0]
2076 # define vmail (&vifs)[1]
2077 # define vmpath (&vmail)[1]
2078 # define vpath (&vmpath)[1]
2080 # define vpath (&vifs)[1]
2082 #define vps1 (&vpath)[1]
2083 #define vps2 (&vps1)[1]
2084 #define vps4 (&vps2)[1]
2085 #if ENABLE_ASH_GETOPTS
2086 # define voptind (&vps4)[1]
2087 # define vlineno (&voptind)[1]
2088 # if ENABLE_ASH_RANDOM_SUPPORT
2089 # define vrandom (&vlineno)[1]
2092 # define vlineno (&vps4)[1]
2093 # if ENABLE_ASH_RANDOM_SUPPORT
2094 # define vrandom (&vlineno)[1]
2097 #define INIT_G_var() do { \
2099 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2101 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2102 varinit[i].flags = varinit_data[i].flags; \
2103 varinit[i].var_text = varinit_data[i].var_text; \
2104 varinit[i].var_func = varinit_data[i].var_func; \
2106 strcpy(linenovar, "LINENO="); \
2107 vlineno.var_text = linenovar; \
2111 * The following macros access the values of the above variables.
2112 * They have to skip over the name. They return the null string
2113 * for unset variables.
2115 #define ifsval() (vifs.var_text + 4)
2116 #define ifsset() ((vifs.flags & VUNSET) == 0)
2118 # define mailval() (vmail.var_text + 5)
2119 # define mpathval() (vmpath.var_text + 9)
2120 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2122 #define pathval() (vpath.var_text + 5)
2123 #define ps1val() (vps1.var_text + 4)
2124 #define ps2val() (vps2.var_text + 4)
2125 #define ps4val() (vps4.var_text + 4)
2126 #if ENABLE_ASH_GETOPTS
2127 # define optindval() (voptind.var_text + 7)
2130 #if ENABLE_ASH_GETOPTS
2131 static void FAST_FUNC
2132 getoptsreset(const char *value)
2134 shellparam.optind = 1;
2135 if (is_number(value))
2136 shellparam.optind = number(value) ?: 1;
2137 shellparam.optoff = -1;
2142 * Compares two strings up to the first = or '\0'. The first
2143 * string must be terminated by '='; the second may be terminated by
2144 * either '=' or '\0'.
2147 varcmp(const char *p, const char *q)
2151 while ((c = *p) == (d = *q)) {
2152 if (c == '\0' || c == '=')
2166 * Find the appropriate entry in the hash table from the name.
2168 static struct var **
2169 hashvar(const char *p)
2173 hashval = ((unsigned char) *p) << 4;
2174 while (*p && *p != '=')
2175 hashval += (unsigned char) *p++;
2176 return &vartab[hashval % VTABSIZE];
2180 vpcmp(const void *a, const void *b)
2182 return varcmp(*(const char **)a, *(const char **)b);
2186 * This routine initializes the builtin variables.
2196 * PS1 depends on uid
2198 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2199 vps1.var_text = "PS1=\\w \\$ ";
2202 vps1.var_text = "PS1=# ";
2205 end = vp + ARRAY_SIZE(varinit);
2207 vpp = hashvar(vp->var_text);
2210 } while (++vp < end);
2213 static struct var **
2214 findvar(struct var **vpp, const char *name)
2216 for (; *vpp; vpp = &(*vpp)->next) {
2217 if (varcmp((*vpp)->var_text, name) == 0) {
2225 * Find the value of a variable. Returns NULL if not set.
2227 static const char* FAST_FUNC
2228 lookupvar(const char *name)
2232 v = *findvar(hashvar(name), name);
2234 #if ENABLE_ASH_RANDOM_SUPPORT
2236 * Dynamic variables are implemented roughly the same way they are
2237 * in bash. Namely, they're "special" so long as they aren't unset.
2238 * As soon as they're unset, they're no longer dynamic, and dynamic
2239 * lookup will no longer happen at that point. -- PFM.
2241 if (v->flags & VDYNAMIC)
2244 if (!(v->flags & VUNSET)) {
2245 if (v == &vlineno && v->var_text == linenovar) {
2246 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2248 return var_end(v->var_text);
2254 #if ENABLE_UNICODE_SUPPORT
2256 reinit_unicode_for_ash(void)
2258 /* Unicode support should be activated even if LANG is set
2259 * _during_ shell execution, not only if it was set when
2260 * shell was started. Therefore, re-check LANG every time:
2262 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2263 || ENABLE_UNICODE_USING_LOCALE
2265 const char *s = lookupvar("LC_ALL");
2266 if (!s) s = lookupvar("LC_CTYPE");
2267 if (!s) s = lookupvar("LANG");
2272 # define reinit_unicode_for_ash() ((void)0)
2276 * Search the environment of a builtin command.
2278 static ALWAYS_INLINE const char *
2279 bltinlookup(const char *name)
2281 return lookupvar(name);
2285 * Same as setvar except that the variable and value are passed in
2286 * the first argument as name=value. Since the first argument will
2287 * be actually stored in the table, it should not be a string that
2289 * Called with interrupts off.
2292 setvareq(char *s, int flags)
2294 struct var *vp, **vpp;
2297 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2298 vpp = findvar(vpp, s);
2301 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2304 if (flags & VNOSAVE)
2308 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2314 if (vp->var_func && !(flags & VNOFUNC))
2315 vp->var_func(var_end(s));
2317 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2318 free((char*)vp->var_text);
2320 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2324 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2329 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2331 /* variable s is not found */
2334 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2336 vp = ckzalloc(sizeof(*vp));
2338 /*vp->func = NULL; - ckzalloc did it */
2341 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2351 * Set the value of a variable. The flags argument is ored with the
2352 * flags of the variable. If val is NULL, the variable is unset.
2355 setvar(const char *name, const char *val, int flags)
2364 q = endofname(name);
2365 p = strchrnul(q, '=');
2367 if (!namelen || p != q)
2368 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2373 vallen = strlen(val);
2377 nameeq = ckmalloc(namelen + vallen + 2);
2378 p = mempcpy(nameeq, name, namelen);
2381 p = mempcpy(p, val, vallen);
2384 vp = setvareq(nameeq, flags | VNOSAVE);
2390 static void FAST_FUNC
2391 setvar0(const char *name, const char *val)
2393 setvar(name, val, 0);
2397 * Unset the specified variable.
2400 unsetvar(const char *s)
2406 * Process a linked list of variable assignments.
2409 listsetvar(struct strlist *list_set_var, int flags)
2411 struct strlist *lp = list_set_var;
2417 setvareq(lp->text, flags);
2424 * Generate a list of variables satisfying the given conditions.
2426 #if !ENABLE_FEATURE_SH_NOFORK
2427 # define listvars(on, off, lp, end) listvars(on, off, end)
2430 listvars(int on, int off, struct strlist *lp, char ***end)
2441 for (vp = *vpp; vp; vp = vp->next) {
2442 if ((vp->flags & mask) == on) {
2443 #if ENABLE_FEATURE_SH_NOFORK
2444 /* If variable with the same name is both
2445 * exported and temporarily set for a command:
2448 * then "ZVAR=6" will be both in vartab and
2449 * lp lists. Do not pass it twice to printenv.
2451 struct strlist *lp1 = lp;
2453 if (strcmp(lp1->text, vp->var_text) == 0)
2458 if (ep == stackstrend())
2459 ep = growstackstr();
2460 *ep++ = (char*)vp->var_text;
2461 #if ENABLE_FEATURE_SH_NOFORK
2466 } while (++vpp < vartab + VTABSIZE);
2468 #if ENABLE_FEATURE_SH_NOFORK
2470 if (ep == stackstrend())
2471 ep = growstackstr();
2477 if (ep == stackstrend())
2478 ep = growstackstr();
2482 return grabstackstr(ep);
2486 /* ============ Path search helper
2488 * The variable path (passed by reference) should be set to the start
2489 * of the path before the first call; path_advance will update
2490 * this value as it proceeds. Successive calls to path_advance will return
2491 * the possible path expansions in sequence. If an option (indicated by
2492 * a percent sign) appears in the path entry then the global variable
2493 * pathopt will be set to point to it; otherwise pathopt will be set to
2496 static const char *pathopt; /* set by path_advance */
2499 path_advance(const char **path, const char *name)
2509 for (p = start; *p && *p != ':' && *p != '%'; p++)
2511 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2512 while (stackblocksize() < len)
2516 q = mempcpy(q, start, p - start);
2523 while (*p && *p != ':')
2530 return stalloc(len);
2534 /* ============ Prompt */
2536 static smallint doprompt; /* if set, prompt the user */
2537 static smallint needprompt; /* true if interactive and at start of line */
2539 #if ENABLE_FEATURE_EDITING
2540 static line_input_t *line_input_state;
2541 static const char *cmdedit_prompt;
2543 putprompt(const char *s)
2545 if (ENABLE_ASH_EXPAND_PRMT) {
2546 free((char*)cmdedit_prompt);
2547 cmdedit_prompt = ckstrdup(s);
2554 putprompt(const char *s)
2560 /* expandstr() needs parsing machinery, so it is far away ahead... */
2561 static const char *expandstr(const char *ps, int syntax_type);
2562 /* Values for syntax param */
2563 #define BASESYNTAX 0 /* not in quotes */
2564 #define DQSYNTAX 1 /* in double quotes */
2565 #define SQSYNTAX 2 /* in single quotes */
2566 #define ARISYNTAX 3 /* in arithmetic */
2567 #if ENABLE_ASH_EXPAND_PRMT
2568 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2570 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2573 * called by editline -- any expansions to the prompt should be added here.
2576 setprompt_if(smallint do_set, int whichprompt)
2579 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2586 switch (whichprompt) {
2596 #if ENABLE_ASH_EXPAND_PRMT
2597 pushstackmark(&smark, stackblocksize());
2598 putprompt(expandstr(prompt, PSSYNTAX));
2599 popstackmark(&smark);
2606 /* ============ The cd and pwd commands */
2608 #define CD_PHYSICAL 1
2618 while ((i = nextopt("LP")) != '\0') {
2620 flags ^= CD_PHYSICAL;
2629 * Update curdir (the name of the current directory) in response to a
2633 updatepwd(const char *dir)
2640 cdcomppath = sstrdup(dir);
2643 if (curdir == nullstr)
2645 new = stack_putstr(curdir, new);
2647 new = makestrspace(strlen(dir) + 2, new);
2648 lim = (char *)stackblock() + 1;
2652 if (new > lim && *lim == '/')
2657 if (dir[1] == '/' && dir[2] != '/') {
2663 p = strtok(cdcomppath, "/");
2667 if (p[1] == '.' && p[2] == '\0') {
2679 new = stack_putstr(p, new);
2682 p = strtok(NULL, "/");
2687 return stackblock();
2691 * Find out what the current directory is. If we already know the current
2692 * directory, this routine returns immediately.
2697 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2698 return dir ? dir : nullstr;
2702 setpwd(const char *val, int setold)
2706 oldcur = dir = curdir;
2709 setvar("OLDPWD", oldcur, VEXPORT);
2712 if (physdir != nullstr) {
2713 if (physdir != oldcur)
2717 if (oldcur == val || !val) {
2723 dir = ckstrdup(val);
2724 if (oldcur != dir && oldcur != nullstr) {
2729 setvar("PWD", dir, VEXPORT);
2732 static void hashcd(void);
2735 * Actually do the chdir. We also call hashcd to let other routines
2736 * know that the current directory has changed.
2739 docd(const char *dest, int flags)
2741 const char *dir = NULL;
2744 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2747 if (!(flags & CD_PHYSICAL)) {
2748 dir = updatepwd(dest);
2762 static int FAST_FUNC
2763 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2775 dest = bltinlookup("HOME");
2776 else if (LONE_DASH(dest)) {
2777 dest = bltinlookup("OLDPWD");
2799 path = bltinlookup("CDPATH");
2802 p = path_advance(&path, dest);
2803 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2807 if (!docd(p, flags))
2818 ash_msg_and_raise_perror("can't cd to %s", dest);
2821 if (flags & CD_PRINT)
2822 out1fmt("%s\n", curdir);
2826 static int FAST_FUNC
2827 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2830 const char *dir = curdir;
2834 if (physdir == nullstr)
2838 out1fmt("%s\n", dir);
2843 /* ============ ... */
2846 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2848 /* Syntax classes */
2849 #define CWORD 0 /* character is nothing special */
2850 #define CNL 1 /* newline character */
2851 #define CBACK 2 /* a backslash character */
2852 #define CSQUOTE 3 /* single quote */
2853 #define CDQUOTE 4 /* double quote */
2854 #define CENDQUOTE 5 /* a terminating quote */
2855 #define CBQUOTE 6 /* backwards single quote */
2856 #define CVAR 7 /* a dollar sign */
2857 #define CENDVAR 8 /* a '}' character */
2858 #define CLP 9 /* a left paren in arithmetic */
2859 #define CRP 10 /* a right paren in arithmetic */
2860 #define CENDFILE 11 /* end of file */
2861 #define CCTL 12 /* like CWORD, except it must be escaped */
2862 #define CSPCL 13 /* these terminate a word */
2863 #define CIGN 14 /* character should be ignored */
2866 #if ENABLE_ASH_ALIAS
2870 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2872 #if ENABLE_FEATURE_SH_MATH
2873 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2875 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2877 static const uint16_t S_I_T[] ALIGN2 = {
2878 #if ENABLE_ASH_ALIAS
2879 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2881 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2882 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2883 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2884 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2885 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2886 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2887 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2888 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2889 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2890 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2891 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2892 #if !USE_SIT_FUNCTION
2893 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2894 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2895 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2899 /* Constants below must match table above */
2901 #if ENABLE_ASH_ALIAS
2902 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2904 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2905 CNL_CNL_CNL_CNL , /* 2 */
2906 CWORD_CCTL_CCTL_CWORD , /* 3 */
2907 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2908 CVAR_CVAR_CWORD_CVAR , /* 5 */
2909 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2910 CSPCL_CWORD_CWORD_CLP , /* 7 */
2911 CSPCL_CWORD_CWORD_CRP , /* 8 */
2912 CBACK_CBACK_CCTL_CBACK , /* 9 */
2913 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2914 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2915 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2916 CWORD_CWORD_CWORD_CWORD , /* 13 */
2917 CCTL_CCTL_CCTL_CCTL , /* 14 */
2920 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2921 * caller must ensure proper cast on it if c is *char_ptr!
2923 #if USE_SIT_FUNCTION
2926 SIT(int c, int syntax)
2928 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2929 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2931 * This causes '/' to be prepended with CTLESC in dquoted string,
2932 * making "./file"* treated incorrectly because we feed
2933 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2934 * The "homegrown" glob implementation is okay with that,
2935 * but glibc one isn't. With '/' always treated as CWORD,
2938 # if ENABLE_ASH_ALIAS
2939 static const uint8_t syntax_index_table[] ALIGN1 = {
2940 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2941 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2942 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2946 static const uint8_t syntax_index_table[] ALIGN1 = {
2947 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2948 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2949 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2958 # if ENABLE_ASH_ALIAS
2964 /* Cast is purely for paranoia here,
2965 * just in case someone passed signed char to us */
2966 if ((unsigned char)c >= CTL_FIRST
2967 && (unsigned char)c <= CTL_LAST
2971 s = strchrnul(spec_symbls, c);
2974 indx = syntax_index_table[s - spec_symbls];
2976 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2979 #else /* !USE_SIT_FUNCTION */
2981 static const uint8_t syntax_index_table[] ALIGN1 = {
2982 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2983 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2993 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2994 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3016 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3017 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3018 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3020 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3022 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3023 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3024 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3025 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3026 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3028 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3029 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3030 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3031 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3038 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3039 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3040 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3041 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3042 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3043 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3044 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3045 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3046 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3047 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3048 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3049 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3050 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3051 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3052 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3053 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3054 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3055 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3056 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3057 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3058 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3059 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3060 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3061 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3062 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3063 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3064 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3065 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3066 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3067 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3068 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3069 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3070 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3071 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3072 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3073 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3074 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3075 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3076 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3077 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3078 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3079 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3080 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3081 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3082 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3083 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3084 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3085 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3086 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3087 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3088 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3089 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3090 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3091 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3092 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3093 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3094 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3095 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3096 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3097 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3098 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3099 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3100 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3101 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3102 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3103 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3104 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3105 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3106 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3109 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3110 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3111 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3112 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3114 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3115 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3116 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3117 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3118 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3119 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3120 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3121 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3173 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3174 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3175 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3176 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3177 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3178 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3179 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3180 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3181 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3182 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3183 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3184 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3185 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3186 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3187 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3188 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3189 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3190 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3191 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3192 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3193 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3194 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3195 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3240 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3241 # if ENABLE_ASH_ALIAS
3242 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3247 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3248 #else /* debug version, caught one signed char bug */
3249 # define SIT(c, syntax) \
3251 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3252 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3253 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3254 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3255 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3259 #endif /* !USE_SIT_FUNCTION */
3262 /* ============ Alias handling */
3264 #if ENABLE_ASH_ALIAS
3266 #define ALIASINUSE 1
3277 static struct alias **atab; // [ATABSIZE];
3278 #define INIT_G_alias() do { \
3279 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3283 static struct alias **
3284 __lookupalias(const char *name)
3286 unsigned int hashval;
3293 ch = (unsigned char)*p;
3297 ch = (unsigned char)*++p;
3299 app = &atab[hashval % ATABSIZE];
3301 for (; *app; app = &(*app)->next) {
3302 if (strcmp(name, (*app)->name) == 0) {
3310 static struct alias *
3311 lookupalias(const char *name, int check)
3313 struct alias *ap = *__lookupalias(name);
3315 if (check && ap && (ap->flag & ALIASINUSE))
3320 static struct alias *
3321 freealias(struct alias *ap)
3325 if (ap->flag & ALIASINUSE) {
3326 ap->flag |= ALIASDEAD;
3338 setalias(const char *name, const char *val)
3340 struct alias *ap, **app;
3342 app = __lookupalias(name);
3346 if (!(ap->flag & ALIASINUSE)) {
3349 ap->val = ckstrdup(val);
3350 ap->flag &= ~ALIASDEAD;
3353 ap = ckzalloc(sizeof(struct alias));
3354 ap->name = ckstrdup(name);
3355 ap->val = ckstrdup(val);
3356 /*ap->flag = 0; - ckzalloc did it */
3357 /*ap->next = NULL;*/
3364 unalias(const char *name)
3368 app = __lookupalias(name);
3372 *app = freealias(*app);
3383 struct alias *ap, **app;
3387 for (i = 0; i < ATABSIZE; i++) {
3389 for (ap = *app; ap; ap = *app) {
3390 *app = freealias(*app);
3400 printalias(const struct alias *ap)
3402 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3406 * TODO - sort output
3408 static int FAST_FUNC
3409 aliascmd(int argc UNUSED_PARAM, char **argv)
3418 for (i = 0; i < ATABSIZE; i++) {
3419 for (ap = atab[i]; ap; ap = ap->next) {
3425 while ((n = *++argv) != NULL) {
3426 v = strchr(n+1, '=');
3427 if (v == NULL) { /* n+1: funny ksh stuff */
3428 ap = *__lookupalias(n);
3430 fprintf(stderr, "%s: %s not found\n", "alias", n);
3443 static int FAST_FUNC
3444 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3448 while (nextopt("a") != '\0') {
3452 for (i = 0; *argptr; argptr++) {
3453 if (unalias(*argptr)) {
3454 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3462 #endif /* ASH_ALIAS */
3465 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3468 #define FORK_NOJOB 2
3470 /* mode flags for showjob(s) */
3471 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3472 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3473 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3474 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3477 * A job structure contains information about a job. A job is either a
3478 * single process or a set of processes contained in a pipeline. In the
3479 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3483 pid_t ps_pid; /* process id */
3484 int ps_status; /* last process status from wait() */
3485 char *ps_cmd; /* text of command being run */
3489 struct procstat ps0; /* status of process */
3490 struct procstat *ps; /* status or processes when more than one */
3492 int stopstatus; /* status of a stopped job */
3494 unsigned nprocs; /* number of processes */
3496 #define JOBRUNNING 0 /* at least one proc running */
3497 #define JOBSTOPPED 1 /* all procs are stopped */
3498 #define JOBDONE 2 /* all procs are completed */
3502 sigint: 1, /* job was killed by SIGINT */
3503 jobctl: 1, /* job running under job control */
3505 waited: 1, /* true if this entry has been waited for */
3506 used: 1, /* true if this entry is in used */
3507 changed: 1; /* true if status has changed */
3508 struct job *prev_job; /* previous job */
3511 static struct job *makejob(/*union node *,*/ int);
3512 static int forkshell(struct job *, union node *, int);
3513 static int waitforjob(struct job *);
3516 enum { doing_jobctl = 0 };
3517 #define setjobctl(on) do {} while (0)
3519 static smallint doing_jobctl; //references:8
3520 static void setjobctl(int);
3527 ignoresig(int signo)
3529 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3530 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3531 /* No, need to do it */
3532 signal(signo, SIG_IGN);
3534 sigmode[signo - 1] = S_HARD_IGN;
3538 * Only one usage site - in setsignal()
3541 signal_handler(int signo)
3543 if (signo == SIGCHLD) {
3549 gotsig[signo - 1] = 1;
3550 pending_sig = signo;
3552 if (signo == SIGINT && !trap[SIGINT]) {
3553 if (!suppress_int) {
3555 raise_interrupt(); /* does not return */
3562 * Set the signal handler for the specified signal. The routine figures
3563 * out what it should be set to.
3566 setsignal(int signo)
3569 char cur_act, new_act;
3570 struct sigaction act;
3574 if (t != NULL) { /* trap for this sig is set */
3576 if (t[0] == '\0') /* trap is "": ignore this sig */
3580 if (rootshell && new_act == S_DFL) {
3583 if (iflag || minusc || sflag == 0)
3592 * "In all cases, bash ignores SIGQUIT. Non-builtin
3593 * commands run by bash have signal handlers
3594 * set to the values inherited by the shell
3595 * from its parent". */
3611 /* if !rootshell, we reset SIGQUIT to DFL,
3612 * whereas we have to restore it to what shell got on entry.
3613 * This is handled by the fact that if signal was IGNored on entry,
3614 * then cur_act is S_HARD_IGN and we never change its sigaction
3618 if (signo == SIGCHLD)
3621 t = &sigmode[signo - 1];
3624 /* current setting is not yet known */
3625 if (sigaction(signo, NULL, &act)) {
3626 /* pretend it worked; maybe we should give a warning,
3627 * but other shells don't. We don't alter sigmode,
3628 * so we retry every time.
3629 * btw, in Linux it never fails. --vda */
3632 if (act.sa_handler == SIG_IGN) {
3633 cur_act = S_HARD_IGN;
3635 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3637 cur_act = S_IGN; /* don't hard ignore these */
3640 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3641 /* installing SIG_DFL over SIG_DFL is a no-op */
3642 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3647 if (cur_act == S_HARD_IGN || cur_act == new_act)
3652 act.sa_handler = SIG_DFL;
3655 act.sa_handler = signal_handler;
3658 act.sa_handler = SIG_IGN;
3661 /* flags and mask matter only if !DFL and !IGN, but we do it
3662 * for all cases for more deterministic behavior:
3664 act.sa_flags = 0; //TODO: why not SA_RESTART?
3665 sigfillset(&act.sa_mask);
3667 sigaction_set(signo, &act);
3670 /* mode flags for set_curjob */
3671 #define CUR_DELETE 2
3672 #define CUR_RUNNING 1
3673 #define CUR_STOPPED 0
3676 /* pgrp of shell on invocation */
3677 static int initialpgrp; //references:2
3678 static int ttyfd = -1; //5
3681 static struct job *jobtab; //5
3683 static unsigned njobs; //4
3685 static struct job *curjob; //lots
3686 /* number of presumed living untracked jobs */
3687 static int jobless; //4
3690 /* Bash has a feature: it restores termios after a successful wait for
3691 * a foreground job which had at least one stopped or sigkilled member.
3692 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3693 * properly restoring tty state. Should we do this too?
3694 * A reproducer: ^Z an interactive python:
3697 * Python 2.7.12 (...)
3699 * { python leaves tty in -icanon -echo state. We do survive that... }
3700 * [1]+ Stopped python
3701 * { ...however, next program (python #2) does not survive it well: }
3703 * Python 2.7.12 (...)
3704 * >>> Traceback (most recent call last):
3705 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3706 * File "<stdin>", line 1, in <module>
3707 * NameError: name 'qwerty' is not defined
3709 * The implementation below is modeled on bash code and seems to work.
3710 * However, I'm not sure we should do this. For one: what if I'd fg
3711 * the stopped python instead? It'll be confused by "restored" tty state.
3713 static struct termios shell_tty_info;
3717 if (rootshell && ttyfd >= 0)
3718 tcgetattr(ttyfd, &shell_tty_info);
3723 /* if (rootshell) - caller ensures this */
3725 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3728 job_signal_status(struct job *jp)
3732 struct procstat *ps = jp->ps;
3733 for (i = 0; i < jp->nprocs; i++) {
3734 status = ps[i].ps_status;
3735 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3741 restore_tty_if_stopped_or_signaled(struct job *jp)
3743 //TODO: check what happens if we come from waitforjob() in expbackq()
3745 int s = job_signal_status(jp);
3746 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3751 # define get_tty_state() ((void)0)
3752 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3756 set_curjob(struct job *jp, unsigned mode)
3759 struct job **jpp, **curp;
3761 /* first remove from list */
3762 jpp = curp = &curjob;
3767 jpp = &jp1->prev_job;
3769 *jpp = jp1->prev_job;
3771 /* Then re-insert in correct position */
3779 /* job being deleted */
3782 /* newly created job or backgrounded job,
3783 * put after all stopped jobs.
3788 if (!jp1 || jp1->state != JOBSTOPPED)
3791 jpp = &jp1->prev_job;
3797 /* newly stopped job - becomes curjob */
3798 jp->prev_job = *jpp;
3806 jobno(const struct job *jp)
3808 return jp - jobtab + 1;
3813 * Convert a job name to a job structure.
3816 #define getjob(name, getctl) getjob(name)
3819 getjob(const char *name, int getctl)
3823 const char *err_msg = "%s: no such job";
3827 char *(*match)(const char *, const char *);
3842 if (c == '+' || c == '%') {
3844 err_msg = "No current job";
3850 err_msg = "No previous job";
3860 if (num > 0 && num <= njobs) {
3861 jp = jobtab + num - 1;
3876 if (match(jp->ps[0].ps_cmd, p)) {
3880 err_msg = "%s: ambiguous";
3890 err_msg = "job %s not created under job control";
3891 if (getctl && jp->jobctl == 0)
3896 ash_msg_and_raise_error(err_msg, name);
3900 * Mark a job structure as unused.
3903 freejob(struct job *jp)
3905 struct procstat *ps;
3909 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3910 if (ps->ps_cmd != nullstr)
3913 if (jp->ps != &jp->ps0)
3916 set_curjob(jp, CUR_DELETE);
3922 xtcsetpgrp(int fd, pid_t pgrp)
3924 if (tcsetpgrp(fd, pgrp))
3925 ash_msg_and_raise_perror("can't set tty process group");
3929 * Turn job control on and off.
3931 * Note: This code assumes that the third arg to ioctl is a character
3932 * pointer, which is true on Berkeley systems but not System V. Since
3933 * System V doesn't have job control yet, this isn't a problem now.
3935 * Called with interrupts off.
3943 if (on == doing_jobctl || rootshell == 0)
3947 ofd = fd = open(_PATH_TTY, O_RDWR);
3949 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3950 * That sometimes helps to acquire controlling tty.
3951 * Obviously, a workaround for bugs when someone
3952 * failed to provide a controlling tty to bash! :) */
3958 /* fd is a tty at this point */
3959 fd = fcntl(fd, F_DUPFD, 10);
3960 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3963 goto out; /* F_DUPFD failed */
3964 close_on_exec_on(fd);
3965 while (1) { /* while we are in the background */
3966 pgrp = tcgetpgrp(fd);
3969 ash_msg("can't access tty; job control turned off");
3973 if (pgrp == getpgrp())
3984 xtcsetpgrp(fd, pgrp);
3986 /* turning job control off */
3989 /* was xtcsetpgrp, but this can make exiting ash
3990 * loop forever if pty is already deleted */
3991 tcsetpgrp(fd, pgrp);
4005 static int FAST_FUNC
4006 killcmd(int argc, char **argv)
4008 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4011 if (argv[i][0] == '%') {
4013 * "kill %N" - job kill
4014 * Converting to pgrp / pid kill
4020 jp = getjob(argv[i], 0);
4022 * In jobs started under job control, we signal
4023 * entire process group by kill -PGRP_ID.
4024 * This happens, f.e., in interactive shell.
4026 * Otherwise, we signal each child via
4027 * kill PID1 PID2 PID3.
4029 * sh -c 'sleep 1|sleep 1 & kill %1'
4030 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4031 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4033 n = jp->nprocs; /* can't be 0 (I hope) */
4036 dst = alloca(n * sizeof(int)*4);
4038 for (j = 0; j < n; j++) {
4039 struct procstat *ps = &jp->ps[j];
4040 /* Skip non-running and not-stopped members
4041 * (i.e. dead members) of the job
4043 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4046 * kill_main has matching code to expect
4047 * leading space. Needed to not confuse
4048 * negative pids with "kill -SIGNAL_NO" syntax
4050 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4054 } while (argv[++i]);
4056 return kill_main(argc, argv);
4060 showpipe(struct job *jp /*, FILE *out*/)
4062 struct procstat *ps;
4063 struct procstat *psend;
4065 psend = jp->ps + jp->nprocs;
4066 for (ps = jp->ps + 1; ps < psend; ps++)
4067 printf(" | %s", ps->ps_cmd);
4068 newline_and_flush(stdout);
4069 flush_stdout_stderr();
4074 restartjob(struct job *jp, int mode)
4076 struct procstat *ps;
4082 if (jp->state == JOBDONE)
4084 jp->state = JOBRUNNING;
4085 pgid = jp->ps[0].ps_pid;
4086 if (mode == FORK_FG) {
4088 xtcsetpgrp(ttyfd, pgid);
4090 killpg(pgid, SIGCONT);
4094 if (WIFSTOPPED(ps->ps_status)) {
4100 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4105 static int FAST_FUNC
4106 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4112 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4116 jp = getjob(*argv, 1);
4117 if (mode == FORK_BG) {
4118 set_curjob(jp, CUR_RUNNING);
4119 printf("[%d] ", jobno(jp));
4121 out1str(jp->ps[0].ps_cmd);
4122 showpipe(jp /*, stdout*/);
4123 retval = restartjob(jp, mode);
4124 } while (*argv && *++argv);
4130 sprint_status48(char *s, int status, int sigonly)
4136 if (!WIFEXITED(status)) {
4138 if (WIFSTOPPED(status))
4139 st = WSTOPSIG(status);
4142 st = WTERMSIG(status);
4144 if (st == SIGINT || st == SIGPIPE)
4147 if (WIFSTOPPED(status))
4152 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4153 col = fmtstr(s, 32, strsignal(st));
4154 if (WCOREDUMP(status)) {
4155 strcpy(s + col, " (core dumped)");
4156 col += sizeof(" (core dumped)")-1;
4158 } else if (!sigonly) {
4159 st = WEXITSTATUS(status);
4160 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4167 wait_block_or_sig(int *status)
4174 /* Poll all children for changes in their state */
4176 /* if job control is active, accept stopped processes too */
4177 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4179 break; /* Error (e.g. EINTR, ECHILD) or pid */
4181 /* Children exist, but none are ready. Sleep until interesting signal */
4184 sigprocmask(SIG_SETMASK, &mask, &mask);
4185 while (!got_sigchld && !pending_sig)
4187 sigprocmask(SIG_SETMASK, &mask, NULL);
4188 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4189 while (!got_sigchld && !pending_sig)
4193 /* If it was SIGCHLD, poll children again */
4194 } while (got_sigchld);
4199 #define DOWAIT_NONBLOCK 0
4200 #define DOWAIT_BLOCK 1
4201 #define DOWAIT_BLOCK_OR_SIG 2
4204 dowait(int block, struct job *job)
4209 struct job *thisjob = NULL;
4211 TRACE(("dowait(0x%x) called\n", block));
4213 /* It's wrong to call waitpid() outside of INT_OFF region:
4214 * signal can arrive just after syscall return and handler can
4215 * longjmp away, losing stop/exit notification processing.
4216 * Thus, for "jobs" builtin, and for waiting for a fg job,
4217 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4219 * However, for "wait" builtin it is wrong to simply call waitpid()
4220 * in INT_OFF region: "wait" needs to wait for any running job
4221 * to change state, but should exit on any trap too.
4222 * In INT_OFF region, a signal just before syscall entry can set
4223 * pending_sig variables, but we can't check them, and we would
4224 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4226 * Because of this, we run inside INT_OFF, but use a special routine
4227 * which combines waitpid() and sigsuspend().
4228 * This is the reason why we need to have a handler for SIGCHLD:
4229 * SIG_DFL handler does not wake sigsuspend().
4232 if (block == DOWAIT_BLOCK_OR_SIG) {
4233 pid = wait_block_or_sig(&status);
4236 if (block == DOWAIT_NONBLOCK)
4237 wait_flags = WNOHANG;
4238 /* if job control is active, accept stopped processes too */
4240 wait_flags |= WUNTRACED;
4241 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4242 pid = waitpid(-1, &status, wait_flags);
4244 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4245 pid, status, errno, strerror(errno)));
4250 for (jp = curjob; jp; jp = jp->prev_job) {
4252 struct procstat *ps;
4253 struct procstat *psend;
4254 if (jp->state == JOBDONE)
4258 psend = ps + jp->nprocs;
4260 if (ps->ps_pid == pid) {
4261 TRACE(("Job %d: changing status of proc %d "
4262 "from 0x%x to 0x%x\n",
4263 jobno(jp), pid, ps->ps_status, status));
4264 ps->ps_status = status;
4267 if (ps->ps_status == -1)
4268 jobstate = JOBRUNNING;
4270 if (jobstate == JOBRUNNING)
4272 if (WIFSTOPPED(ps->ps_status)) {
4273 jp->stopstatus = ps->ps_status;
4274 jobstate = JOBSTOPPED;
4277 } while (++ps < psend);
4281 /* Found the job where one of its processes changed its state.
4282 * Is there at least one live and running process in this job? */
4283 if (jobstate != JOBRUNNING) {
4284 /* No. All live processes in the job are stopped
4285 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4287 thisjob->changed = 1;
4288 if (thisjob->state != jobstate) {
4289 TRACE(("Job %d: changing state from %d to %d\n",
4290 jobno(thisjob), thisjob->state, jobstate));
4291 thisjob->state = jobstate;
4293 if (jobstate == JOBSTOPPED)
4294 set_curjob(thisjob, CUR_STOPPED);
4300 /* The process wasn't found in job list */
4302 if (!WIFSTOPPED(status))
4308 if (thisjob && thisjob == job) {
4312 len = sprint_status48(s, status, 1);
4324 showjob(struct job *jp, int mode)
4326 struct procstat *ps;
4327 struct procstat *psend;
4330 char s[16 + 16 + 48];
4331 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4335 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4336 /* just output process (group) id of pipeline */
4337 fprintf(out, "%d\n", ps->ps_pid);
4341 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4346 else if (curjob && jp == curjob->prev_job)
4349 if (mode & SHOW_PIDS)
4350 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4352 psend = ps + jp->nprocs;
4354 if (jp->state == JOBRUNNING) {
4355 strcpy(s + col, "Running");
4356 col += sizeof("Running") - 1;
4358 int status = psend[-1].ps_status;
4359 if (jp->state == JOBSTOPPED)
4360 status = jp->stopstatus;
4361 col += sprint_status48(s + col, status, 0);
4363 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4365 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4366 * or prints several "PID | <cmdN>" lines,
4367 * depending on SHOW_PIDS bit.
4368 * We do not print status of individual processes
4369 * between PID and <cmdN>. bash does it, but not very well:
4370 * first line shows overall job status, not process status,
4371 * making it impossible to know 1st process status.
4375 /* for each process */
4378 if (mode & SHOW_PIDS)
4379 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4381 fprintf(out, "%s%*c%s%s",
4383 33 - col >= 0 ? 33 - col : 0, ' ',
4384 ps == jp->ps ? "" : "| ",
4387 } while (++ps != psend);
4388 newline_and_flush(out);
4392 if (jp->state == JOBDONE) {
4393 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4399 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4400 * statuses have changed since the last call to showjobs.
4407 TRACE(("showjobs(0x%x) called\n", mode));
4409 /* Handle all finished jobs */
4410 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4413 for (jp = curjob; jp; jp = jp->prev_job) {
4414 if (!(mode & SHOW_CHANGED) || jp->changed) {
4420 static int FAST_FUNC
4421 jobscmd(int argc UNUSED_PARAM, char **argv)
4426 while ((m = nextopt("lp")) != '\0') {
4430 mode |= SHOW_ONLY_PGID;
4436 showjob(getjob(*argv, 0), mode);
4446 /* Called only on finished or stopped jobs (no members are running) */
4448 getstatus(struct job *job)
4452 struct procstat *ps;
4454 /* Fetch last member's status */
4455 ps = job->ps + job->nprocs - 1;
4456 status = ps->ps_status;
4458 /* "set -o pipefail" mode: use last _nonzero_ status */
4459 while (status == 0 && --ps >= job->ps)
4460 status = ps->ps_status;
4463 retval = WEXITSTATUS(status);
4464 if (!WIFEXITED(status)) {
4466 retval = WSTOPSIG(status);
4467 if (!WIFSTOPPED(status))
4470 /* XXX: limits number of signals */
4471 retval = WTERMSIG(status);
4473 if (retval == SIGINT)
4479 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4480 jobno(job), job->nprocs, status, retval));
4484 static int FAST_FUNC
4485 waitcmd(int argc UNUSED_PARAM, char **argv)
4496 /* wait for all jobs */
4500 if (!jp) /* no running procs */
4502 if (jp->state == JOBRUNNING)
4508 * "When bash is waiting for an asynchronous command via
4509 * the wait builtin, the reception of a signal for which a trap
4510 * has been set will cause the wait builtin to return immediately
4511 * with an exit status greater than 128, immediately after which
4512 * the trap is executed."
4514 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4515 /* if child sends us a signal *and immediately exits*,
4516 * dowait() returns pid > 0. Check this case,
4517 * not "if (dowait() < 0)"!
4526 if (**argv != '%') {
4527 pid_t pid = number(*argv);
4532 if (job->ps[job->nprocs - 1].ps_pid == pid)
4534 job = job->prev_job;
4537 job = getjob(*argv, 0);
4539 /* loop until process terminated or stopped */
4540 while (job->state == JOBRUNNING) {
4541 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4546 retval = getstatus(job);
4553 retval = 128 + pending_sig;
4562 struct job *jp, *jq;
4564 len = njobs * sizeof(*jp);
4566 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4568 offset = (char *)jp - (char *)jq;
4570 /* Relocate pointers */
4573 jq = (struct job *)((char *)jq + l);
4577 #define joff(p) ((struct job *)((char *)(p) + l))
4578 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4579 if (joff(jp)->ps == &jq->ps0)
4580 jmove(joff(jp)->ps);
4581 if (joff(jp)->prev_job)
4582 jmove(joff(jp)->prev_job);
4592 jp = (struct job *)((char *)jp + len);
4596 } while (--jq >= jp);
4601 * Return a new job structure.
4602 * Called with interrupts off.
4605 makejob(/*union node *node,*/ int nprocs)
4610 for (i = njobs, jp = jobtab; ; jp++) {
4617 if (jp->state != JOBDONE || !jp->waited)
4626 memset(jp, 0, sizeof(*jp));
4628 /* jp->jobctl is a bitfield.
4629 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4633 jp->prev_job = curjob;
4638 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4640 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4647 * Return a string identifying a command (to be printed by the
4650 static char *cmdnextc;
4653 cmdputs(const char *s)
4655 static const char vstype[VSTYPE + 1][3] = {
4656 "", "}", "-", "+", "?", "=",
4657 "%", "%%", "#", "##"
4658 IF_BASH_SUBSTR(, ":")
4659 IF_BASH_PATTERN_SUBST(, "/", "//")
4662 const char *p, *str;
4666 unsigned char subtype = 0;
4670 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4672 while ((c = *p++) != '\0') {
4680 if ((subtype & VSTYPE) == VSLENGTH)
4686 str = "\"}" + !(quoted & 1);
4693 #if ENABLE_FEATURE_SH_MATH
4708 if ((subtype & VSTYPE) != VSNORMAL)
4710 str = vstype[subtype & VSTYPE];
4711 if (subtype & VSNUL)
4720 /* These can only happen inside quotes */
4726 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4737 while ((c = *str++) != '\0') {
4740 } /* while *p++ not NUL */
4743 USTPUTC('"', nextc);
4749 /* cmdtxt() and cmdlist() call each other */
4750 static void cmdtxt(union node *n);
4753 cmdlist(union node *np, int sep)
4755 for (; np; np = np->narg.next) {
4759 if (sep && np->narg.next)
4765 cmdtxt(union node *n)
4768 struct nodelist *lp;
4779 lp = n->npipe.cmdlist;
4797 cmdtxt(n->nbinary.ch1);
4813 cmdtxt(n->nif.test);
4815 if (n->nif.elsepart) {
4816 cmdtxt(n->nif.ifpart);
4818 n = n->nif.elsepart;
4836 cmdtxt(n->nbinary.ch1);
4846 cmdputs(n->nfor.var);
4848 cmdlist(n->nfor.args, 1);
4853 cmdputs(n->ndefun.text);
4857 cmdlist(n->ncmd.args, 1);
4858 cmdlist(n->ncmd.redirect, 0);
4871 cmdputs(n->ncase.expr->narg.text);
4873 for (np = n->ncase.cases; np; np = np->nclist.next) {
4874 cmdtxt(np->nclist.pattern);
4876 cmdtxt(np->nclist.body);
4890 #if BASH_REDIR_OUTPUT
4905 cmdputs(utoa(n->nfile.fd));
4907 if (n->type == NTOFD || n->type == NFROMFD) {
4908 if (n->ndup.dupfd >= 0)
4909 cmdputs(utoa(n->ndup.dupfd));
4920 commandtext(union node *n)
4924 STARTSTACKSTR(cmdnextc);
4926 name = stackblock();
4927 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4928 return ckstrdup(name);
4933 * Fork off a subshell. If we are doing job control, give the subshell its
4934 * own process group. Jp is a job structure that the job is to be added to.
4935 * N is the command that will be evaluated by the child. Both jp and n may
4936 * be NULL. The mode parameter can be one of the following:
4937 * FORK_FG - Fork off a foreground process.
4938 * FORK_BG - Fork off a background process.
4939 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4940 * process group even if job control is on.
4942 * When job control is turned off, background processes have their standard
4943 * input redirected to /dev/null (except for the second and later processes
4946 * Called with interrupts off.
4949 * Clear traps on a fork.
4957 for (tp = trap; tp < &trap[NSIG]; tp++) {
4958 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4959 if (trap_ptr == trap)
4961 /* else: it "belongs" to trap_ptr vector, don't free */
4963 if ((tp - trap) != 0)
4964 setsignal(tp - trap);
4971 /* Lives far away from here, needed for forkchild */
4972 static void closescript(void);
4974 /* Called after fork(), in child */
4975 /* jp and n are NULL when called by openhere() for heredoc support */
4976 static NOINLINE void
4977 forkchild(struct job *jp, union node *n, int mode)
4981 TRACE(("Child shell %d\n", getpid()));
4985 /* man bash: "Non-builtin commands run by bash have signal handlers
4986 * set to the values inherited by the shell from its parent".
4987 * Do we do it correctly? */
4991 if (mode == FORK_NOJOB /* is it `xxx` ? */
4992 && n && n->type == NCMD /* is it single cmd? */
4993 /* && n->ncmd.args->type == NARG - always true? */
4994 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4995 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4996 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4998 TRACE(("Trap hack\n"));
4999 /* Awful hack for `trap` or $(trap).
5001 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5002 * contains an example where "trap" is executed in a subshell:
5004 * save_traps=$(trap)
5006 * eval "$save_traps"
5008 * Standard does not say that "trap" in subshell shall print
5009 * parent shell's traps. It only says that its output
5010 * must have suitable form, but then, in the above example
5011 * (which is not supposed to be normative), it implies that.
5013 * bash (and probably other shell) does implement it
5014 * (traps are reset to defaults, but "trap" still shows them),
5015 * but as a result, "trap" logic is hopelessly messed up:
5018 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5019 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5020 * # true | trap <--- trap is in subshell - no output (ditto)
5021 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5022 * trap -- 'echo Ho' SIGWINCH
5023 * # echo `(trap)` <--- in subshell in subshell - output
5024 * trap -- 'echo Ho' SIGWINCH
5025 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5026 * trap -- 'echo Ho' SIGWINCH
5028 * The rules when to forget and when to not forget traps
5029 * get really complex and nonsensical.
5031 * Our solution: ONLY bare $(trap) or `trap` is special.
5033 /* Save trap handler strings for trap builtin to print */
5034 trap_ptr = xmemdup(trap, sizeof(trap));
5035 /* Fall through into clearing traps */
5039 /* do job control only in root shell */
5041 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5044 if (jp->nprocs == 0)
5047 pgrp = jp->ps[0].ps_pid;
5048 /* this can fail because we are doing it in the parent also */
5050 if (mode == FORK_FG)
5051 xtcsetpgrp(ttyfd, pgrp);
5056 if (mode == FORK_BG) {
5057 /* man bash: "When job control is not in effect,
5058 * asynchronous commands ignore SIGINT and SIGQUIT" */
5061 if (jp->nprocs == 0) {
5063 if (open(bb_dev_null, O_RDONLY) != 0)
5064 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5068 if (iflag) { /* why if iflag only? */
5073 * "In all cases, bash ignores SIGQUIT. Non-builtin
5074 * commands run by bash have signal handlers
5075 * set to the values inherited by the shell
5077 * Take care of the second rule: */
5081 if (n && n->type == NCMD
5082 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5084 TRACE(("Job hack\n"));
5085 /* "jobs": we do not want to clear job list for it,
5086 * instead we remove only _its_ own_ job from job list.
5087 * This makes "jobs .... | cat" more useful.
5093 for (jp = curjob; jp; jp = jp->prev_job)
5098 /* Called after fork(), in parent */
5100 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5103 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5105 TRACE(("In parent shell: child = %d\n", pid));
5107 /* jp is NULL when called by openhere() for heredoc support */
5108 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5114 if (mode != FORK_NOJOB && jp->jobctl) {
5117 if (jp->nprocs == 0)
5120 pgrp = jp->ps[0].ps_pid;
5121 /* This can fail because we are doing it in the child also */
5125 if (mode == FORK_BG) {
5126 backgndpid = pid; /* set $! */
5127 set_curjob(jp, CUR_RUNNING);
5130 struct procstat *ps = &jp->ps[jp->nprocs++];
5133 ps->ps_cmd = nullstr;
5135 if (doing_jobctl && n)
5136 ps->ps_cmd = commandtext(n);
5141 /* jp and n are NULL when called by openhere() for heredoc support */
5143 forkshell(struct job *jp, union node *n, int mode)
5147 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5150 TRACE(("Fork failed, errno=%d", errno));
5153 ash_msg_and_raise_perror("can't fork");
5156 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5157 forkchild(jp, n, mode);
5159 forkparent(jp, n, mode, pid);
5165 * Wait for job to finish.
5167 * Under job control we have the problem that while a child process
5168 * is running interrupts generated by the user are sent to the child
5169 * but not to the shell. This means that an infinite loop started by
5170 * an interactive user may be hard to kill. With job control turned off,
5171 * an interactive user may place an interactive program inside a loop.
5172 * If the interactive program catches interrupts, the user doesn't want
5173 * these interrupts to also abort the loop. The approach we take here
5174 * is to have the shell ignore interrupt signals while waiting for a
5175 * foreground process to terminate, and then send itself an interrupt
5176 * signal if the child process was terminated by an interrupt signal.
5177 * Unfortunately, some programs want to do a bit of cleanup and then
5178 * exit on interrupt; unless these processes terminate themselves by
5179 * sending a signal to themselves (instead of calling exit) they will
5180 * confuse this approach.
5182 * Called with interrupts off.
5185 waitforjob(struct job *jp)
5189 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5192 while (jp->state == JOBRUNNING) {
5193 /* In non-interactive shells, we _can_ get
5194 * a keyboard signal here and be EINTRed,
5195 * but we just loop back, waiting for command to complete.
5198 * "If bash is waiting for a command to complete and receives
5199 * a signal for which a trap has been set, the trap
5200 * will not be executed until the command completes."
5202 * Reality is that even if trap is not set, bash
5203 * will not act on the signal until command completes.
5204 * Try this. sleep5intoff.c:
5205 * #include <signal.h>
5206 * #include <unistd.h>
5209 * sigemptyset(&set);
5210 * sigaddset(&set, SIGINT);
5211 * sigaddset(&set, SIGQUIT);
5212 * sigprocmask(SIG_BLOCK, &set, NULL);
5216 * $ bash -c './sleep5intoff; echo hi'
5217 * ^C^C^C^C <--- pressing ^C once a second
5219 * $ bash -c './sleep5intoff; echo hi'
5220 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5223 dowait(DOWAIT_BLOCK, jp);
5230 xtcsetpgrp(ttyfd, rootpid);
5231 restore_tty_if_stopped_or_signaled(jp);
5234 * This is truly gross.
5235 * If we're doing job control, then we did a TIOCSPGRP which
5236 * caused us (the shell) to no longer be in the controlling
5237 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5238 * intuit from the subprocess exit status whether a SIGINT
5239 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5241 if (jp->sigint) /* TODO: do the same with all signals */
5242 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5244 if (jp->state == JOBDONE)
5251 * return 1 if there are stopped jobs, otherwise 0
5263 if (jp && jp->state == JOBSTOPPED) {
5264 out2str("You have stopped jobs.\n");
5274 * Code for dealing with input/output redirection.
5279 #define EMPTY -2 /* marks an unused slot in redirtab */
5280 #define CLOSED -1 /* marks a slot of previously-closed fd */
5283 * Handle here documents. Normally we fork off a process to write the
5284 * data to a pipe. If the document is short, we can stuff the data in
5285 * the pipe without forking.
5287 /* openhere needs this forward reference */
5288 static void expandhere(union node *arg, int fd);
5290 openhere(union node *redir)
5296 ash_msg_and_raise_perror("can't create pipe");
5297 if (redir->type == NHERE) {
5298 len = strlen(redir->nhere.doc->narg.text);
5299 if (len <= PIPE_BUF) {
5300 full_write(pip[1], redir->nhere.doc->narg.text, len);
5304 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5307 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5308 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5309 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5310 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5311 signal(SIGPIPE, SIG_DFL);
5312 if (redir->type == NHERE)
5313 full_write(pip[1], redir->nhere.doc->narg.text, len);
5315 expandhere(redir->nhere.doc, pip[1]);
5316 _exit(EXIT_SUCCESS);
5324 openredirect(union node *redir)
5330 switch (redir->nfile.type) {
5331 /* Can't happen, our single caller does this itself */
5337 return openhere(redir);
5340 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5341 * allocated space. Do it only when we know it is safe.
5343 fname = redir->nfile.expfname;
5345 switch (redir->nfile.type) {
5351 f = open(fname, O_RDONLY);
5356 f = open(fname, O_RDWR|O_CREAT, 0666);
5361 #if BASH_REDIR_OUTPUT
5364 /* Take care of noclobber mode. */
5366 if (stat(fname, &sb) < 0) {
5367 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5370 } else if (!S_ISREG(sb.st_mode)) {
5371 f = open(fname, O_WRONLY, 0666);
5374 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5387 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5392 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5400 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5402 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5406 * Copy a file descriptor to be >= 10. Throws exception on error.
5414 newfd = fcntl(from, F_DUPFD, 10);
5415 err = newfd < 0 ? errno : 0;
5418 ash_msg_and_raise_perror("%d", from);
5420 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5426 dup2_or_raise(int from, int to)
5430 newfd = (from != to) ? dup2(from, to) : to;
5432 /* Happens when source fd is not open: try "echo >&99" */
5433 ash_msg_and_raise_perror("%d", from);
5438 fcntl_F_DUPFD(int fd, int avoid_fd)
5442 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5452 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5456 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5462 /* fd was not open? */
5465 ash_msg_and_raise_perror("%d", newfd);
5467 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5472 /* Struct def and variable are moved down to the first usage site */
5478 struct redirtab *next;
5480 struct squirrel two_fd[];
5482 #define redirlist (G_var.redirlist)
5485 add_squirrel_closed(struct redirtab *sq, int fd)
5492 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5493 /* If we collide with an already moved fd... */
5494 if (fd == sq->two_fd[i].orig_fd) {
5496 * "echo 3>FILE 3>&- 3>FILE"
5497 * "echo 3>&- 3>FILE"
5498 * No need for last redirect to insert
5499 * another "need to close 3" indicator.
5501 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5505 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5506 sq->two_fd[i].orig_fd = fd;
5507 sq->two_fd[i].moved_to = CLOSED;
5511 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5515 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5520 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5521 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5522 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5523 return 1; /* "we closed fd" */
5526 /* Are we called from redirect(0)? E.g. redirect
5527 * in a forked child. No need to save fds,
5528 * we aren't going to use them anymore, ok to trash.
5533 /* If this one of script's fds? */
5535 struct parsefile *pf = g_parsefile;
5537 /* We skip fd == 0 case because of the following:
5538 * $ ash # running ash interactively
5540 * and in script.sh: "exec 9>&0".
5541 * Even though top-level pf_fd _is_ 0,
5542 * it's still ok to use it: "read" builtin uses it,
5543 * why should we cripple "exec" builtin?
5545 if (fd == pf->pf_fd) {
5546 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5547 return 1; /* "we closed fd" */
5553 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5555 /* First: do we collide with some already moved fds? */
5556 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5557 /* If we collide with an already moved fd... */
5558 if (fd == sq->two_fd[i].moved_to) {
5559 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5560 sq->two_fd[i].moved_to = new_fd;
5561 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5562 if (new_fd < 0) /* what? */
5564 return 0; /* "we did not close fd" */
5566 if (fd == sq->two_fd[i].orig_fd) {
5567 /* Example: echo Hello >/dev/null 1>&2 */
5568 TRACE(("redirect_fd %d: already moved\n", fd));
5569 return 0; /* "we did not close fd" */
5573 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5574 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5575 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5579 /* new_fd = CLOSED; - already is -1 */
5581 sq->two_fd[i].moved_to = new_fd;
5582 sq->two_fd[i].orig_fd = fd;
5584 /* if we move stderr, let "set -x" code know */
5585 if (fd == preverrout_fd)
5586 preverrout_fd = new_fd;
5588 return 0; /* "we did not close fd" */
5592 internally_opened_fd(int fd, struct redirtab *sq)
5599 /* If this one of script's fds? */
5601 struct parsefile *pf = g_parsefile;
5603 if (fd == pf->pf_fd)
5609 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5610 if (fd == sq->two_fd[i].moved_to)
5617 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5618 * old file descriptors are stashed away so that the redirection can be
5619 * undone by calling popredir.
5621 /* flags passed to redirect */
5622 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5624 redirect(union node *redir, int flags)
5626 struct redirtab *sv;
5633 if (flags & REDIR_PUSH)
5641 fd = redir->nfile.fd;
5642 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5643 //bb_error_msg("doing %d > %d", fd, newfd);
5644 newfd = redir->ndup.dupfd;
5647 newfd = openredirect(redir); /* always >= 0 */
5649 /* open() gave us precisely the fd we wanted.
5650 * This means that this fd was not busy
5651 * (not opened to anywhere).
5652 * Remember to close it on restore:
5654 add_squirrel_closed(sv, fd);
5663 /* if "N>FILE": move newfd to fd */
5664 /* if "N>&M": dup newfd to fd */
5665 /* if "N>&-": close fd (newfd is -1) */
5667 IF_BASH_REDIR_OUTPUT(redirect_more:)
5669 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5671 /* "N>&-" means "close me" */
5673 /* ^^^ optimization: saving may already
5674 * have closed it. If not... */
5678 /* if newfd is a script fd or saved fd, simulate EBADF */
5679 if (internally_opened_fd(newfd, sv)) {
5681 ash_msg_and_raise_perror("%d", newfd);
5683 dup2_or_raise(newfd, fd);
5684 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5686 #if BASH_REDIR_OUTPUT
5687 if (redir->nfile.type == NTO2 && fd == 1) {
5688 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5696 } while ((redir = redir->nfile.next) != NULL);
5699 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5700 #define REDIR_SAVEFD2 0
5701 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5702 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5703 // not only for calls with flags containing REDIR_SAVEFD2.
5704 // We do this unconditionally (see save_fd_on_redirect()).
5705 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5706 // preverrout_fd = copied_fd2;
5710 redirectsafe(union node *redir, int flags)
5713 volatile int saveint;
5714 struct jmploc *volatile savehandler = exception_handler;
5715 struct jmploc jmploc;
5718 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5719 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5721 exception_handler = &jmploc;
5722 redirect(redir, flags);
5724 exception_handler = savehandler;
5725 if (err && exception_type != EXERROR)
5726 longjmp(exception_handler->loc, 1);
5727 RESTORE_INT(saveint);
5731 static struct redirtab*
5732 pushredir(union node *redir)
5734 struct redirtab *sv;
5743 #if BASH_REDIR_OUTPUT
5744 if (redir->nfile.type == NTO2)
5747 redir = redir->nfile.next;
5750 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5753 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5754 sv->next = redirlist;
5760 * Undo the effects of the last redirection.
5765 struct redirtab *rp;
5768 if (redirlist == NULL)
5772 for (i = 0; i < rp->pair_count; i++) {
5773 int fd = rp->two_fd[i].orig_fd;
5774 int copy = rp->two_fd[i].moved_to;
5775 if (copy == CLOSED) {
5780 if (copy != EMPTY) {
5783 dup2_or_raise(copy, fd);
5788 redirlist = rp->next;
5794 unwindredir(struct redirtab *stop)
5796 while (redirlist != stop)
5797 popredir(/*drop:*/ 0);
5801 /* ============ Routines to expand arguments to commands
5803 * We have to deal with backquotes, shell variables, and file metacharacters.
5806 #if ENABLE_FEATURE_SH_MATH
5808 ash_arith(const char *s)
5810 arith_state_t math_state;
5813 math_state.lookupvar = lookupvar;
5814 math_state.setvar = setvar0;
5815 //math_state.endofname = endofname;
5818 result = arith(&math_state, s);
5819 if (math_state.errmsg)
5820 ash_msg_and_raise_error(math_state.errmsg);
5827 # if ENABLE_FEATURE_SH_MATH
5828 static int substr_atoi(const char *s)
5830 arith_t t = ash_arith(s);
5831 if (sizeof(t) > sizeof(int)) {
5832 /* clamp very large or very large negative nums for ${v:N:M}:
5833 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5843 # define substr_atoi(s) number(s)
5850 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5851 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5852 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5853 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5854 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5855 * POSIX says for this case:
5856 * Pathname expansion shall not be performed on the word by a
5857 * non-interactive shell; an interactive shell may perform it, but shall
5858 * do so only when the expansion would result in one word.
5859 * Currently, our code complies to the above rule by never globbing
5860 * redirection filenames.
5861 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5862 * (this means that on a typical Linux distro, bash almost always
5863 * performs globbing, and thus diverges from what we do).
5865 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5866 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5867 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5868 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5869 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5873 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5874 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5875 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5876 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5878 /* Add CTLESC when necessary. */
5879 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5880 /* Do not skip NUL characters. */
5881 #define QUOTES_KEEPNUL EXP_TILDE
5884 * Structure specifying which parts of the string should be searched
5885 * for IFS characters.
5888 struct ifsregion *next; /* next region in list */
5889 int begoff; /* offset of start of region */
5890 int endoff; /* offset of end of region */
5891 int nulonly; /* search for nul bytes only */
5895 struct strlist *list;
5896 struct strlist **lastp;
5899 /* output of current string */
5900 static char *expdest;
5901 /* list of back quote expressions */
5902 static struct nodelist *argbackq;
5903 /* first struct in list of ifs regions */
5904 static struct ifsregion ifsfirst;
5905 /* last struct in list */
5906 static struct ifsregion *ifslastp;
5907 /* holds expanded arg list */
5908 static struct arglist exparg;
5912 * cvtnum() is used even if math support is off (to prepare $? values and such).
5919 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5920 len = sizeof(arith_t) * 3;
5921 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5922 if (sizeof(arith_t) < 4) len += 2;
5924 expdest = makestrspace(len, expdest);
5925 len = fmtstr(expdest, len, ARITH_FMT, num);
5926 STADJUST(len, expdest);
5931 * Break the argument string into pieces based upon IFS and add the
5932 * strings to the argument list. The regions of the string to be
5933 * searched for IFS characters have been stored by recordregion.
5936 ifsbreakup(char *string, struct arglist *arglist)
5938 struct ifsregion *ifsp;
5943 const char *ifs, *realifs;
5948 if (ifslastp != NULL) {
5951 realifs = ifsset() ? ifsval() : defifs;
5954 p = string + ifsp->begoff;
5955 nulonly = ifsp->nulonly;
5956 ifs = nulonly ? nullstr : realifs;
5958 while (p < string + ifsp->endoff) {
5960 if ((unsigned char)*p == CTLESC)
5962 if (!strchr(ifs, *p)) {
5967 ifsspc = (strchr(defifs, *p) != NULL);
5968 /* Ignore IFS whitespace at start */
5969 if (q == start && ifsspc) {
5975 sp = stzalloc(sizeof(*sp));
5977 *arglist->lastp = sp;
5978 arglist->lastp = &sp->next;
5982 if (p >= string + ifsp->endoff) {
5986 if ((unsigned char)*p == CTLESC)
5988 if (strchr(ifs, *p) == NULL) {
5992 if (strchr(defifs, *p) == NULL) {
6007 } while (ifsp != NULL);
6016 sp = stzalloc(sizeof(*sp));
6018 *arglist->lastp = sp;
6019 arglist->lastp = &sp->next;
6025 struct ifsregion *p = ifsfirst.next;
6032 struct ifsregion *ifsp;
6037 ifsfirst.next = NULL;
6044 esclen(const char *start, const char *p)
6048 while (p > start && (unsigned char)*--p == CTLESC) {
6055 * Remove any CTLESC characters from a string.
6057 #if !BASH_PATTERN_SUBST
6058 #define rmescapes(str, flag, slash_position) \
6059 rmescapes(str, flag)
6062 rmescapes(char *str, int flag, int *slash_position)
6064 static const char qchars[] ALIGN1 = {
6065 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6069 unsigned protect_against_glob;
6072 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6078 if (flag & RMESCAPE_ALLOC) {
6079 size_t len = p - str;
6080 size_t fulllen = len + strlen(p) + 1;
6082 if (flag & RMESCAPE_GROW) {
6083 int strloc = str - (char *)stackblock();
6084 r = makestrspace(fulllen, expdest);
6085 /* p and str may be invalidated by makestrspace */
6086 str = (char *)stackblock() + strloc;
6088 } else if (flag & RMESCAPE_HEAP) {
6089 r = ckmalloc(fulllen);
6091 r = stalloc(fulllen);
6095 q = (char *)mempcpy(q, str, len);
6100 globbing = flag & RMESCAPE_GLOB;
6101 protect_against_glob = globbing;
6103 if ((unsigned char)*p == CTLQUOTEMARK) {
6104 // Note: both inquotes and protect_against_glob only affect whether
6105 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6106 inquotes = ~inquotes;
6108 protect_against_glob = globbing;
6111 if ((unsigned char)*p == CTLESC) {
6115 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6117 if (protect_against_glob) {
6119 * We used to trust glob() and fnmatch() to eat
6120 * superfluous escapes (\z where z has no
6121 * special meaning anyway). But this causes
6122 * bugs such as string of one greek letter rho
6123 * (unicode-encoded as two bytes "cf,81")
6124 * getting encoded as "cf,CTLESC,81"
6125 * and here, converted to "cf,\,81" -
6126 * which does not go well with some flavors
6127 * of fnmatch() in unicode locales
6128 * (for example, glibc <= 2.22).
6130 * Lets add "\" only on the chars which need it.
6131 * Testcases for less obvious chars are shown.
6136 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6137 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6138 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6139 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6140 /* Some libc support [^negate], that's why "^" also needs love */
6141 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6146 } else if (*p == '\\' && !inquotes) {
6147 /* naked back slash */
6148 protect_against_glob = 0;
6151 #if BASH_PATTERN_SUBST
6152 else if (slash_position && p == str + *slash_position) {
6153 /* stop handling globbing */
6155 *slash_position = q - r;
6156 slash_position = NULL;
6159 protect_against_glob = globbing;
6164 if (flag & RMESCAPE_GROW) {
6166 STADJUST(q - r + 1, expdest);
6170 #define pmatch(a, b) !fnmatch((a), (b), 0)
6173 * Prepare a pattern for a expmeta (internal glob(3)) call.
6175 * Returns an stalloced string.
6178 preglob(const char *pattern, int flag)
6180 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6184 * Put a string on the stack.
6187 memtodest(const char *p, size_t len, int syntax, int quotes)
6194 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6197 unsigned char c = *p++;
6199 if (quotes & QUOTES_ESC) {
6200 int n = SIT(c, syntax);
6202 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6209 } else if (!(quotes & QUOTES_KEEPNUL))
6218 strtodest(const char *p, int syntax, int quotes)
6220 size_t len = strlen(p);
6221 memtodest(p, len, syntax, quotes);
6226 * Record the fact that we have to scan this region of the
6227 * string for IFS characters.
6230 recordregion(int start, int end, int nulonly)
6232 struct ifsregion *ifsp;
6234 if (ifslastp == NULL) {
6238 ifsp = ckzalloc(sizeof(*ifsp));
6239 /*ifsp->next = NULL; - ckzalloc did it */
6240 ifslastp->next = ifsp;
6244 ifslastp->begoff = start;
6245 ifslastp->endoff = end;
6246 ifslastp->nulonly = nulonly;
6250 removerecordregions(int endoff)
6252 if (ifslastp == NULL)
6255 if (ifsfirst.endoff > endoff) {
6256 while (ifsfirst.next) {
6257 struct ifsregion *ifsp;
6259 ifsp = ifsfirst.next->next;
6260 free(ifsfirst.next);
6261 ifsfirst.next = ifsp;
6264 if (ifsfirst.begoff > endoff) {
6267 ifslastp = &ifsfirst;
6268 ifsfirst.endoff = endoff;
6273 ifslastp = &ifsfirst;
6274 while (ifslastp->next && ifslastp->next->begoff < endoff)
6275 ifslastp = ifslastp->next;
6276 while (ifslastp->next) {
6277 struct ifsregion *ifsp;
6279 ifsp = ifslastp->next->next;
6280 free(ifslastp->next);
6281 ifslastp->next = ifsp;
6284 if (ifslastp->endoff > endoff)
6285 ifslastp->endoff = endoff;
6289 exptilde(char *startp, char *p, int flags)
6295 int quotes = flags & QUOTES_ESC;
6299 while ((c = *++p) != '\0') {
6306 if (flags & EXP_VARTILDE)
6316 if (*name == '\0') {
6317 home = lookupvar("HOME");
6319 pw = getpwnam(name);
6324 if (!home || !*home)
6327 strtodest(home, SQSYNTAX, quotes);
6335 * Execute a command inside back quotes. If it's a builtin command, we
6336 * want to save its output in a block obtained from malloc. Otherwise
6337 * we fork off a subprocess and get the output of the command via a pipe.
6338 * Should be called with interrupts off.
6340 struct backcmd { /* result of evalbackcmd */
6341 int fd; /* file descriptor to read from */
6342 int nleft; /* number of chars in buffer */
6343 char *buf; /* buffer */
6344 struct job *jp; /* job structure for command */
6347 /* These forward decls are needed to use "eval" code for backticks handling: */
6348 /* flags in argument to evaltree */
6349 #define EV_EXIT 01 /* exit after evaluating tree */
6350 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6351 static int evaltree(union node *, int);
6353 /* An evaltree() which is known to never return.
6354 * Used to use an alias:
6355 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6356 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6358 static ALWAYS_INLINE NORETURN void
6359 evaltreenr(union node *n, int flags)
6362 bb_unreachable(abort());
6366 static void FAST_FUNC
6367 evalbackcmd(union node *n, struct backcmd *result)
6381 ash_msg_and_raise_perror("can't create pipe");
6382 jp = makejob(/*n,*/ 1);
6383 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6389 dup2_or_raise(pip[1], 1);
6392 /* TODO: eflag clearing makes the following not abort:
6393 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6394 * which is what bash does (unless it is in POSIX mode).
6395 * dash deleted "eflag = 0" line in the commit
6396 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6397 * [EVAL] Don't clear eflag in evalbackcmd
6398 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6402 evaltreenr(n, EV_EXIT);
6407 result->fd = pip[0];
6411 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6412 result->fd, result->buf, result->nleft, result->jp));
6416 * Expand stuff in backwards quotes.
6419 expbackq(union node *cmd, int flag)
6427 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6428 struct stackmark smark;
6431 startloc = expdest - (char *)stackblock();
6432 pushstackmark(&smark, startloc);
6433 evalbackcmd(cmd, &in);
6434 popstackmark(&smark);
6441 memtodest(p, i, syntax, flag & QUOTES_ESC);
6445 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6446 TRACE(("expbackq: read returns %d\n", i));
6455 back_exitstatus = waitforjob(in.jp);
6459 /* Eat all trailing newlines */
6461 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6465 if (!(flag & EXP_QUOTED))
6466 recordregion(startloc, dest - (char *)stackblock(), 0);
6467 TRACE(("evalbackq: size:%d:'%.*s'\n",
6468 (int)((dest - (char *)stackblock()) - startloc),
6469 (int)((dest - (char *)stackblock()) - startloc),
6470 stackblock() + startloc));
6473 #if ENABLE_FEATURE_SH_MATH
6475 * Expand arithmetic expression. Backup to start of expression,
6476 * evaluate, place result in (backed up) result, adjust string position.
6488 * This routine is slightly over-complicated for
6489 * efficiency. Next we scan backwards looking for the
6490 * start of arithmetic.
6492 start = stackblock();
6499 while ((unsigned char)*p != CTLARI) {
6503 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6508 esc = esclen(start, p);
6518 removerecordregions(begoff);
6522 if (flag & QUOTES_ESC)
6523 rmescapes(p + 1, 0, NULL);
6525 len = cvtnum(ash_arith(p + 1));
6527 if (!(flag & EXP_QUOTED))
6528 recordregion(begoff, begoff + len, 0);
6532 /* argstr needs it */
6533 static char *evalvar(char *p, int flags);
6536 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6537 * characters to allow for further processing. Otherwise treat
6538 * $@ like $* since no splitting will be performed.
6541 argstr(char *p, int flags)
6543 static const char spclchars[] ALIGN1 = {
6551 #if ENABLE_FEATURE_SH_MATH
6556 const char *reject = spclchars;
6557 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6562 if (!(flags & EXP_VARTILDE)) {
6564 } else if (flags & EXP_VARTILDE2) {
6569 if (flags & EXP_TILDE) {
6572 flags &= ~EXP_TILDE;
6576 p = exptilde(p, q, flags);
6579 startloc = expdest - (char *)stackblock();
6583 length += strcspn(p + length, reject);
6587 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6589 /* c == '=' || c == ':' || c == CTLENDARI */
6595 expdest = stack_nputstr(p, length, expdest);
6596 newloc = expdest - (char *)stackblock();
6597 if (breakall && !inquotes && newloc > startloc) {
6598 recordregion(startloc, newloc, 0);
6609 if (flags & EXP_VARTILDE2) {
6613 flags |= EXP_VARTILDE2;
6618 * sort of a hack - expand tildes in variable
6619 * assignments (after the first '=' and after ':'s).
6628 case CTLENDVAR: /* ??? */
6631 inquotes ^= EXP_QUOTED;
6632 /* "$@" syntax adherence hack */
6633 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6634 p = evalvar(p + 1, flags | inquotes) + 1;
6638 if (flags & QUOTES_ESC) {
6649 * Quoted parameter expansion pattern: remove quote
6650 * unless inside inner quotes or we have a literal
6653 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6654 EXP_QPAT && *p != '\\')
6659 TRACE(("argstr: evalvar('%s')\n", p));
6660 p = evalvar(p, flags | inquotes);
6661 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6664 expbackq(argbackq->n, flags | inquotes);
6665 argbackq = argbackq->next;
6667 #if ENABLE_FEATURE_SH_MATH
6670 expari(flags | inquotes);
6679 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6680 char *pattern, int quotes, int zero)
6689 const char *s = loc2;
6696 match = pmatch(pattern, s);
6701 if (quotes && (unsigned char)*loc == CTLESC)
6710 scanright(char *startp, char *rmesc, char *rmescend,
6711 char *pattern, int quotes, int match_at_start)
6713 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6714 int try2optimize = match_at_start;
6720 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6721 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6722 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6724 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6725 * and on each iteration they go back two/one char until they reach the beginning.
6726 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6728 /* TODO: document in what other circumstances we are called. */
6730 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6733 const char *s = loc2;
6734 if (match_at_start) {
6738 match = pmatch(pattern, s);
6739 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6743 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6745 /* Maybe we can optimize this:
6746 * if pattern ends with unescaped *, we can avoid checking
6747 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6748 * it won't match truncated "raw_value_of_" strings too.
6750 unsigned plen = strlen(pattern);
6751 /* Does it end with "*"? */
6752 if (plen != 0 && pattern[--plen] == '*') {
6753 /* "xxxx*" is not escaped */
6754 /* "xxx\*" is escaped */
6755 /* "xx\\*" is not escaped */
6756 /* "x\\\*" is escaped */
6758 while (plen != 0 && pattern[--plen] == '\\')
6761 break; /* ends with unescaped "*" */
6769 esc = esclen(startp, loc);
6780 static void varunset(const char *, const char *, const char *, int) NORETURN;
6782 varunset(const char *end, const char *var, const char *umsg, int varflags)
6788 msg = "parameter not set";
6790 if ((unsigned char)*end == CTLENDVAR) {
6791 if (varflags & VSNUL)
6797 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6801 subevalvar(char *p, char *varname, int strloc, int subtype,
6802 int startloc, int varflags, int flag)
6804 struct nodelist *saveargbackq = argbackq;
6805 int quotes = flag & QUOTES_ESC;
6808 char *rmesc, *rmescend;
6810 int amount, resetloc;
6812 IF_BASH_PATTERN_SUBST(int workloc;)
6813 IF_BASH_PATTERN_SUBST(int slash_pos;)
6814 IF_BASH_PATTERN_SUBST(char *repl;)
6816 char *(*scan)(char*, char*, char*, char*, int, int);
6818 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6819 // p, varname, strloc, subtype, startloc, varflags, quotes);
6821 #if BASH_PATTERN_SUBST
6822 /* For "${v/pattern/repl}", we must find the delimiter _before_
6823 * argstr() call expands possible variable references in pattern:
6824 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6827 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6828 /* Find '/' and replace with NUL */
6831 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6832 if (*repl == '\0') {
6840 if ((unsigned char)*repl == CTLESC && repl[1])
6846 argstr_flags = EXP_TILDE;
6847 if (subtype != VSASSIGN && subtype != VSQUESTION)
6848 argstr_flags |= (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE);
6849 argstr(p, argstr_flags);
6850 #if BASH_PATTERN_SUBST
6853 slash_pos = expdest - ((char *)stackblock() + strloc);
6854 STPUTC('/', expdest);
6855 argstr(repl + 1, argstr_flags);
6859 STPUTC('\0', expdest);
6860 argbackq = saveargbackq;
6861 startp = (char *)stackblock() + startloc;
6862 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6866 setvar0(varname, startp);
6867 amount = startp - expdest;
6868 STADJUST(amount, expdest);
6872 varunset(p, varname, startp, varflags);
6877 int pos, len, orig_len;
6880 loc = str = stackblock() + strloc;
6882 /* Read POS in ${var:POS:LEN} */
6883 colon = strchr(loc, ':');
6884 if (colon) *colon = '\0';
6885 pos = substr_atoi(loc);
6886 if (colon) *colon = ':';
6888 /* Read LEN in ${var:POS:LEN} */
6889 len = str - startp - 1;
6890 /* *loc != '\0', guaranteed by parser */
6893 /* Adjust the length by the number of escapes */
6894 for (ptr = startp; ptr < (str - 1); ptr++) {
6895 if ((unsigned char)*ptr == CTLESC) {
6902 if (*loc++ == ':') {
6904 len = substr_atoi(loc);
6906 /* Skip POS in ${var:POS:LEN} */
6908 while (*loc && *loc != ':')
6911 len = substr_atoi(loc);
6914 /* ${VAR:$((-n)):l} starts n chars from the end */
6915 pos = orig_len + pos;
6917 if ((unsigned)pos >= orig_len) {
6918 /* apart from obvious ${VAR:999999:l},
6919 * covers ${VAR:$((-9999999)):l} - result is ""
6926 /* ${VAR:N:-M} sets LEN to strlen()-M */
6927 len = (orig_len - pos) + len;
6929 if ((unsigned)len > (orig_len - pos))
6930 len = orig_len - pos;
6932 for (str = startp; pos; str++, pos--) {
6933 if (quotes && (unsigned char)*str == CTLESC)
6936 for (loc = startp; len; len--) {
6937 if (quotes && (unsigned char)*str == CTLESC)
6942 amount = loc - expdest;
6943 STADJUST(amount, expdest);
6946 #endif /* BASH_SUBSTR */
6949 resetloc = expdest - (char *)stackblock();
6951 #if BASH_PATTERN_SUBST
6954 /* We'll comeback here if we grow the stack while handling
6955 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6956 * stack will need rebasing, and we'll need to remove our work
6962 amount = expdest - ((char *)stackblock() + resetloc);
6963 STADJUST(-amount, expdest);
6964 startp = (char *)stackblock() + startloc;
6967 rmescend = (char *)stackblock() + strloc;
6968 //bb_error_msg("str7:'%s'", rmescend);
6970 //TODO: how to handle slash_pos here if string changes (shortens?)
6971 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
6972 if (rmesc != startp) {
6974 startp = (char *)stackblock() + startloc;
6978 str = (char *)stackblock() + strloc;
6980 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6981 * The result is a_\_z_c (not a\_\_z_c)!
6983 * The search pattern and replace string treat backslashes differently!
6984 * "&slash_pos" causes rmescapes() to work differently on the pattern
6985 * and string. It's only used on the first call.
6987 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
6988 rmescapes(str, RMESCAPE_GLOB,
6989 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
6992 #if BASH_PATTERN_SUBST
6993 workloc = expdest - (char *)stackblock();
6994 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6999 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7001 if (slash_pos >= 0) {
7002 repl = str + slash_pos;
7006 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7008 /* If there's no pattern to match, return the expansion unmolested */
7017 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7018 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7020 /* No match, advance */
7021 char *restart_detect = stackblock();
7023 STPUTC(*idx, expdest);
7024 if (quotes && (unsigned char)*idx == CTLESC) {
7027 STPUTC(*idx, expdest);
7029 if (stackblock() != restart_detect)
7034 /* continue; - prone to quadratic behavior, smarter code: */
7037 if (str[0] == '*') {
7038 /* Pattern is "*foo". If "*foo" does not match "long_string",
7039 * it would never match "ong_string" etc, no point in trying.
7046 if (subtype == VSREPLACEALL) {
7048 if (quotes && (unsigned char)*idx == CTLESC)
7057 //bb_error_msg("repl:'%s'", repl);
7058 for (loc = (char*)repl; *loc; loc++) {
7059 char *restart_detect = stackblock();
7060 if (quotes && *loc == '\\') {
7061 STPUTC(CTLESC, expdest);
7064 STPUTC(*loc, expdest);
7065 if (stackblock() != restart_detect)
7070 if (subtype == VSREPLACE) {
7071 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7073 char *restart_detect = stackblock();
7074 STPUTC(*idx, expdest);
7075 if (stackblock() != restart_detect)
7084 /* We've put the replaced text into a buffer at workloc, now
7085 * move it to the right place and adjust the stack.
7087 STPUTC('\0', expdest);
7088 startp = (char *)stackblock() + startloc;
7089 memmove(startp, (char *)stackblock() + workloc, len + 1);
7090 //bb_error_msg("startp:'%s'", startp);
7091 amount = expdest - (startp + len);
7092 STADJUST(-amount, expdest);
7095 #endif /* BASH_PATTERN_SUBST */
7097 subtype -= VSTRIMRIGHT;
7099 if (subtype < 0 || subtype > 7)
7102 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7103 zero = subtype >> 1;
7104 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7105 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7107 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7110 memmove(startp, loc, str - loc);
7111 loc = startp + (str - loc) - 1;
7114 amount = loc - expdest;
7115 STADJUST(amount, expdest);
7121 * Add the value of a specialized variable to the stack string.
7122 * name parameter (examples):
7123 * ash -c 'echo $1' name:'1='
7124 * ash -c 'echo $qwe' name:'qwe='
7125 * ash -c 'echo $$' name:'$='
7126 * ash -c 'echo ${$}' name:'$='
7127 * ash -c 'echo ${$##q}' name:'$=q'
7128 * ash -c 'echo ${#$}' name:'$='
7129 * note: examples with bad shell syntax:
7130 * ash -c 'echo ${#$1}' name:'$=1'
7131 * ash -c 'echo ${#1#}' name:'1=#'
7133 static NOINLINE ssize_t
7134 varvalue(char *name, int varflags, int flags, int *quotedp)
7141 int quoted = *quotedp;
7142 int subtype = varflags & VSTYPE;
7143 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7144 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7147 sep = (flags & EXP_FULL) << CHAR_BIT;
7148 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7158 num = shellparam.nparam;
7166 goto check_1char_name;
7168 expdest = makestrspace(NOPTS, expdest);
7169 for (i = NOPTS - 1; i >= 0; i--) {
7171 USTPUTC(optletters(i), expdest);
7177 /* handles cases similar to ${#$1} */
7178 if (name[2] != '\0')
7179 raise_error_syntax("bad substitution");
7192 sep |= ifsset() ? ifsval()[0] : ' ';
7199 while ((p = *ap++) != NULL) {
7200 len += strtodest(p, syntax, quotes);
7204 memtodest(&sepc, 1, syntax, quotes);
7219 num = atoi(name); /* number(name) fails on ${N#str} etc */
7220 if (num < 0 || num > shellparam.nparam)
7222 p = num ? shellparam.p[num - 1] : arg0;
7225 /* NB: name has form "VAR=..." */
7226 p = lookupvar(name);
7231 len = strtodest(p, syntax, quotes);
7232 #if ENABLE_UNICODE_SUPPORT
7233 if (subtype == VSLENGTH && len > 0) {
7234 reinit_unicode_for_ash();
7235 if (unicode_status == UNICODE_ON) {
7236 STADJUST(-len, expdest);
7238 len = unicode_strlen(p);
7246 STADJUST(-len, expdest);
7251 * Expand a variable, and return a pointer to the next character in the
7255 evalvar(char *p, int flag)
7266 varflags = (unsigned char) *p++;
7267 subtype = varflags & VSTYPE;
7270 raise_error_syntax("bad substitution");
7272 quoted = flag & EXP_QUOTED;
7274 easy = (!quoted || (*var == '@' && shellparam.nparam));
7275 startloc = expdest - (char *)stackblock();
7276 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7279 varlen = varvalue(var, varflags, flag, "ed);
7280 if (varflags & VSNUL)
7283 if (subtype == VSPLUS) {
7284 varlen = -1 - varlen;
7288 if (subtype == VSMINUS) {
7293 flag | EXP_TILDE | EXP_WORD
7300 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7304 subevalvar(p, var, 0, subtype, startloc, varflags,
7305 flag & ~QUOTES_ESC);
7308 * Remove any recorded regions beyond
7311 removerecordregions(startloc);
7315 if (varlen < 0 && uflag)
7316 varunset(p, var, 0, 0);
7318 if (subtype == VSLENGTH) {
7319 cvtnum(varlen > 0 ? varlen : 0);
7323 if (subtype == VSNORMAL) {
7327 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7336 case VSTRIMRIGHTMAX:
7340 #if BASH_PATTERN_SUBST
7352 * Terminate the string and start recording the pattern
7355 STPUTC('\0', expdest);
7356 patloc = expdest - (char *)stackblock();
7357 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7358 startloc, varflags, flag)) {
7359 int amount = expdest - (
7360 (char *)stackblock() + patloc - 1
7362 STADJUST(-amount, expdest);
7364 /* Remove any recorded regions beyond start of variable */
7365 removerecordregions(startloc);
7370 if (subtype != VSNORMAL) { /* skip to end of alternative */
7373 unsigned char c = *p++;
7376 else if (c == CTLBACKQ) {
7378 argbackq = argbackq->next;
7379 } else if (c == CTLVAR) {
7380 if ((*p++ & VSTYPE) != VSNORMAL)
7382 } else if (c == CTLENDVAR) {
7392 * Add a file name to the list.
7395 addfname(const char *name)
7399 sp = stzalloc(sizeof(*sp));
7400 sp->text = sstrdup(name);
7402 exparg.lastp = &sp->next;
7405 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7407 hasmeta(const char *p)
7409 static const char chars[] ALIGN1 = {
7410 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7414 p = strpbrk(p, chars);
7417 switch ((unsigned char) *p) {
7421 if (*p == CTLQUOTEMARK)
7425 if (*p == '\0') /* huh? */
7436 if (!strchr(p + 1, ']')) {
7437 /* It's not a properly closed [] pattern,
7438 * but other metas may follow. Continue checking.
7439 * my[file* _is_ globbed by bash
7440 * and matches filenames like "my[file1".
7456 /* If we want to use glob() from libc... */
7457 #if !ENABLE_ASH_INTERNAL_GLOB
7459 /* Add the result of glob() to the list */
7461 addglob(const glob_t *pglob)
7463 char **p = pglob->gl_pathv;
7470 expandmeta(struct strlist *str /*, int flag*/)
7472 /* TODO - EXP_REDIR */
7482 if (!hasmeta(str->text))
7486 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7487 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7488 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7490 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7491 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7492 // Which means you need to unescape the string, right? Not so fast:
7493 // if there _is_ a file named "file\?" (with backslash), it is returned
7494 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7495 // You DON'T KNOW by looking at the result whether you need to unescape it.
7497 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7498 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7499 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7500 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7501 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7502 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7503 i = glob(p, 0, NULL, &pglob);
7504 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7509 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7510 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7511 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7523 *exparg.lastp = str;
7524 rmescapes(str->text, 0, NULL);
7525 exparg.lastp = &str->next;
7527 default: /* GLOB_NOSPACE */
7530 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7537 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7540 * Do metacharacter (i.e. *, ?, [...]) expansion.
7543 expmeta(char *expdir, char *enddir, char *name)
7559 for (p = name; esc = 0, *p; p += esc + 1) {
7560 if (*p == '*' || *p == '?')
7562 else if (*p == '[') {
7569 if (*q == '/' || *q == '\0')
7579 if (p[esc] == '/') {
7582 start = p + esc + 1;
7586 if (metaflag == 0) { /* we've reached the end of the file name */
7587 if (enddir != expdir)
7595 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7606 } while (p < start);
7608 if (enddir == expdir) {
7610 } else if (enddir == expdir + 1 && *expdir == '/') {
7619 if (enddir != expdir)
7621 if (*endname == 0) {
7634 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7635 if (dp->d_name[0] == '.' && !matchdot)
7637 if (pmatch(start, dp->d_name)) {
7639 strcpy(enddir, dp->d_name);
7642 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7645 expmeta(expdir, p, endname);
7651 endname[-esc - 1] = esc ? '\\' : '/';
7654 static struct strlist *
7655 msort(struct strlist *list, int len)
7657 struct strlist *p, *q = NULL;
7658 struct strlist **lpp;
7666 for (n = half; --n >= 0;) {
7670 q->next = NULL; /* terminate first half of list */
7671 q = msort(list, half); /* sort first half of list */
7672 p = msort(p, len - half); /* sort second half */
7675 #if ENABLE_LOCALE_SUPPORT
7676 if (strcoll(p->text, q->text) < 0)
7678 if (strcmp(p->text, q->text) < 0)
7702 * Sort the results of file name expansion. It calculates the number of
7703 * strings to sort and then calls msort (short for merge sort) to do the
7706 static struct strlist *
7707 expsort(struct strlist *str)
7713 for (sp = str; sp; sp = sp->next)
7715 return msort(str, len);
7719 expandmeta(struct strlist *str /*, int flag*/)
7721 /* TODO - EXP_REDIR */
7725 struct strlist **savelastp;
7731 if (!hasmeta(str->text))
7733 savelastp = exparg.lastp;
7736 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7738 int i = strlen(str->text);
7739 //BUGGY estimation of how long expanded name can be
7740 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7742 expmeta(expdir, expdir, p);
7747 if (exparg.lastp == savelastp) {
7752 *exparg.lastp = str;
7753 rmescapes(str->text, 0, NULL);
7754 exparg.lastp = &str->next;
7756 *exparg.lastp = NULL;
7757 *savelastp = sp = expsort(*savelastp);
7758 while (sp->next != NULL)
7760 exparg.lastp = &sp->next;
7765 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7768 * Perform variable substitution and command substitution on an argument,
7769 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7770 * perform splitting and file name expansion. When arglist is NULL, perform
7771 * here document expansion.
7774 expandarg(union node *arg, struct arglist *arglist, int flag)
7779 argbackq = arg->narg.backquote;
7780 STARTSTACKSTR(expdest);
7781 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7782 argstr(arg->narg.text, flag);
7783 p = _STPUTC('\0', expdest);
7785 if (arglist == NULL) {
7786 /* here document expanded */
7789 p = grabstackstr(p);
7790 TRACE(("expandarg: p:'%s'\n", p));
7791 exparg.lastp = &exparg.list;
7795 if (flag & EXP_FULL) {
7796 ifsbreakup(p, &exparg);
7797 *exparg.lastp = NULL;
7798 exparg.lastp = &exparg.list;
7799 expandmeta(exparg.list /*, flag*/);
7801 sp = stzalloc(sizeof(*sp));
7804 exparg.lastp = &sp->next;
7806 *exparg.lastp = NULL;
7808 *arglist->lastp = exparg.list;
7809 arglist->lastp = exparg.lastp;
7817 * Expand shell variables and backquotes inside a here document.
7820 expandhere(union node *arg, int fd)
7822 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7823 full_write(fd, stackblock(), expdest - (char *)stackblock());
7827 * Returns true if the pattern matches the string.
7830 patmatch(char *pattern, const char *string)
7832 char *p = preglob(pattern, 0);
7833 int r = pmatch(p, string);
7834 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7839 * See if a pattern matches in a case statement.
7842 casematch(union node *pattern, char *val)
7844 struct stackmark smark;
7847 setstackmark(&smark);
7848 argbackq = pattern->narg.backquote;
7849 STARTSTACKSTR(expdest);
7850 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7851 STACKSTRNUL(expdest);
7853 result = patmatch(stackblock(), val);
7854 popstackmark(&smark);
7859 /* ============ find_command */
7863 int (*builtin)(int, char **) FAST_FUNC;
7864 /* unsigned flags; */
7866 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7867 /* "regular" builtins always take precedence over commands,
7868 * regardless of PATH=....%builtin... position */
7869 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7870 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7873 smallint cmdtype; /* CMDxxx */
7876 /* index >= 0 for commands without path (slashes) */
7877 /* (TODO: what exactly does the value mean? PATH position?) */
7878 /* index == -1 for commands with slashes */
7879 /* index == (-2 - applet_no) for NOFORK applets */
7880 const struct builtincmd *cmd;
7881 struct funcnode *func;
7884 /* values of cmdtype */
7885 #define CMDUNKNOWN -1 /* no entry in table for command */
7886 #define CMDNORMAL 0 /* command is an executable program */
7887 #define CMDFUNCTION 1 /* command is a shell function */
7888 #define CMDBUILTIN 2 /* command is a shell builtin */
7890 /* action to find_command() */
7891 #define DO_ERR 0x01 /* prints errors */
7892 #define DO_ABS 0x02 /* checks absolute paths */
7893 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7894 #define DO_ALTPATH 0x08 /* using alternate path */
7895 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7897 static void find_command(char *, struct cmdentry *, int, const char *);
7900 /* ============ Hashing commands */
7903 * When commands are first encountered, they are entered in a hash table.
7904 * This ensures that a full path search will not have to be done for them
7905 * on each invocation.
7907 * We should investigate converting to a linear search, even though that
7908 * would make the command name "hash" a misnomer.
7912 struct tblentry *next; /* next entry in hash chain */
7913 union param param; /* definition of builtin function */
7914 smallint cmdtype; /* CMDxxx */
7915 char rehash; /* if set, cd done since entry created */
7916 char cmdname[1]; /* name of command */
7919 static struct tblentry **cmdtable;
7920 #define INIT_G_cmdtable() do { \
7921 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7924 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7928 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7930 #if ENABLE_FEATURE_SH_STANDALONE
7931 if (applet_no >= 0) {
7932 if (APPLET_IS_NOEXEC(applet_no)) {
7936 popredir(/*drop:*/ 1);
7937 run_noexec_applet_and_exit(applet_no, cmd, argv);
7939 /* re-exec ourselves with the new arguments */
7940 execve(bb_busybox_exec_path, argv, envp);
7941 /* If they called chroot or otherwise made the binary no longer
7942 * executable, fall through */
7949 execve(cmd, argv, envp);
7950 } while (errno == EINTR);
7952 execve(cmd, argv, envp);
7954 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7955 /* Run "cmd" as a shell script:
7956 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7957 * "If the execve() function fails with ENOEXEC, the shell
7958 * shall execute a command equivalent to having a shell invoked
7959 * with the command name as its first operand,
7960 * with any remaining arguments passed to the new shell"
7962 * That is, do not use $SHELL, user's shell, or /bin/sh;
7963 * just call ourselves.
7965 * Note that bash reads ~80 chars of the file, and if it sees
7966 * a zero byte before it sees newline, it doesn't try to
7967 * interpret it, but fails with "cannot execute binary file"
7968 * message and exit code 126. For one, this prevents attempts
7969 * to interpret foreign ELF binaries as shell scripts.
7971 argv[0] = (char*) cmd;
7972 cmd = bb_busybox_exec_path;
7973 /* NB: this is only possible because all callers of shellexec()
7974 * ensure that the argv[-1] slot exists!
7977 argv[0] = (char*) "ash";
7983 * Exec a program. Never returns. If you change this routine, you may
7984 * have to change the find_command routine as well.
7985 * argv[-1] must exist and be writable! See tryexec() for why.
7987 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7988 static void shellexec(char *prog, char **argv, const char *path, int idx)
7994 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7996 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
7997 if (strchr(prog, '/') != NULL
7998 #if ENABLE_FEATURE_SH_STANDALONE
7999 || (applet_no = find_applet_by_name(prog)) >= 0
8002 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8003 if (applet_no >= 0) {
8004 /* We tried execing ourself, but it didn't work.
8005 * Maybe /proc/self/exe doesn't exist?
8014 while ((cmdname = path_advance(&path, prog)) != NULL) {
8015 if (--idx < 0 && pathopt == NULL) {
8016 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8017 if (errno != ENOENT && errno != ENOTDIR)
8024 /* Map to POSIX errors */
8036 exitstatus = exerrno;
8037 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8038 prog, e, suppress_int));
8039 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8044 printentry(struct tblentry *cmdp)
8050 idx = cmdp->param.index;
8053 name = path_advance(&path, cmdp->cmdname);
8055 } while (--idx >= 0);
8056 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8060 * Clear out command entries. The argument specifies the first entry in
8061 * PATH which has changed.
8064 clearcmdentry(int firstchange)
8066 struct tblentry **tblp;
8067 struct tblentry **pp;
8068 struct tblentry *cmdp;
8071 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8073 while ((cmdp = *pp) != NULL) {
8074 if ((cmdp->cmdtype == CMDNORMAL &&
8075 cmdp->param.index >= firstchange)
8076 || (cmdp->cmdtype == CMDBUILTIN &&
8077 builtinloc >= firstchange)
8090 * Locate a command in the command hash table. If "add" is nonzero,
8091 * add the command to the table if it is not already present. The
8092 * variable "lastcmdentry" is set to point to the address of the link
8093 * pointing to the entry, so that delete_cmd_entry can delete the
8096 * Interrupts must be off if called with add != 0.
8098 static struct tblentry **lastcmdentry;
8100 static struct tblentry *
8101 cmdlookup(const char *name, int add)
8103 unsigned int hashval;
8105 struct tblentry *cmdp;
8106 struct tblentry **pp;
8109 hashval = (unsigned char)*p << 4;
8111 hashval += (unsigned char)*p++;
8113 pp = &cmdtable[hashval % CMDTABLESIZE];
8114 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8115 if (strcmp(cmdp->cmdname, name) == 0)
8119 if (add && cmdp == NULL) {
8120 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8122 /* + 1 - already done because
8123 * tblentry::cmdname is char[1] */);
8124 /*cmdp->next = NULL; - ckzalloc did it */
8125 cmdp->cmdtype = CMDUNKNOWN;
8126 strcpy(cmdp->cmdname, name);
8133 * Delete the command entry returned on the last lookup.
8136 delete_cmd_entry(void)
8138 struct tblentry *cmdp;
8141 cmdp = *lastcmdentry;
8142 *lastcmdentry = cmdp->next;
8143 if (cmdp->cmdtype == CMDFUNCTION)
8144 freefunc(cmdp->param.func);
8150 * Add a new command entry, replacing any existing command entry for
8151 * the same name - except special builtins.
8154 addcmdentry(char *name, struct cmdentry *entry)
8156 struct tblentry *cmdp;
8158 cmdp = cmdlookup(name, 1);
8159 if (cmdp->cmdtype == CMDFUNCTION) {
8160 freefunc(cmdp->param.func);
8162 cmdp->cmdtype = entry->cmdtype;
8163 cmdp->param = entry->u;
8167 static int FAST_FUNC
8168 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8170 struct tblentry **pp;
8171 struct tblentry *cmdp;
8173 struct cmdentry entry;
8176 if (nextopt("r") != '\0') {
8181 if (*argptr == NULL) {
8182 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8183 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8184 if (cmdp->cmdtype == CMDNORMAL)
8192 while ((name = *argptr) != NULL) {
8193 cmdp = cmdlookup(name, 0);
8195 && (cmdp->cmdtype == CMDNORMAL
8196 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8200 find_command(name, &entry, DO_ERR, pathval());
8201 if (entry.cmdtype == CMDUNKNOWN)
8209 * Called when a cd is done. Marks all commands so the next time they
8210 * are executed they will be rehashed.
8215 struct tblentry **pp;
8216 struct tblentry *cmdp;
8218 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8219 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8220 if (cmdp->cmdtype == CMDNORMAL
8221 || (cmdp->cmdtype == CMDBUILTIN
8222 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8232 * Fix command hash table when PATH changed.
8233 * Called before PATH is changed. The argument is the new value of PATH;
8234 * pathval() still returns the old value at this point.
8235 * Called with interrupts off.
8237 static void FAST_FUNC
8238 changepath(const char *new)
8246 firstchange = 9999; /* assume no change */
8252 if ((*old == '\0' && *new == ':')
8253 || (*old == ':' && *new == '\0')
8257 old = new; /* ignore subsequent differences */
8261 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8268 if (builtinloc < 0 && idx_bltin >= 0)
8269 builtinloc = idx_bltin; /* zap builtins */
8270 if (builtinloc >= 0 && idx_bltin < 0)
8272 clearcmdentry(firstchange);
8273 builtinloc = idx_bltin;
8309 typedef smallint token_id_t;
8311 /* Nth bit indicates if token marks the end of a list */
8314 /* 0 */ | (1u << TEOF)
8315 /* 1 */ | (0u << TNL)
8316 /* 2 */ | (0u << TREDIR)
8317 /* 3 */ | (0u << TWORD)
8318 /* 4 */ | (0u << TSEMI)
8319 /* 5 */ | (0u << TBACKGND)
8320 /* 6 */ | (0u << TAND)
8321 /* 7 */ | (0u << TOR)
8322 /* 8 */ | (0u << TPIPE)
8323 /* 9 */ | (0u << TLP)
8324 /* 10 */ | (1u << TRP)
8325 /* 11 */ | (1u << TENDCASE)
8326 /* 12 */ | (1u << TENDBQUOTE)
8327 /* 13 */ | (0u << TNOT)
8328 /* 14 */ | (0u << TCASE)
8329 /* 15 */ | (1u << TDO)
8330 /* 16 */ | (1u << TDONE)
8331 /* 17 */ | (1u << TELIF)
8332 /* 18 */ | (1u << TELSE)
8333 /* 19 */ | (1u << TESAC)
8334 /* 20 */ | (1u << TFI)
8335 /* 21 */ | (0u << TFOR)
8337 /* 22 */ | (0u << TFUNCTION)
8339 /* 23 */ | (0u << TIF)
8340 /* 24 */ | (0u << TIN)
8341 /* 25 */ | (1u << TTHEN)
8342 /* 26 */ | (0u << TUNTIL)
8343 /* 27 */ | (0u << TWHILE)
8344 /* 28 */ | (0u << TBEGIN)
8345 /* 29 */ | (1u << TEND)
8346 , /* thus far 29 bits used */
8349 static const char *const tokname_array[] = {
8363 #define KWDOFFSET 13
8364 /* the following are keywords */
8386 /* Wrapper around strcmp for qsort/bsearch/... */
8388 pstrcmp(const void *a, const void *b)
8390 return strcmp((char*)a, *(char**)b);
8393 static const char *const *
8394 findkwd(const char *s)
8396 return bsearch(s, tokname_array + KWDOFFSET,
8397 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8398 sizeof(tokname_array[0]), pstrcmp);
8402 * Locate and print what a word is...
8405 describe_command(char *command, const char *path, int describe_command_verbose)
8407 struct cmdentry entry;
8408 #if ENABLE_ASH_ALIAS
8409 const struct alias *ap;
8412 path = path ? path : pathval();
8414 if (describe_command_verbose) {
8418 /* First look at the keywords */
8419 if (findkwd(command)) {
8420 out1str(describe_command_verbose ? " is a shell keyword" : command);
8424 #if ENABLE_ASH_ALIAS
8425 /* Then look at the aliases */
8426 ap = lookupalias(command, 0);
8428 if (!describe_command_verbose) {
8433 out1fmt(" is an alias for %s", ap->val);
8438 find_command(command, &entry, DO_ABS, path);
8440 switch (entry.cmdtype) {
8442 int j = entry.u.index;
8448 p = path_advance(&path, command);
8452 if (describe_command_verbose) {
8453 out1fmt(" is %s", p);
8461 if (describe_command_verbose) {
8462 out1str(" is a shell function");
8469 if (describe_command_verbose) {
8470 out1fmt(" is a %sshell builtin",
8471 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8472 "special " : nullstr
8480 if (describe_command_verbose) {
8481 out1str(": not found\n");
8490 static int FAST_FUNC
8491 typecmd(int argc UNUSED_PARAM, char **argv)
8497 /* type -p ... ? (we don't bother checking for 'p') */
8498 if (argv[1] && argv[1][0] == '-') {
8503 err |= describe_command(argv[i++], NULL, verbose);
8508 #if ENABLE_ASH_CMDCMD
8509 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8511 parse_command_args(char **argv, const char **path)
8524 if (c == '-' && !*cp) {
8532 *path = bb_default_path;
8535 /* run 'typecmd' for other options */
8544 static int FAST_FUNC
8545 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8553 const char *path = NULL;
8555 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8556 * never reaches this function.
8559 while ((c = nextopt("pvV")) != '\0')
8561 verify |= VERIFY_VERBOSE;
8563 /*verify |= VERIFY_BRIEF*/;
8569 path = bb_default_path;
8571 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8573 if (/*verify && */ cmd)
8574 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8581 /*static int funcblocksize; // size of structures in function */
8582 /*static int funcstringsize; // size of strings in node */
8583 static void *funcblock; /* block to allocate function from */
8584 static char *funcstring_end; /* end of block to allocate strings from */
8586 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8587 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8588 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8589 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8590 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8591 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8592 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8593 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8594 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8595 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8596 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8597 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8598 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8599 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8600 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8601 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8602 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8603 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8604 #if BASH_REDIR_OUTPUT
8605 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8607 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8608 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8609 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8610 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8611 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8612 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8613 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8614 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8615 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8618 static int calcsize(int funcblocksize, union node *n);
8621 sizenodelist(int funcblocksize, struct nodelist *lp)
8624 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8625 funcblocksize = calcsize(funcblocksize, lp->n);
8628 return funcblocksize;
8632 calcsize(int funcblocksize, union node *n)
8635 return funcblocksize;
8636 funcblocksize += nodesize[n->type];
8639 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8640 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8641 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8644 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8649 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8650 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8657 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8658 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8661 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8662 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8663 funcblocksize = calcsize(funcblocksize, n->nif.test);
8666 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8667 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8668 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8671 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8672 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8675 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8676 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8677 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8680 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8681 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8684 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8685 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8686 funcblocksize = calcsize(funcblocksize, n->narg.next);
8689 #if BASH_REDIR_OUTPUT
8696 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8697 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8701 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8702 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8706 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8707 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8710 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8713 return funcblocksize;
8717 nodeckstrdup(char *s)
8719 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8720 return strcpy(funcstring_end, s);
8723 static union node *copynode(union node *);
8725 static struct nodelist *
8726 copynodelist(struct nodelist *lp)
8728 struct nodelist *start;
8729 struct nodelist **lpp;
8734 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8735 (*lpp)->n = copynode(lp->n);
8737 lpp = &(*lpp)->next;
8744 copynode(union node *n)
8751 funcblock = (char *) funcblock + nodesize[n->type];
8755 new->ncmd.redirect = copynode(n->ncmd.redirect);
8756 new->ncmd.args = copynode(n->ncmd.args);
8757 new->ncmd.assign = copynode(n->ncmd.assign);
8758 new->ncmd.linno = n->ncmd.linno;
8761 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8762 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8767 new->nredir.redirect = copynode(n->nredir.redirect);
8768 new->nredir.n = copynode(n->nredir.n);
8769 new->nredir.linno = n->nredir.linno;
8776 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8777 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8780 new->nif.elsepart = copynode(n->nif.elsepart);
8781 new->nif.ifpart = copynode(n->nif.ifpart);
8782 new->nif.test = copynode(n->nif.test);
8785 new->nfor.var = nodeckstrdup(n->nfor.var);
8786 new->nfor.body = copynode(n->nfor.body);
8787 new->nfor.args = copynode(n->nfor.args);
8788 new->nfor.linno = n->nfor.linno;
8791 new->ncase.cases = copynode(n->ncase.cases);
8792 new->ncase.expr = copynode(n->ncase.expr);
8793 new->ncase.linno = n->ncase.linno;
8796 new->nclist.body = copynode(n->nclist.body);
8797 new->nclist.pattern = copynode(n->nclist.pattern);
8798 new->nclist.next = copynode(n->nclist.next);
8801 new->ndefun.body = copynode(n->ndefun.body);
8802 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8803 new->ndefun.linno = n->ndefun.linno;
8806 new->narg.backquote = copynodelist(n->narg.backquote);
8807 new->narg.text = nodeckstrdup(n->narg.text);
8808 new->narg.next = copynode(n->narg.next);
8811 #if BASH_REDIR_OUTPUT
8818 new->nfile.fname = copynode(n->nfile.fname);
8819 new->nfile.fd = n->nfile.fd;
8820 new->nfile.next = copynode(n->nfile.next);
8824 new->ndup.vname = copynode(n->ndup.vname);
8825 new->ndup.dupfd = n->ndup.dupfd;
8826 new->ndup.fd = n->ndup.fd;
8827 new->ndup.next = copynode(n->ndup.next);
8831 new->nhere.doc = copynode(n->nhere.doc);
8832 new->nhere.fd = n->nhere.fd;
8833 new->nhere.next = copynode(n->nhere.next);
8836 new->nnot.com = copynode(n->nnot.com);
8839 new->type = n->type;
8844 * Make a copy of a parse tree.
8846 static struct funcnode *
8847 copyfunc(union node *n)
8852 /*funcstringsize = 0;*/
8853 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8854 f = ckzalloc(blocksize /* + funcstringsize */);
8855 funcblock = (char *) f + offsetof(struct funcnode, n);
8856 funcstring_end = (char *) f + blocksize;
8858 /* f->count = 0; - ckzalloc did it */
8863 * Define a shell function.
8866 defun(union node *func)
8868 struct cmdentry entry;
8871 entry.cmdtype = CMDFUNCTION;
8872 entry.u.func = copyfunc(func);
8873 addcmdentry(func->ndefun.text, &entry);
8877 /* Reasons for skipping commands (see comment on breakcmd routine) */
8878 #define SKIPBREAK (1 << 0)
8879 #define SKIPCONT (1 << 1)
8880 #define SKIPFUNC (1 << 2)
8881 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8882 static int skipcount; /* number of levels to skip */
8883 static int loopnest; /* current loop nesting level */
8884 static int funcline; /* starting line number of current function, or 0 if not in a function */
8886 /* Forward decl way out to parsing code - dotrap needs it */
8887 static int evalstring(char *s, int flags);
8889 /* Called to execute a trap.
8890 * Single callsite - at the end of evaltree().
8891 * If we return non-zero, evaltree raises EXEXIT exception.
8893 * Perhaps we should avoid entering new trap handlers
8894 * while we are executing a trap handler. [is it a TODO?]
8901 uint8_t last_status;
8906 last_status = exitstatus;
8910 TRACE(("dotrap entered\n"));
8911 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8923 /* non-trapped SIGINT is handled separately by raise_interrupt,
8924 * don't upset it by resetting gotsig[SIGINT-1] */
8925 if (sig == SIGINT && !p)
8928 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8934 exitstatus = last_status;
8935 TRACE(("dotrap returns\n"));
8938 /* forward declarations - evaluation is fairly recursive business... */
8939 static int evalloop(union node *, int);
8940 static int evalfor(union node *, int);
8941 static int evalcase(union node *, int);
8942 static int evalsubshell(union node *, int);
8943 static void expredir(union node *);
8944 static int evalpipe(union node *, int);
8945 static int evalcommand(union node *, int);
8946 static int evalbltin(const struct builtincmd *, int, char **, int);
8947 static void prehash(union node *);
8950 * Evaluate a parse tree. The value is left in the global variable
8954 evaltree(union node *n, int flags)
8957 int (*evalfn)(union node *, int);
8961 TRACE(("evaltree(NULL) called\n"));
8964 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8971 out1fmt("Node type = %d\n", n->type);
8976 status = !evaltree(n->nnot.com, EV_TESTED);
8979 errlinno = lineno = n->nredir.linno;
8981 lineno -= funcline - 1;
8982 expredir(n->nredir.redirect);
8983 pushredir(n->nredir.redirect);
8984 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8986 status = evaltree(n->nredir.n, flags & EV_TESTED);
8988 if (n->nredir.redirect)
8989 popredir(/*drop:*/ 0);
8992 evalfn = evalcommand;
8994 if (eflag && !(flags & EV_TESTED))
9006 evalfn = evalsubshell;
9019 #error NAND + 1 != NOR
9021 #if NOR + 1 != NSEMI
9022 #error NOR + 1 != NSEMI
9024 unsigned is_or = n->type - NAND;
9027 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9029 if ((!status) == is_or || evalskip)
9035 status = evalfn(n, flags);
9039 status = evaltree(n->nif.test, EV_TESTED);
9046 if (n->nif.elsepart) {
9047 n = n->nif.elsepart;
9054 /* Not necessary. To test it:
9055 * "false; f() { qwerty; }; echo $?" should print 0.
9059 exitstatus = status;
9063 /* Order of checks below is important:
9064 * signal handlers trigger before exit caused by "set -e".
9068 if (checkexit & status)
9069 raise_exception(EXEXIT);
9070 if (flags & EV_EXIT)
9071 raise_exception(EXEXIT);
9073 TRACE(("leaving evaltree (no interrupts)\n"));
9080 int skip = evalskip;
9087 if (--skipcount <= 0) {
9098 evalloop(union node *n, int flags)
9109 i = evaltree(n->nbinary.ch1, EV_TESTED);
9111 if (skip == SKIPFUNC)
9115 if (n->type != NWHILE)
9119 status = evaltree(n->nbinary.ch2, flags);
9121 } while (!(skip & ~SKIPCONT));
9128 evalfor(union node *n, int flags)
9130 struct arglist arglist;
9133 struct stackmark smark;
9136 errlinno = lineno = n->ncase.linno;
9138 lineno -= funcline - 1;
9140 setstackmark(&smark);
9141 arglist.list = NULL;
9142 arglist.lastp = &arglist.list;
9143 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9144 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9146 *arglist.lastp = NULL;
9150 for (sp = arglist.list; sp; sp = sp->next) {
9151 setvar0(n->nfor.var, sp->text);
9152 status = evaltree(n->nfor.body, flags);
9153 if (skiploop() & ~SKIPCONT)
9157 popstackmark(&smark);
9163 evalcase(union node *n, int flags)
9167 struct arglist arglist;
9168 struct stackmark smark;
9171 errlinno = lineno = n->ncase.linno;
9173 lineno -= funcline - 1;
9175 setstackmark(&smark);
9176 arglist.list = NULL;
9177 arglist.lastp = &arglist.list;
9178 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9179 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9180 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9181 if (casematch(patp, arglist.list->text)) {
9182 /* Ensure body is non-empty as otherwise
9183 * EV_EXIT may prevent us from setting the
9186 if (evalskip == 0 && cp->nclist.body) {
9187 status = evaltree(cp->nclist.body, flags);
9194 popstackmark(&smark);
9200 * Kick off a subshell to evaluate a tree.
9203 evalsubshell(union node *n, int flags)
9206 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9209 errlinno = lineno = n->nredir.linno;
9211 lineno -= funcline - 1;
9213 expredir(n->nredir.redirect);
9214 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9217 if (backgnd == FORK_FG)
9219 jp = makejob(/*n,*/ 1);
9220 if (forkshell(jp, n, backgnd) == 0) {
9225 flags &= ~EV_TESTED;
9227 redirect(n->nredir.redirect, 0);
9228 evaltreenr(n->nredir.n, flags);
9233 if (backgnd == FORK_FG)
9234 status = waitforjob(jp);
9240 * Compute the names of the files in a redirection list.
9242 static void fixredir(union node *, const char *, int);
9244 expredir(union node *n)
9248 for (redir = n; redir; redir = redir->nfile.next) {
9252 fn.lastp = &fn.list;
9253 switch (redir->type) {
9257 #if BASH_REDIR_OUTPUT
9262 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9263 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9264 #if BASH_REDIR_OUTPUT
9268 // By the design of stack allocator, the loop of this kind:
9269 // while true; do while true; do break; done </dev/null; done
9270 // will look like a memory leak: ash plans to free expfname's
9271 // of "/dev/null" as soon as it finishes running the loop
9272 // (in this case, never).
9273 // This "fix" is wrong:
9274 if (redir->nfile.expfname)
9275 stunalloc(redir->nfile.expfname);
9276 // It results in corrupted state of stacked allocations.
9278 redir->nfile.expfname = fn.list->text;
9281 case NTOFD: /* >& */
9282 if (redir->ndup.vname) {
9283 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9284 if (fn.list == NULL)
9285 ash_msg_and_raise_error("redir error");
9286 #if BASH_REDIR_OUTPUT
9287 //FIXME: we used expandarg with different args!
9288 if (!isdigit_str9(fn.list->text)) {
9289 /* >&file, not >&fd */
9290 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9291 ash_msg_and_raise_error("redir error");
9293 goto store_expfname;
9296 fixredir(redir, fn.list->text, 1);
9304 * Evaluate a pipeline. All the processes in the pipeline are children
9305 * of the process creating the pipeline. (This differs from some versions
9306 * of the shell, which make the last process in a pipeline the parent
9310 evalpipe(union node *n, int flags)
9313 struct nodelist *lp;
9319 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9321 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9325 if (n->npipe.pipe_backgnd == 0)
9327 jp = makejob(/*n,*/ pipelen);
9329 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9333 if (pipe(pip) < 0) {
9335 ash_msg_and_raise_perror("can't create pipe");
9338 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9352 evaltreenr(lp->n, flags);
9359 /* Don't want to trigger debugging */
9363 if (n->npipe.pipe_backgnd == 0) {
9364 status = waitforjob(jp);
9365 TRACE(("evalpipe: job done exit status %d\n", status));
9373 * Controls whether the shell is interactive or not.
9376 setinteractive(int on)
9378 static smallint is_interactive;
9380 if (++on == is_interactive)
9382 is_interactive = on;
9386 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9387 if (is_interactive > 1) {
9388 /* Looks like they want an interactive shell */
9389 static smallint did_banner;
9392 /* note: ash and hush share this string */
9393 out1fmt("\n\n%s %s\n"
9394 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9397 "built-in shell (ash)"
9411 setinteractive(iflag);
9413 #if ENABLE_FEATURE_EDITING_VI
9415 line_input_state->flags |= VI_MODE;
9417 line_input_state->flags &= ~VI_MODE;
9419 viflag = 0; /* forcibly keep the option off */
9423 struct localvar_list {
9424 struct localvar_list *next;
9425 struct localvar *lv;
9428 static struct localvar_list *localvar_stack;
9431 * Called after a function returns.
9432 * Interrupts must be off.
9435 poplocalvars(int keep)
9437 struct localvar_list *ll;
9438 struct localvar *lvp, *next;
9442 ll = localvar_stack;
9443 localvar_stack = ll->next;
9448 while ((lvp = next) != NULL) {
9451 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9453 int bits = VSTRFIXED;
9455 if (lvp->flags != VUNSET) {
9456 if (vp->var_text == lvp->text)
9458 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9459 free((char*)lvp->text);
9463 vp->flags |= (lvp->flags & bits);
9466 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9467 unsetvar(vp->var_text);
9468 } else if (vp == NULL) { /* $- saved */
9469 memcpy(optlist, lvp->text, sizeof(optlist));
9470 free((char*)lvp->text);
9472 } else if (lvp->flags == VUNSET) {
9473 vp->flags &= ~(VSTRFIXED|VREADONLY);
9474 unsetvar(vp->var_text);
9477 vp->var_func(var_end(lvp->text));
9478 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9479 free((char*)vp->var_text);
9480 vp->flags = lvp->flags;
9481 vp->var_text = lvp->text;
9489 * Create a new localvar environment.
9491 static struct localvar_list *
9494 struct localvar_list *ll;
9497 ll = ckzalloc(sizeof(*ll));
9498 /*ll->lv = NULL; - zalloc did it */
9499 ll->next = localvar_stack;
9500 localvar_stack = ll;
9507 unwindlocalvars(struct localvar_list *stop)
9509 while (localvar_stack != stop)
9514 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9516 volatile struct shparam saveparam;
9517 struct jmploc *volatile savehandler;
9518 struct jmploc jmploc;
9522 saveparam = shellparam;
9523 savefuncline = funcline;
9524 savehandler = exception_handler;
9525 e = setjmp(jmploc.loc);
9530 exception_handler = &jmploc;
9531 shellparam.malloced = 0;
9533 funcline = func->n.ndefun.linno;
9535 shellparam.nparam = argc - 1;
9536 shellparam.p = argv + 1;
9537 #if ENABLE_ASH_GETOPTS
9538 shellparam.optind = 1;
9539 shellparam.optoff = -1;
9542 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9546 funcline = savefuncline;
9548 freeparam(&shellparam);
9549 shellparam = saveparam;
9550 exception_handler = savehandler;
9552 evalskip &= ~SKIPFUNC;
9557 * Make a variable a local variable. When a variable is made local, it's
9558 * value and flags are saved in a localvar structure. The saved values
9559 * will be restored when the shell function returns. We handle the name
9560 * "-" as a special case: it makes changes to "set +-options" local
9561 * (options will be restored on return from the function).
9566 struct localvar *lvp;
9569 char *eq = strchr(name, '=');
9572 /* Cater for duplicate "local". Examples:
9573 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9574 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9576 lvp = localvar_stack->lv;
9578 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9582 * it's a duplicate "local VAR" declaration, do nothing
9589 lvp = ckzalloc(sizeof(*lvp));
9590 if (LONE_DASH(name)) {
9592 p = ckmalloc(sizeof(optlist));
9593 lvp->text = memcpy(p, optlist, sizeof(optlist));
9596 vpp = hashvar(name);
9597 vp = *findvar(vpp, name);
9599 /* variable did not exist yet */
9601 vp = setvareq(name, VSTRFIXED);
9603 vp = setvar(name, NULL, VSTRFIXED);
9604 lvp->flags = VUNSET;
9606 lvp->text = vp->var_text;
9607 lvp->flags = vp->flags;
9608 /* make sure neither "struct var" nor string gets freed
9609 * during (un)setting:
9611 vp->flags |= VSTRFIXED|VTEXTFIXED;
9615 /* "local VAR" unsets VAR: */
9616 setvar0(name, NULL);
9620 lvp->next = localvar_stack->lv;
9621 localvar_stack->lv = lvp;
9627 * The "local" command.
9629 static int FAST_FUNC
9630 localcmd(int argc UNUSED_PARAM, char **argv)
9634 if (!localvar_stack)
9635 ash_msg_and_raise_error("not in a function");
9638 while ((name = *argv++) != NULL) {
9644 static int FAST_FUNC
9645 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9650 static int FAST_FUNC
9651 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9656 static int FAST_FUNC
9657 execcmd(int argc UNUSED_PARAM, char **argv)
9660 while (nextopt("a:") != '\0')
9661 /* nextopt() sets optionarg to "-a ARGV0" */;
9667 iflag = 0; /* exit on error */
9670 /* We should set up signals for "exec CMD"
9671 * the same way as for "CMD" without "exec".
9672 * But optschanged->setinteractive->setsignal
9673 * still thought we are a root shell. Therefore, for example,
9674 * SIGQUIT is still set to IGN. Fix it:
9678 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9679 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9680 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9684 argv[0] = optionarg;
9685 shellexec(prog, argv, pathval(), 0);
9692 * The return command.
9694 static int FAST_FUNC
9695 returncmd(int argc UNUSED_PARAM, char **argv)
9698 * If called outside a function, do what ksh does;
9699 * skip the rest of the file.
9701 evalskip = SKIPFUNC;
9702 return argv[1] ? number(argv[1]) : exitstatus;
9705 /* Forward declarations for builtintab[] */
9706 static int breakcmd(int, char **) FAST_FUNC;
9707 static int dotcmd(int, char **) FAST_FUNC;
9708 static int evalcmd(int, char **, int) FAST_FUNC;
9709 static int exitcmd(int, char **) FAST_FUNC;
9710 static int exportcmd(int, char **) FAST_FUNC;
9711 #if ENABLE_ASH_GETOPTS
9712 static int getoptscmd(int, char **) FAST_FUNC;
9715 static int helpcmd(int, char **) FAST_FUNC;
9718 static int historycmd(int, char **) FAST_FUNC;
9720 #if ENABLE_FEATURE_SH_MATH
9721 static int letcmd(int, char **) FAST_FUNC;
9723 static int readcmd(int, char **) FAST_FUNC;
9724 static int setcmd(int, char **) FAST_FUNC;
9725 static int shiftcmd(int, char **) FAST_FUNC;
9726 static int timescmd(int, char **) FAST_FUNC;
9727 static int trapcmd(int, char **) FAST_FUNC;
9728 static int umaskcmd(int, char **) FAST_FUNC;
9729 static int unsetcmd(int, char **) FAST_FUNC;
9730 static int ulimitcmd(int, char **) FAST_FUNC;
9732 #define BUILTIN_NOSPEC "0"
9733 #define BUILTIN_SPECIAL "1"
9734 #define BUILTIN_REGULAR "2"
9735 #define BUILTIN_SPEC_REG "3"
9736 #define BUILTIN_ASSIGN "4"
9737 #define BUILTIN_SPEC_ASSG "5"
9738 #define BUILTIN_REG_ASSG "6"
9739 #define BUILTIN_SPEC_REG_ASSG "7"
9741 /* Stubs for calling non-FAST_FUNC's */
9743 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9745 #if ENABLE_ASH_PRINTF
9746 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9748 #if ENABLE_ASH_TEST || BASH_TEST2
9749 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9752 /* Keep these in proper order since it is searched via bsearch() */
9753 static const struct builtincmd builtintab[] = {
9754 { BUILTIN_SPEC_REG "." , dotcmd },
9755 { BUILTIN_SPEC_REG ":" , truecmd },
9757 { BUILTIN_REGULAR "[" , testcmd },
9760 { BUILTIN_REGULAR "[[" , testcmd },
9762 #if ENABLE_ASH_ALIAS
9763 { BUILTIN_REG_ASSG "alias" , aliascmd },
9766 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9768 { BUILTIN_SPEC_REG "break" , breakcmd },
9769 { BUILTIN_REGULAR "cd" , cdcmd },
9770 { BUILTIN_NOSPEC "chdir" , cdcmd },
9771 #if ENABLE_ASH_CMDCMD
9772 { BUILTIN_REGULAR "command" , commandcmd },
9774 { BUILTIN_SPEC_REG "continue", breakcmd },
9776 { BUILTIN_REGULAR "echo" , echocmd },
9778 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9779 { BUILTIN_SPEC_REG "exec" , execcmd },
9780 { BUILTIN_SPEC_REG "exit" , exitcmd },
9781 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9782 { BUILTIN_REGULAR "false" , falsecmd },
9784 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9786 #if ENABLE_ASH_GETOPTS
9787 { BUILTIN_REGULAR "getopts" , getoptscmd },
9789 { BUILTIN_NOSPEC "hash" , hashcmd },
9791 { BUILTIN_NOSPEC "help" , helpcmd },
9794 { BUILTIN_NOSPEC "history" , historycmd },
9797 { BUILTIN_REGULAR "jobs" , jobscmd },
9798 { BUILTIN_REGULAR "kill" , killcmd },
9800 #if ENABLE_FEATURE_SH_MATH
9801 { BUILTIN_NOSPEC "let" , letcmd },
9803 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9804 #if ENABLE_ASH_PRINTF
9805 { BUILTIN_REGULAR "printf" , printfcmd },
9807 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9808 { BUILTIN_REGULAR "read" , readcmd },
9809 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9810 { BUILTIN_SPEC_REG "return" , returncmd },
9811 { BUILTIN_SPEC_REG "set" , setcmd },
9812 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9814 { BUILTIN_SPEC_REG "source" , dotcmd },
9817 { BUILTIN_REGULAR "test" , testcmd },
9819 { BUILTIN_SPEC_REG "times" , timescmd },
9820 { BUILTIN_SPEC_REG "trap" , trapcmd },
9821 { BUILTIN_REGULAR "true" , truecmd },
9822 { BUILTIN_NOSPEC "type" , typecmd },
9823 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9824 { BUILTIN_REGULAR "umask" , umaskcmd },
9825 #if ENABLE_ASH_ALIAS
9826 { BUILTIN_REGULAR "unalias" , unaliascmd },
9828 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9829 { BUILTIN_REGULAR "wait" , waitcmd },
9832 /* Should match the above table! */
9833 #define COMMANDCMD (builtintab + \
9835 /* [ */ 1 * ENABLE_ASH_TEST + \
9836 /* [[ */ 1 * BASH_TEST2 + \
9837 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9838 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9839 /* break cd cddir */ 3)
9840 #define EVALCMD (COMMANDCMD + \
9841 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9842 /* continue */ 1 + \
9843 /* echo */ 1 * ENABLE_ASH_ECHO + \
9845 #define EXECCMD (EVALCMD + \
9849 * Search the table of builtin commands.
9852 pstrcmp1(const void *a, const void *b)
9854 return strcmp((char*)a, *(char**)b + 1);
9856 static struct builtincmd *
9857 find_builtin(const char *name)
9859 struct builtincmd *bp;
9862 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9869 * Execute a simple command.
9872 isassignment(const char *p)
9874 const char *q = endofname(p);
9879 static int FAST_FUNC
9880 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9882 /* Preserve exitstatus of a previous possible redirection
9883 * as POSIX mandates */
9884 return back_exitstatus;
9887 evalcommand(union node *cmd, int flags)
9889 static const struct builtincmd null_bltin = {
9890 "\0\0", bltincmd /* why three NULs? */
9892 struct localvar_list *localvar_stop;
9893 struct redirtab *redir_stop;
9894 struct stackmark smark;
9896 struct arglist arglist;
9897 struct arglist varlist;
9900 const struct strlist *sp;
9901 struct cmdentry cmdentry;
9908 smallint cmd_is_exec;
9910 errlinno = lineno = cmd->ncmd.linno;
9912 lineno -= funcline - 1;
9914 /* First expand the arguments. */
9915 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9916 setstackmark(&smark);
9917 localvar_stop = pushlocalvars();
9918 back_exitstatus = 0;
9920 cmdentry.cmdtype = CMDBUILTIN;
9921 cmdentry.u.cmd = &null_bltin;
9922 varlist.lastp = &varlist.list;
9923 *varlist.lastp = NULL;
9924 arglist.lastp = &arglist.list;
9925 *arglist.lastp = NULL;
9928 if (cmd->ncmd.args) {
9929 struct builtincmd *bcmd;
9930 smallint pseudovarflag;
9932 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9933 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9935 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9936 struct strlist **spp;
9938 spp = arglist.lastp;
9939 if (pseudovarflag && isassignment(argp->narg.text))
9940 expandarg(argp, &arglist, EXP_VARTILDE);
9942 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9944 for (sp = *spp; sp; sp = sp->next)
9949 /* Reserve one extra spot at the front for shellexec. */
9950 nargv = stalloc(sizeof(char *) * (argc + 2));
9952 for (sp = arglist.list; sp; sp = sp->next) {
9953 TRACE(("evalcommand arg: %s\n", sp->text));
9954 *nargv++ = sp->text;
9959 if (iflag && funcline == 0 && argc > 0)
9960 lastarg = nargv[-1];
9962 expredir(cmd->ncmd.redirect);
9963 redir_stop = pushredir(cmd->ncmd.redirect);
9965 if (BASH_XTRACEFD && xflag) {
9966 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
9967 * we do not emulate this. We only use its value.
9969 const char *xtracefd = lookupvar("BASH_XTRACEFD");
9970 if (xtracefd && is_number(xtracefd))
9971 preverrout_fd = atoi(xtracefd);
9974 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9976 path = vpath.var_text;
9977 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9978 struct strlist **spp;
9981 spp = varlist.lastp;
9982 expandarg(argp, &varlist, EXP_VARTILDE);
9984 mklocal((*spp)->text);
9987 * Modify the command lookup path, if a PATH= assignment
9991 if (varcmp(p, path) == 0)
9995 /* Print the command if xflag is set. */
9997 const char *pfx = "";
9999 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10003 char *varval = sp->text;
10004 char *eq = strchrnul(varval, '=');
10007 fdprintf(preverrout_fd, "%s%.*s%s",
10009 (int)(eq - varval), varval,
10010 maybe_single_quote(eq)
10018 fdprintf(preverrout_fd, "%s%s",
10020 /* always quote if matches reserved word: */
10022 ? single_quote(sp->text)
10023 : maybe_single_quote(sp->text)
10028 safe_write(preverrout_fd, "\n", 1);
10034 /* Now locate the command. */
10036 int cmd_flag = DO_ERR;
10037 #if ENABLE_ASH_CMDCMD
10038 const char *oldpath = path + 5;
10042 find_command(argv[0], &cmdentry, cmd_flag, path);
10043 if (cmdentry.cmdtype == CMDUNKNOWN) {
10044 flush_stdout_stderr();
10049 /* implement bltin and command here */
10050 if (cmdentry.cmdtype != CMDBUILTIN)
10053 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10054 if (cmdentry.u.cmd == EXECCMD)
10056 #if ENABLE_ASH_CMDCMD
10057 if (cmdentry.u.cmd == COMMANDCMD) {
10059 nargv = parse_command_args(argv, &path);
10062 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10063 * nargv => "PROG". path is updated if -p.
10065 argc -= nargv - argv;
10067 cmd_flag |= DO_NOFUNC;
10076 exitstatus = status;
10078 /* We have a redirection error. */
10080 raise_exception(EXERROR);
10085 /* Execute the command. */
10086 switch (cmdentry.cmdtype) {
10089 #if ENABLE_FEATURE_SH_STANDALONE \
10090 && ENABLE_FEATURE_SH_NOFORK \
10092 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10093 * around run_nofork_applet() call.
10094 * (2) Should this check also be done in forkshell()?
10095 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10097 /* find_command() encodes applet_no as (-2 - applet_no) */
10098 int applet_no = (- cmdentry.u.index - 2);
10099 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10103 sv_environ = environ;
10104 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10106 * Run <applet>_main().
10107 * Signals (^C) can't interrupt here.
10108 * Otherwise we can mangle stdio or malloc internal state.
10109 * This makes applets which can run for a long time
10110 * and/or wait for user input ineligible for NOFORK:
10111 * for example, "yes" or "rm" (rm -i waits for input).
10113 status = run_nofork_applet(applet_no, argv);
10114 environ = sv_environ;
10116 * Try enabling NOFORK for "yes" applet.
10117 * ^C _will_ stop it (write returns EINTR),
10118 * but this causes stdout FILE to be stuck
10119 * and needing clearerr(). What if other applets
10120 * also can get EINTRs? Do we need to switch
10121 * our signals to SA_RESTART?
10123 /*clearerr(stdout);*/
10128 /* Can we avoid forking? For example, very last command
10129 * in a script or a subshell does not need forking,
10130 * we can just exec it.
10132 if (!(flags & EV_EXIT) || may_have_traps) {
10133 /* No, forking off a child is necessary */
10136 jp = makejob(/*cmd,*/ 1);
10137 if (forkshell(jp, cmd, FORK_FG) != 0) {
10139 status = waitforjob(jp);
10141 TRACE(("forked child exited with %d\n", status));
10146 /* fall through to exec'ing external program */
10148 listsetvar(varlist.list, VEXPORT|VSTACK);
10149 shellexec(argv[0], argv, path, cmdentry.u.index);
10153 if (spclbltin > 0 || argc == 0) {
10155 if (cmd_is_exec && argc > 1)
10156 listsetvar(varlist.list, VEXPORT);
10159 /* Tight loop with builtins only:
10160 * "while kill -0 $child; do true; done"
10161 * will never exit even if $child died, unless we do this
10162 * to reap the zombie and make kill detect that it's gone: */
10163 dowait(DOWAIT_NONBLOCK, NULL);
10165 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10166 if (exception_type == EXERROR && spclbltin <= 0) {
10171 longjmp(exception_handler->loc, 1);
10177 /* See above for the rationale */
10178 dowait(DOWAIT_NONBLOCK, NULL);
10179 if (evalfun(cmdentry.u.func, argc, argv, flags))
10182 status = exitstatus;
10187 if (cmd->ncmd.redirect)
10188 popredir(/*drop:*/ cmd_is_exec);
10189 unwindredir(redir_stop);
10190 unwindlocalvars(localvar_stop);
10192 /* dsl: I think this is intended to be used to support
10193 * '_' in 'vi' command mode during line editing...
10194 * However I implemented that within libedit itself.
10196 setvar0("_", lastarg);
10198 popstackmark(&smark);
10204 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10206 char *volatile savecmdname;
10207 struct jmploc *volatile savehandler;
10208 struct jmploc jmploc;
10212 savecmdname = commandname;
10213 savehandler = exception_handler;
10214 i = setjmp(jmploc.loc);
10217 exception_handler = &jmploc;
10218 commandname = argv[0];
10220 optptr = NULL; /* initialize nextopt */
10221 if (cmd == EVALCMD)
10222 status = evalcmd(argc, argv, flags);
10224 status = (*cmd->builtin)(argc, argv);
10225 flush_stdout_stderr();
10226 status |= ferror(stdout);
10227 exitstatus = status;
10230 commandname = savecmdname;
10231 exception_handler = savehandler;
10237 goodname(const char *p)
10239 return endofname(p)[0] == '\0';
10244 * Search for a command. This is called before we fork so that the
10245 * location of the command will be available in the parent as well as
10246 * the child. The check for "goodname" is an overly conservative
10247 * check that the name will not be subject to expansion.
10250 prehash(union node *n)
10252 struct cmdentry entry;
10254 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10255 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10259 /* ============ Builtin commands
10261 * Builtin commands whose functions are closely tied to evaluation
10262 * are implemented here.
10266 * Handle break and continue commands. Break, continue, and return are
10267 * all handled by setting the evalskip flag. The evaluation routines
10268 * above all check this flag, and if it is set they start skipping
10269 * commands rather than executing them. The variable skipcount is
10270 * the number of loops to break/continue, or the number of function
10271 * levels to return. (The latter is always 1.) It should probably
10272 * be an error to break out of more loops than exist, but it isn't
10273 * in the standard shell so we don't make it one here.
10275 static int FAST_FUNC
10276 breakcmd(int argc UNUSED_PARAM, char **argv)
10278 int n = argv[1] ? number(argv[1]) : 1;
10281 ash_msg_and_raise_error(msg_illnum, argv[1]);
10285 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10293 * This implements the input routines used by the parser.
10297 INPUT_PUSH_FILE = 1,
10298 INPUT_NOFILE_OK = 2,
10301 static smallint checkkwd;
10302 /* values of checkkwd variable */
10303 #define CHKALIAS 0x1
10306 #define CHKEOFMARK 0x8
10309 * Push a string back onto the input at this current parsefile level.
10310 * We handle aliases this way.
10312 #if !ENABLE_ASH_ALIAS
10313 #define pushstring(s, ap) pushstring(s)
10316 pushstring(char *s, struct alias *ap)
10318 struct strpush *sp;
10323 if (g_parsefile->strpush) {
10324 sp = ckzalloc(sizeof(*sp));
10325 sp->prev = g_parsefile->strpush;
10327 sp = &(g_parsefile->basestrpush);
10329 g_parsefile->strpush = sp;
10330 sp->prev_string = g_parsefile->next_to_pgetc;
10331 sp->prev_left_in_line = g_parsefile->left_in_line;
10332 sp->unget = g_parsefile->unget;
10333 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10334 #if ENABLE_ASH_ALIAS
10337 ap->flag |= ALIASINUSE;
10341 g_parsefile->next_to_pgetc = s;
10342 g_parsefile->left_in_line = len;
10343 g_parsefile->unget = 0;
10350 struct strpush *sp = g_parsefile->strpush;
10353 #if ENABLE_ASH_ALIAS
10355 if (g_parsefile->next_to_pgetc[-1] == ' '
10356 || g_parsefile->next_to_pgetc[-1] == '\t'
10358 checkkwd |= CHKALIAS;
10360 if (sp->string != sp->ap->val) {
10363 sp->ap->flag &= ~ALIASINUSE;
10364 if (sp->ap->flag & ALIASDEAD) {
10365 unalias(sp->ap->name);
10369 g_parsefile->next_to_pgetc = sp->prev_string;
10370 g_parsefile->left_in_line = sp->prev_left_in_line;
10371 g_parsefile->unget = sp->unget;
10372 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10373 g_parsefile->strpush = sp->prev;
10374 if (sp != &(g_parsefile->basestrpush))
10383 char *buf = g_parsefile->buf;
10385 g_parsefile->next_to_pgetc = buf;
10386 #if ENABLE_FEATURE_EDITING
10388 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10389 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10391 # if ENABLE_ASH_IDLE_TIMEOUT
10394 const char *tmout_var = lookupvar("TMOUT");
10396 timeout = atoi(tmout_var) * 1000;
10401 line_input_state->timeout = timeout;
10403 # if ENABLE_FEATURE_TAB_COMPLETION
10404 line_input_state->path_lookup = pathval();
10406 reinit_unicode_for_ash();
10407 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10409 /* ^C pressed, "convert" to SIGINT */
10410 write(STDOUT_FILENO, "^C", 2);
10411 if (trap[SIGINT]) {
10417 exitstatus = 128 + SIGINT;
10423 /* Ctrl+D pressed */
10426 # if ENABLE_ASH_IDLE_TIMEOUT
10427 else if (errno == EAGAIN && timeout > 0) {
10428 puts("\007timed out waiting for input: auto-logout");
10435 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10438 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10440 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10441 int flags = fcntl(0, F_GETFL);
10442 if (flags >= 0 && (flags & O_NONBLOCK)) {
10443 flags &= ~O_NONBLOCK;
10444 if (fcntl(0, F_SETFL, flags) >= 0) {
10445 out2str("sh: turning off NDELAY mode\n");
10456 * Refill the input buffer and return the next input character:
10458 * 1) If a string was pushed back on the input, pop it;
10459 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10460 * or we are reading from a string so we can't refill the buffer,
10462 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10463 * 4) Process input up to the next newline, deleting nul characters.
10465 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10466 #define pgetc_debug(...) ((void)0)
10467 static int pgetc(void);
10474 if (g_parsefile->strpush) {
10475 #if ENABLE_ASH_ALIAS
10476 if (g_parsefile->left_in_line == -1
10477 && g_parsefile->strpush->ap
10478 && g_parsefile->next_to_pgetc[-1] != ' '
10479 && g_parsefile->next_to_pgetc[-1] != '\t'
10481 pgetc_debug("preadbuffer PEOA");
10488 /* on both branches above g_parsefile->left_in_line < 0.
10489 * "pgetc" needs refilling.
10492 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10493 * pungetc() may increment it a few times.
10494 * Assuming it won't increment it to less than -90.
10496 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10497 pgetc_debug("preadbuffer PEOF1");
10498 /* even in failure keep left_in_line and next_to_pgetc
10499 * in lock step, for correct multi-layer pungetc.
10500 * left_in_line was decremented before preadbuffer(),
10501 * must inc next_to_pgetc: */
10502 g_parsefile->next_to_pgetc++;
10506 more = g_parsefile->left_in_buffer;
10508 flush_stdout_stderr();
10512 /* don't try reading again */
10513 g_parsefile->left_in_line = -99;
10514 pgetc_debug("preadbuffer PEOF2");
10515 g_parsefile->next_to_pgetc++;
10520 /* Find out where's the end of line.
10521 * Set g_parsefile->left_in_line
10522 * and g_parsefile->left_in_buffer acordingly.
10523 * NUL chars are deleted.
10525 q = g_parsefile->next_to_pgetc;
10533 memmove(q, q + 1, more);
10537 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10543 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10544 if (g_parsefile->left_in_line < 0)
10549 g_parsefile->left_in_buffer = more;
10554 out2str(g_parsefile->next_to_pgetc);
10558 pgetc_debug("preadbuffer at %d:%p'%s'",
10559 g_parsefile->left_in_line,
10560 g_parsefile->next_to_pgetc,
10561 g_parsefile->next_to_pgetc);
10562 return (unsigned char)*g_parsefile->next_to_pgetc++;
10568 g_parsefile->linno++;
10569 setprompt_if(doprompt, 2);
10574 g_parsefile->linno++;
10575 needprompt = doprompt;
10583 pgetc_debug("pgetc at %d:%p'%s'",
10584 g_parsefile->left_in_line,
10585 g_parsefile->next_to_pgetc,
10586 g_parsefile->next_to_pgetc);
10587 if (g_parsefile->unget)
10588 return g_parsefile->lastc[--g_parsefile->unget];
10590 if (--g_parsefile->left_in_line >= 0)
10591 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10595 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10596 g_parsefile->lastc[0] = c;
10601 #if ENABLE_ASH_ALIAS
10603 pgetc_without_PEOA(void)
10607 pgetc_debug("pgetc at %d:%p'%s'",
10608 g_parsefile->left_in_line,
10609 g_parsefile->next_to_pgetc,
10610 g_parsefile->next_to_pgetc);
10612 } while (c == PEOA);
10616 # define pgetc_without_PEOA() pgetc()
10620 * Undo a call to pgetc. Only two characters may be pushed back.
10621 * PEOF may be pushed back.
10626 g_parsefile->unget++;
10629 /* This one eats backslash+newline */
10635 while ((c = pgetc()) == '\\') {
10636 if (pgetc() != '\n') {
10648 * To handle the "." command, a stack of input files is used. Pushfile
10649 * adds a new entry to the stack and popfile restores the previous level.
10654 struct parsefile *pf;
10656 pf = ckzalloc(sizeof(*pf));
10657 pf->prev = g_parsefile;
10659 /*pf->strpush = NULL; - ckzalloc did it */
10660 /*pf->basestrpush.prev = NULL;*/
10668 struct parsefile *pf = g_parsefile;
10674 if (pf->pf_fd >= 0)
10677 while (pf->strpush)
10679 g_parsefile = pf->prev;
10685 * Return to top level.
10690 while (g_parsefile != &basepf)
10695 * Close the file(s) that the shell is reading commands from. Called
10696 * after a fork is done.
10702 if (g_parsefile->pf_fd > 0) {
10703 close(g_parsefile->pf_fd);
10704 g_parsefile->pf_fd = 0;
10709 * Like setinputfile, but takes an open file descriptor. Call this with
10713 setinputfd(int fd, int push)
10717 g_parsefile->buf = NULL;
10719 g_parsefile->pf_fd = fd;
10720 if (g_parsefile->buf == NULL)
10721 g_parsefile->buf = ckmalloc(IBUFSIZ);
10722 g_parsefile->left_in_buffer = 0;
10723 g_parsefile->left_in_line = 0;
10724 g_parsefile->linno = 1;
10728 * Set the input to take input from a file. If push is set, push the
10729 * old input onto the stack first.
10732 setinputfile(const char *fname, int flags)
10737 fd = open(fname, O_RDONLY);
10739 if (flags & INPUT_NOFILE_OK)
10742 ash_msg_and_raise_perror("can't open '%s'", fname);
10747 close_on_exec_on(fd);
10748 setinputfd(fd, flags & INPUT_PUSH_FILE);
10755 * Like setinputfile, but takes input from a string.
10758 setinputstring(char *string)
10762 g_parsefile->next_to_pgetc = string;
10763 g_parsefile->left_in_line = strlen(string);
10764 g_parsefile->buf = NULL;
10765 g_parsefile->linno = 1;
10771 * Routines to check for mail.
10774 #if ENABLE_ASH_MAIL
10776 /* Hash of mtimes of mailboxes */
10777 static unsigned mailtime_hash;
10778 /* Set if MAIL or MAILPATH is changed. */
10779 static smallint mail_var_path_changed;
10782 * Print appropriate message(s) if mail has arrived.
10783 * If mail_var_path_changed is set,
10784 * then the value of MAIL has mail_var_path_changed,
10785 * so we just update the values.
10794 struct stackmark smark;
10797 setstackmark(&smark);
10798 mpath = mpathset() ? mpathval() : mailval();
10801 p = path_advance(&mpath, nullstr);
10806 for (q = p; *q; q++)
10812 q[-1] = '\0'; /* delete trailing '/' */
10813 if (stat(p, &statb) < 0) {
10816 /* Very simplistic "hash": just a sum of all mtimes */
10817 new_hash += (unsigned)statb.st_mtime;
10819 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10820 if (mailtime_hash != 0)
10821 out2str("you have mail\n");
10822 mailtime_hash = new_hash;
10824 mail_var_path_changed = 0;
10825 popstackmark(&smark);
10828 static void FAST_FUNC
10829 changemail(const char *val UNUSED_PARAM)
10831 mail_var_path_changed = 1;
10834 #endif /* ASH_MAIL */
10837 /* ============ ??? */
10840 * Set the shell parameters.
10843 setparam(char **argv)
10849 for (nparam = 0; argv[nparam]; nparam++)
10851 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10853 *ap++ = ckstrdup(*argv++);
10856 freeparam(&shellparam);
10857 shellparam.malloced = 1;
10858 shellparam.nparam = nparam;
10859 shellparam.p = newparam;
10860 #if ENABLE_ASH_GETOPTS
10861 shellparam.optind = 1;
10862 shellparam.optoff = -1;
10867 * Process shell options. The global variable argptr contains a pointer
10868 * to the argument list; we advance it past the options.
10870 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10871 * For a non-interactive shell, an error condition encountered
10872 * by a special built-in ... shall cause the shell to write a diagnostic message
10873 * to standard error and exit as shown in the following table:
10874 * Error Special Built-In
10876 * Utility syntax error (option or operand error) Shall exit
10878 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10879 * we see that bash does not do that (set "finishes" with error code 1 instead,
10880 * and shell continues), and people rely on this behavior!
10882 * set -o barfoo 2>/dev/null
10885 * Oh well. Let's mimic that.
10888 plus_minus_o(char *name, int val)
10893 for (i = 0; i < NOPTS; i++) {
10894 if (strcmp(name, optnames(i)) == 0) {
10899 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10902 for (i = 0; i < NOPTS; i++) {
10904 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10906 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10912 setoption(int flag, int val)
10916 for (i = 0; i < NOPTS; i++) {
10917 if (optletters(i) == flag) {
10922 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10926 options(int cmdline, int *login_sh)
10934 while ((p = *argptr) != NULL) {
10936 if (c != '-' && c != '+')
10939 val = 0; /* val = 0 if c == '+' */
10942 if (p[0] == '\0' || LONE_DASH(p)) {
10944 /* "-" means turn off -x and -v */
10947 /* "--" means reset params */
10948 else if (*argptr == NULL)
10951 break; /* "-" or "--" terminates options */
10954 /* first char was + or - */
10955 while ((c = *p++) != '\0') {
10956 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10957 if (c == 'c' && cmdline) {
10958 minusc = p; /* command is after shell args */
10959 } else if (c == 'o') {
10960 if (plus_minus_o(*argptr, val)) {
10961 /* it already printed err message */
10962 return 1; /* error */
10966 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10969 /* bash does not accept +-login, we also won't */
10970 } else if (cmdline && val && (c == '-')) { /* long options */
10971 if (strcmp(p, "login") == 0) {
10985 * The shift builtin command.
10987 static int FAST_FUNC
10988 shiftcmd(int argc UNUSED_PARAM, char **argv)
10995 n = number(argv[1]);
10996 if (n > shellparam.nparam)
10999 shellparam.nparam -= n;
11000 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11001 if (shellparam.malloced)
11004 ap2 = shellparam.p;
11005 while ((*ap2++ = *ap1++) != NULL)
11007 #if ENABLE_ASH_GETOPTS
11008 shellparam.optind = 1;
11009 shellparam.optoff = -1;
11016 * POSIX requires that 'set' (but not export or readonly) output the
11017 * variables in lexicographic order - by the locale's collating order (sigh).
11018 * Maybe we could keep them in an ordered balanced binary tree
11019 * instead of hashed lists.
11020 * For now just roll 'em through qsort for printing...
11023 showvars(const char *sep_prefix, int on, int off)
11026 char **ep, **epend;
11028 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11029 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11031 sep = *sep_prefix ? " " : sep_prefix;
11033 for (; ep < epend; ep++) {
11037 p = endofname(*ep);
11038 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11039 * makes "export -p" to have output not suitable for "eval":
11041 * os.environ["test-test"]="test"
11042 * if os.fork() == 0:
11043 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11044 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11048 q = single_quote(++p);
11049 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11055 * The set command builtin.
11057 static int FAST_FUNC
11058 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11063 return showvars(nullstr, 0, VUNSET);
11066 retval = options(/*cmdline:*/ 0, NULL);
11067 if (retval == 0) { /* if no parse error... */
11069 if (*argptr != NULL) {
11077 #if ENABLE_ASH_RANDOM_SUPPORT
11078 static void FAST_FUNC
11079 change_random(const char *value)
11083 if (value == NULL) {
11084 /* "get", generate */
11085 t = next_random(&random_gen);
11086 /* set without recursion */
11087 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11088 vrandom.flags &= ~VNOFUNC;
11091 t = strtoul(value, NULL, 10);
11092 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11097 #if ENABLE_ASH_GETOPTS
11099 getopts(char *optstr, char *optvar, char **optfirst)
11106 int ind = shellparam.optind;
11107 int off = shellparam.optoff;
11111 shellparam.optind = -1;
11112 optnext = optfirst + ind - 1;
11114 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11117 p = optnext[-1] + off;
11118 if (p == NULL || *p == '\0') {
11119 /* Current word is done, advance */
11121 if (p == NULL || *p != '-' || *++p == '\0') {
11123 unsetvar("OPTARG");
11129 if (LONE_DASH(p)) /* check for "--" */
11134 for (q = optstr; *q != c;) {
11136 /* OPTERR is a bashism */
11137 const char *cp = lookupvar("OPTERR");
11138 if ((cp && LONE_CHAR(cp, '0'))
11139 || (optstr[0] == ':')
11142 /*sbuf[1] = '\0'; - already is */
11143 setvar0("OPTARG", sbuf);
11145 fprintf(stderr, "Illegal option -%c\n", c);
11146 unsetvar("OPTARG");
11156 if (*p == '\0' && (p = *optnext) == NULL) {
11157 /* OPTERR is a bashism */
11158 const char *cp = lookupvar("OPTERR");
11159 if ((cp && LONE_CHAR(cp, '0'))
11160 || (optstr[0] == ':')
11163 /*sbuf[1] = '\0'; - already is */
11164 setvar0("OPTARG", sbuf);
11167 fprintf(stderr, "No arg for -%c option\n", c);
11168 unsetvar("OPTARG");
11176 setvar0("OPTARG", p);
11179 setvar0("OPTARG", nullstr);
11181 ind = optnext - optfirst + 1;
11182 setvar("OPTIND", itoa(ind), VNOFUNC);
11184 /*sbuf[1] = '\0'; - already is */
11185 setvar0(optvar, sbuf);
11187 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11188 shellparam.optind = ind;
11194 * The getopts builtin. Shellparam.optnext points to the next argument
11195 * to be processed. Shellparam.optptr points to the next character to
11196 * be processed in the current argument. If shellparam.optnext is NULL,
11197 * then it's the first time getopts has been called.
11199 static int FAST_FUNC
11200 getoptscmd(int argc, char **argv)
11205 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11207 optbase = shellparam.p;
11208 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11209 shellparam.optind = 1;
11210 shellparam.optoff = -1;
11213 optbase = &argv[3];
11214 if ((unsigned)shellparam.optind > argc - 2) {
11215 shellparam.optind = 1;
11216 shellparam.optoff = -1;
11220 return getopts(argv[1], argv[2], optbase);
11222 #endif /* ASH_GETOPTS */
11225 /* ============ Shell parser */
11228 struct heredoc *next; /* next here document in list */
11229 union node *here; /* redirection node */
11230 char *eofmark; /* string indicating end of input */
11231 smallint striptabs; /* if set, strip leading tabs */
11234 static smallint tokpushback; /* last token pushed back */
11235 static smallint quoteflag; /* set if (part of) last token was quoted */
11236 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11237 static struct heredoc *heredoclist; /* list of here documents to read */
11238 static char *wordtext; /* text of last word returned by readtoken */
11239 static struct nodelist *backquotelist;
11240 static union node *redirnode;
11241 static struct heredoc *heredoc;
11243 static const char *
11244 tokname(char *buf, int tok)
11247 return tokname_array[tok];
11248 sprintf(buf, "\"%s\"", tokname_array[tok]);
11252 /* raise_error_unexpected_syntax:
11253 * Called when an unexpected token is read during the parse. The argument
11254 * is the token that is expected, or -1 if more than one type of token can
11255 * occur at this point.
11257 static void raise_error_unexpected_syntax(int) NORETURN;
11259 raise_error_unexpected_syntax(int token)
11265 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11267 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11268 raise_error_syntax(msg);
11272 /* parsing is heavily cross-recursive, need these forward decls */
11273 static union node *andor(void);
11274 static union node *pipeline(void);
11275 static union node *parse_command(void);
11276 static void parseheredoc(void);
11277 static int peektoken(void);
11278 static int readtoken(void);
11280 static union node *
11283 union node *n1, *n2, *n3;
11288 switch (peektoken()) {
11296 if (!n1 && (nlflag & 1))
11302 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11303 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11309 if (tok == TBACKGND) {
11310 if (n2->type == NPIPE) {
11311 n2->npipe.pipe_backgnd = 1;
11313 if (n2->type != NREDIR) {
11314 n3 = stzalloc(sizeof(struct nredir));
11316 /*n3->nredir.redirect = NULL; - stzalloc did it */
11319 n2->type = NBACKGND;
11325 n3 = stzalloc(sizeof(struct nbinary));
11327 n3->nbinary.ch1 = n1;
11328 n3->nbinary.ch2 = n2;
11341 raise_error_unexpected_syntax(-1);
11348 static union node *
11351 union node *n1, *n2, *n3;
11359 } else if (t == TOR) {
11365 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11367 n3 = stzalloc(sizeof(struct nbinary));
11369 n3->nbinary.ch1 = n1;
11370 n3->nbinary.ch2 = n2;
11375 static union node *
11378 union node *n1, *n2, *pipenode;
11379 struct nodelist *lp, *prev;
11383 TRACE(("pipeline: entered\n"));
11384 if (readtoken() == TNOT) {
11386 checkkwd = CHKKWD | CHKALIAS;
11389 n1 = parse_command();
11390 if (readtoken() == TPIPE) {
11391 pipenode = stzalloc(sizeof(struct npipe));
11392 pipenode->type = NPIPE;
11393 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11394 lp = stzalloc(sizeof(struct nodelist));
11395 pipenode->npipe.cmdlist = lp;
11399 lp = stzalloc(sizeof(struct nodelist));
11400 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11401 lp->n = parse_command();
11403 } while (readtoken() == TPIPE);
11409 n2 = stzalloc(sizeof(struct nnot));
11417 static union node *
11422 n = stzalloc(sizeof(struct narg));
11424 /*n->narg.next = NULL; - stzalloc did it */
11425 n->narg.text = wordtext;
11426 n->narg.backquote = backquotelist;
11431 fixredir(union node *n, const char *text, int err)
11435 TRACE(("Fix redir %s %d\n", text, err));
11437 n->ndup.vname = NULL;
11439 fd = bb_strtou(text, NULL, 10);
11440 if (!errno && fd >= 0)
11441 n->ndup.dupfd = fd;
11442 else if (LONE_DASH(text))
11443 n->ndup.dupfd = -1;
11446 raise_error_syntax("bad fd number");
11447 n->ndup.vname = makename();
11454 union node *n = redirnode;
11456 if (n->type == NHERE)
11457 checkkwd = CHKEOFMARK;
11458 if (readtoken() != TWORD)
11459 raise_error_unexpected_syntax(-1);
11460 if (n->type == NHERE) {
11461 struct heredoc *here = heredoc;
11464 if (quoteflag == 0)
11466 TRACE(("Here document %d\n", n->type));
11467 rmescapes(wordtext, 0, NULL);
11468 here->eofmark = wordtext;
11470 if (heredoclist == NULL)
11471 heredoclist = here;
11473 for (p = heredoclist; p->next; p = p->next)
11477 } else if (n->type == NTOFD || n->type == NFROMFD) {
11478 fixredir(n, wordtext, 0);
11480 n->nfile.fname = makename();
11484 static union node *
11487 union node *args, **app;
11488 union node *n = NULL;
11489 union node *vars, **vpp;
11490 union node **rpp, *redir;
11494 smallint double_brackets_flag = 0;
11496 IF_BASH_FUNCTION(smallint function_flag = 0;)
11505 savecheckkwd = CHKALIAS;
11506 savelinno = g_parsefile->linno;
11509 checkkwd = savecheckkwd;
11514 if (peektoken() != TWORD)
11515 raise_error_unexpected_syntax(TWORD);
11520 case TAND: /* "&&" */
11521 case TOR: /* "||" */
11522 if (!double_brackets_flag) {
11526 wordtext = (char *) (t == TAND ? "-a" : "-o");
11529 n = stzalloc(sizeof(struct narg));
11531 /*n->narg.next = NULL; - stzalloc did it */
11532 n->narg.text = wordtext;
11534 if (strcmp("[[", wordtext) == 0)
11535 double_brackets_flag = 1;
11536 else if (strcmp("]]", wordtext) == 0)
11537 double_brackets_flag = 0;
11539 n->narg.backquote = backquotelist;
11540 if (savecheckkwd && isassignment(wordtext)) {
11542 vpp = &n->narg.next;
11545 app = &n->narg.next;
11549 if (function_flag) {
11550 checkkwd = CHKNL | CHKKWD;
11551 switch (peektoken()) {
11563 if (strcmp("[[", wordtext) == 0)
11567 raise_error_unexpected_syntax(-1);
11573 *rpp = n = redirnode;
11574 rpp = &n->nfile.next;
11575 parsefname(); /* read name of redirection file */
11578 IF_BASH_FUNCTION(do_func:)
11579 if (args && app == &args->narg.next
11582 struct builtincmd *bcmd;
11585 /* We have a function */
11586 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11587 raise_error_unexpected_syntax(TRP);
11588 name = n->narg.text;
11589 if (!goodname(name)
11590 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11592 raise_error_syntax("bad function name");
11595 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11596 n->ndefun.text = n->narg.text;
11597 n->ndefun.linno = g_parsefile->linno;
11598 n->ndefun.body = parse_command();
11601 IF_BASH_FUNCTION(function_flag = 0;)
11612 n = stzalloc(sizeof(struct ncmd));
11614 n->ncmd.linno = savelinno;
11615 n->ncmd.args = args;
11616 n->ncmd.assign = vars;
11617 n->ncmd.redirect = redir;
11621 static union node *
11622 parse_command(void)
11624 union node *n1, *n2;
11625 union node *ap, **app;
11626 union node *cp, **cpp;
11627 union node *redir, **rpp;
11635 savelinno = g_parsefile->linno;
11637 switch (readtoken()) {
11639 raise_error_unexpected_syntax(-1);
11642 n1 = stzalloc(sizeof(struct nif));
11644 n1->nif.test = list(0);
11645 if (readtoken() != TTHEN)
11646 raise_error_unexpected_syntax(TTHEN);
11647 n1->nif.ifpart = list(0);
11649 while (readtoken() == TELIF) {
11650 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11651 n2 = n2->nif.elsepart;
11653 n2->nif.test = list(0);
11654 if (readtoken() != TTHEN)
11655 raise_error_unexpected_syntax(TTHEN);
11656 n2->nif.ifpart = list(0);
11658 if (lasttoken == TELSE)
11659 n2->nif.elsepart = list(0);
11661 n2->nif.elsepart = NULL;
11669 n1 = stzalloc(sizeof(struct nbinary));
11670 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11671 n1->nbinary.ch1 = list(0);
11674 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11675 got == TWORD ? wordtext : ""));
11676 raise_error_unexpected_syntax(TDO);
11678 n1->nbinary.ch2 = list(0);
11683 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11684 raise_error_syntax("bad for loop variable");
11685 n1 = stzalloc(sizeof(struct nfor));
11687 n1->nfor.linno = savelinno;
11688 n1->nfor.var = wordtext;
11689 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11690 if (readtoken() == TIN) {
11692 while (readtoken() == TWORD) {
11693 n2 = stzalloc(sizeof(struct narg));
11695 /*n2->narg.next = NULL; - stzalloc did it */
11696 n2->narg.text = wordtext;
11697 n2->narg.backquote = backquotelist;
11699 app = &n2->narg.next;
11702 n1->nfor.args = ap;
11703 if (lasttoken != TNL && lasttoken != TSEMI)
11704 raise_error_unexpected_syntax(-1);
11706 n2 = stzalloc(sizeof(struct narg));
11708 /*n2->narg.next = NULL; - stzalloc did it */
11709 n2->narg.text = (char *)dolatstr;
11710 /*n2->narg.backquote = NULL;*/
11711 n1->nfor.args = n2;
11713 * Newline or semicolon here is optional (but note
11714 * that the original Bourne shell only allowed NL).
11716 if (lasttoken != TSEMI)
11719 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11720 if (readtoken() != TDO)
11721 raise_error_unexpected_syntax(TDO);
11722 n1->nfor.body = list(0);
11726 n1 = stzalloc(sizeof(struct ncase));
11728 n1->ncase.linno = savelinno;
11729 if (readtoken() != TWORD)
11730 raise_error_unexpected_syntax(TWORD);
11731 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11733 /*n2->narg.next = NULL; - stzalloc did it */
11734 n2->narg.text = wordtext;
11735 n2->narg.backquote = backquotelist;
11736 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11737 if (readtoken() != TIN)
11738 raise_error_unexpected_syntax(TIN);
11739 cpp = &n1->ncase.cases;
11741 checkkwd = CHKNL | CHKKWD;
11743 while (t != TESAC) {
11744 if (lasttoken == TLP)
11746 *cpp = cp = stzalloc(sizeof(struct nclist));
11748 app = &cp->nclist.pattern;
11750 *app = ap = stzalloc(sizeof(struct narg));
11752 /*ap->narg.next = NULL; - stzalloc did it */
11753 ap->narg.text = wordtext;
11754 ap->narg.backquote = backquotelist;
11755 if (readtoken() != TPIPE)
11757 app = &ap->narg.next;
11760 //ap->narg.next = NULL;
11761 if (lasttoken != TRP)
11762 raise_error_unexpected_syntax(TRP);
11763 cp->nclist.body = list(2);
11765 cpp = &cp->nclist.next;
11767 checkkwd = CHKNL | CHKKWD;
11771 raise_error_unexpected_syntax(TENDCASE);
11778 n1 = stzalloc(sizeof(struct nredir));
11779 n1->type = NSUBSHELL;
11780 n1->nredir.linno = savelinno;
11781 n1->nredir.n = list(0);
11782 /*n1->nredir.redirect = NULL; - stzalloc did it */
11789 IF_BASH_FUNCTION(case TFUNCTION:)
11793 return simplecmd();
11796 if (readtoken() != t)
11797 raise_error_unexpected_syntax(t);
11800 /* Now check for redirection which may follow command */
11801 checkkwd = CHKKWD | CHKALIAS;
11803 while (readtoken() == TREDIR) {
11804 *rpp = n2 = redirnode;
11805 rpp = &n2->nfile.next;
11811 if (n1->type != NSUBSHELL) {
11812 n2 = stzalloc(sizeof(struct nredir));
11814 n2->nredir.linno = savelinno;
11818 n1->nredir.redirect = redir;
11823 #if BASH_DOLLAR_SQUOTE
11825 decode_dollar_squote(void)
11827 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11833 p = strchr(C_escapes, c);
11838 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11842 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11844 } else if (c == 'x') { /* \xHH */
11848 } while (isxdigit(c) && --cnt);
11850 if (cnt == 3) { /* \x but next char is "bad" */
11854 } else { /* simple seq like \\ or \t */
11859 c = bb_process_escape_sequence((void*)&p);
11860 } else { /* unrecognized "\z": print both chars unless ' or " */
11861 if (c != '\'' && c != '"') {
11863 c |= 0x100; /* "please encode \, then me" */
11870 /* Used by expandstr to get here-doc like behaviour. */
11871 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11873 static ALWAYS_INLINE int
11874 realeofmark(const char *eofmark)
11876 return eofmark && eofmark != FAKEEOFMARK;
11880 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11881 * is not NULL, read a here document. In the latter case, eofmark is the
11882 * word which marks the end of the document and striptabs is true if
11883 * leading tabs should be stripped from the document. The argument c
11884 * is the first character of the input token or document.
11886 * Because C does not have internal subroutines, I have simulated them
11887 * using goto's to implement the subroutine linkage. The following macros
11888 * will run code that appears at the end of readtoken1.
11890 #define CHECKEND() {goto checkend; checkend_return:;}
11891 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11892 #define PARSESUB() {goto parsesub; parsesub_return:;}
11893 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11894 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11895 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11897 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11899 /* NB: syntax parameter fits into smallint */
11900 /* c parameter is an unsigned char or PEOF or PEOA */
11903 struct nodelist *bqlist;
11907 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11908 smallint pssyntax; /* we are expanding a prompt string */
11909 int varnest; /* levels of variables expansion */
11910 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11911 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11912 int dqvarnest; /* levels of variables expansion within double quotes */
11913 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11917 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11918 #if ENABLE_ASH_EXPAND_PRMT
11919 pssyntax = (syntax == PSSYNTAX);
11923 pssyntax = 0; /* constant */
11925 dblquote = (syntax == DQSYNTAX);
11927 IF_FEATURE_SH_MATH(arinest = 0;)
11928 IF_FEATURE_SH_MATH(parenlevel = 0;)
11931 STARTSTACKSTR(out);
11933 /* For each line, until end of word */
11934 CHECKEND(); /* set c to PEOF if at end of here document */
11935 for (;;) { /* until end of line or end of word */
11936 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11937 switch (SIT(c, syntax)) {
11938 case CNL: /* '\n' */
11939 if (syntax == BASESYNTAX)
11940 goto endword; /* exit outer loop */
11944 goto loop; /* continue outer loop */
11949 #if BASH_DOLLAR_SQUOTE
11950 if (c == '\\' && bash_dollar_squote) {
11951 c = decode_dollar_squote();
11953 /* skip $'\000', $'\x00' (like bash) */
11957 /* Unknown escape. Encode as '\z' */
11958 c = (unsigned char)c;
11959 if (eofmark == NULL || dblquote)
11960 USTPUTC(CTLESC, out);
11961 USTPUTC('\\', out);
11965 if (eofmark == NULL || dblquote)
11966 USTPUTC(CTLESC, out);
11969 case CBACK: /* backslash */
11970 c = pgetc_without_PEOA();
11972 USTPUTC(CTLESC, out);
11973 USTPUTC('\\', out);
11975 } else if (c == '\n') {
11978 if (pssyntax && c == '$') {
11979 USTPUTC(CTLESC, out);
11980 USTPUTC('\\', out);
11982 /* Backslash is retained if we are in "str" and next char isn't special */
11987 && (c != '"' || eofmark != NULL)
11989 USTPUTC('\\', out);
11991 USTPUTC(CTLESC, out);
11999 if (eofmark == NULL) {
12000 USTPUTC(CTLQUOTEMARK, out);
12008 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12009 if (eofmark != NULL && varnest == 0) {
12012 if (dqvarnest == 0) {
12013 syntax = BASESYNTAX;
12020 case CVAR: /* '$' */
12021 PARSESUB(); /* parse substitution */
12023 case CENDVAR: /* '}' */
12026 if (dqvarnest > 0) {
12033 #if ENABLE_FEATURE_SH_MATH
12034 case CLP: /* '(' in arithmetic */
12038 case CRP: /* ')' in arithmetic */
12039 if (parenlevel > 0) {
12042 if (pgetc_eatbnl() == ')') {
12044 if (--arinest == 0) {
12045 syntax = prevsyntax;
12049 * unbalanced parens
12050 * (don't 2nd guess - no error)
12058 case CBQUOTE: /* '`' */
12062 goto endword; /* exit outer loop */
12066 if (varnest == 0) {
12067 #if BASH_REDIR_OUTPUT
12069 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12070 if (pgetc() == '>')
12071 c = 0x100 + '>'; /* flag &> */
12075 goto endword; /* exit outer loop */
12077 IF_ASH_ALIAS(if (c != PEOA))
12084 #if ENABLE_FEATURE_SH_MATH
12085 if (syntax == ARISYNTAX)
12086 raise_error_syntax("missing '))'");
12088 if (syntax != BASESYNTAX && eofmark == NULL)
12089 raise_error_syntax("unterminated quoted string");
12090 if (varnest != 0) {
12092 raise_error_syntax("missing '}'");
12094 USTPUTC('\0', out);
12095 len = out - (char *)stackblock();
12096 out = stackblock();
12097 if (eofmark == NULL) {
12098 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12101 if (isdigit_str9(out)) {
12102 PARSEREDIR(); /* passed as params: out, c */
12103 lasttoken = TREDIR;
12106 /* else: non-number X seen, interpret it
12107 * as "NNNX>file" = "NNNX >file" */
12111 quoteflag = quotef;
12112 backquotelist = bqlist;
12113 grabstackblock(len);
12117 /* end of readtoken routine */
12120 * Check to see whether we are at the end of the here document. When this
12121 * is called, c is set to the first character of the next input line. If
12122 * we are at the end of the here document, this routine sets the c to PEOF.
12125 if (realeofmark(eofmark)) {
12129 #if ENABLE_ASH_ALIAS
12131 c = pgetc_without_PEOA();
12134 while (c == '\t') {
12135 c = pgetc_without_PEOA();
12139 markloc = out - (char *)stackblock();
12140 for (p = eofmark; STPUTC(c, out), *p; p++) {
12144 c = pgetc_without_PEOA();
12147 if (c == '\n' || c == PEOF) {
12149 g_parsefile->linno++;
12150 needprompt = doprompt;
12155 p = (char *)stackblock() + markloc + 1;
12156 len_here = out - p;
12159 len_here -= (c >= PEOF);
12165 str = alloca(len_here + 1);
12166 *(char *)mempcpy(str, p, len_here) = '\0';
12168 pushstring(str, NULL);
12173 STADJUST((char *)stackblock() + markloc - out, out);
12175 goto checkend_return;
12179 * Parse a redirection operator. The variable "out" points to a string
12180 * specifying the fd to be redirected. The variable "c" contains the
12181 * first character of the redirection operator.
12184 /* out is already checked to be a valid number or "" */
12185 int fd = (*out == '\0' ? -1 : atoi(out));
12188 np = stzalloc(sizeof(struct nfile));
12193 np->type = NAPPEND;
12195 np->type = NCLOBBER;
12198 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12204 #if BASH_REDIR_OUTPUT
12205 else if (c == 0x100 + '>') { /* this flags &> redirection */
12207 pgetc(); /* this is '>', no need to check */
12211 else { /* c == '<' */
12212 /*np->nfile.fd = 0; - stzalloc did it */
12216 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12217 np = stzalloc(sizeof(struct nhere));
12218 /*np->nfile.fd = 0; - stzalloc did it */
12221 heredoc = stzalloc(sizeof(struct heredoc));
12222 heredoc->here = np;
12225 heredoc->striptabs = 1;
12227 /*heredoc->striptabs = 0; - stzalloc did it */
12233 np->type = NFROMFD;
12237 np->type = NFROMTO;
12249 goto parseredir_return;
12253 * Parse a substitution. At this point, we have read the dollar sign
12254 * and nothing else.
12257 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12258 * (assuming ascii char codes, as the original implementation did) */
12259 #define is_special(c) \
12260 (((unsigned)(c) - 33 < 32) \
12261 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12263 unsigned char subtype;
12266 c = pgetc_eatbnl();
12267 if ((checkkwd & CHKEOFMARK)
12268 || c > 255 /* PEOA or PEOF */
12269 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12271 #if BASH_DOLLAR_SQUOTE
12272 if (syntax != DQSYNTAX && c == '\'')
12273 bash_dollar_squote = 1;
12278 } else if (c == '(') {
12279 /* $(command) or $((arith)) */
12280 if (pgetc_eatbnl() == '(') {
12281 #if ENABLE_FEATURE_SH_MATH
12284 raise_error_syntax("support for $((arith)) is disabled");
12291 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12292 USTPUTC(CTLVAR, out);
12293 typeloc = out - (char *)stackblock();
12295 subtype = VSNORMAL;
12297 c = pgetc_eatbnl();
12302 /* $[{[#]]NAME[}] */
12305 c = pgetc_eatbnl();
12306 } while (is_in_name(c));
12307 } else if (isdigit(c)) {
12308 /* $[{[#]]NUM[}] */
12311 c = pgetc_eatbnl();
12312 } while (isdigit(c));
12314 /* $[{[#]]<specialchar>[}] */
12317 c = pgetc_eatbnl();
12318 if (!subtype && cc == '#') {
12319 subtype = VSLENGTH;
12320 if (c == '_' || isalnum(c))
12323 c = pgetc_eatbnl();
12324 if (cc == '}' || c != '}') {
12332 if (!is_special(cc)) {
12333 if (subtype == VSLENGTH)
12341 if (c != '}' && subtype == VSLENGTH) {
12342 /* ${#VAR didn't end with } */
12346 if (subtype == 0) {
12347 static const char types[] ALIGN1 = "}-+?=";
12348 /* ${VAR...} but not $VAR or ${#VAR} */
12349 /* c == first char after VAR */
12352 c = pgetc_eatbnl();
12354 /* This check is only needed to not misinterpret
12355 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12358 if (!strchr(types, c)) {
12359 subtype = VSSUBSTR;
12361 break; /* "goto badsub" is bigger (!) */
12367 const char *p = strchr(types, c);
12370 subtype |= p - types + VSNORMAL;
12376 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12377 c = pgetc_eatbnl();
12383 #if BASH_PATTERN_SUBST
12385 /* ${v/[/]pattern/repl} */
12386 //TODO: encode pattern and repl separately.
12387 // Currently ${v/$var_with_slash/repl} is horribly broken
12388 subtype = VSREPLACE;
12389 c = pgetc_eatbnl();
12392 subtype++; /* VSREPLACEALL */
12400 ((unsigned char *)stackblock())[typeloc] = subtype;
12401 if (subtype != VSNORMAL) {
12408 goto parsesub_return;
12412 * Called to parse command substitutions. Newstyle is set if the command
12413 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12414 * list of commands (passed by reference), and savelen is the number of
12415 * characters on the top of the stack which must be preserved.
12418 struct nodelist **nlpp;
12422 smallint saveprompt = 0;
12425 savelen = out - (char *)stackblock();
12428 * FIXME: this can allocate very large block on stack and SEGV.
12430 * echo "..<100kbytes>..`true` $(true) `true` ..."
12431 * allocates 100kb for every command subst. With about
12432 * a hundred command substitutions stack overflows.
12433 * With larger prepended string, SEGV happens sooner.
12435 str = alloca(savelen);
12436 memcpy(str, stackblock(), savelen);
12440 /* We must read until the closing backquote, giving special
12441 * treatment to some slashes, and then push the string and
12442 * reread it as input, interpreting it normally.
12448 STARTSTACKSTR(pout);
12452 setprompt_if(needprompt, 2);
12463 * If eating a newline, avoid putting
12464 * the newline into the new character
12465 * stream (via the STPUTC after the
12470 if (pc != '\\' && pc != '`' && pc != '$'
12471 && (!dblquote || pc != '"')
12473 STPUTC('\\', pout);
12475 if (pc <= 255 /* not PEOA or PEOF */) {
12481 IF_ASH_ALIAS(case PEOA:)
12482 raise_error_syntax("EOF in backquote substitution");
12494 STPUTC('\0', pout);
12495 psavelen = pout - (char *)stackblock();
12496 if (psavelen > 0) {
12497 pstr = grabstackstr(pout);
12498 setinputstring(pstr);
12503 nlpp = &(*nlpp)->next;
12504 *nlpp = stzalloc(sizeof(**nlpp));
12505 /* (*nlpp)->next = NULL; - stzalloc did it */
12508 saveprompt = doprompt;
12515 doprompt = saveprompt;
12516 else if (readtoken() != TRP)
12517 raise_error_unexpected_syntax(TRP);
12522 * Start reading from old file again, ignoring any pushed back
12523 * tokens left from the backquote parsing
12528 while (stackblocksize() <= savelen)
12530 STARTSTACKSTR(out);
12532 memcpy(out, str, savelen);
12533 STADJUST(savelen, out);
12535 USTPUTC(CTLBACKQ, out);
12537 goto parsebackq_oldreturn;
12538 goto parsebackq_newreturn;
12541 #if ENABLE_FEATURE_SH_MATH
12543 * Parse an arithmetic expansion (indicate start of one and set state)
12546 if (++arinest == 1) {
12547 prevsyntax = syntax;
12548 syntax = ARISYNTAX;
12550 USTPUTC(CTLARI, out);
12551 goto parsearith_return;
12554 } /* end of readtoken */
12557 * Read the next input token.
12558 * If the token is a word, we set backquotelist to the list of cmds in
12559 * backquotes. We set quoteflag to true if any part of the word was
12561 * If the token is TREDIR, then we set redirnode to a structure containing
12564 * [Change comment: here documents and internal procedures]
12565 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12566 * word parsing code into a separate routine. In this case, readtoken
12567 * doesn't need to have any internal procedures, but parseword does.
12568 * We could also make parseoperator in essence the main routine, and
12569 * have parseword (readtoken1?) handle both words and redirection.]
12571 #define NEW_xxreadtoken
12572 #ifdef NEW_xxreadtoken
12573 /* singles must be first! */
12574 static const char xxreadtoken_chars[7] ALIGN1 = {
12575 '\n', '(', ')', /* singles */
12576 '&', '|', ';', /* doubles */
12580 #define xxreadtoken_singles 3
12581 #define xxreadtoken_doubles 3
12583 static const char xxreadtoken_tokens[] ALIGN1 = {
12584 TNL, TLP, TRP, /* only single occurrence allowed */
12585 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12586 TEOF, /* corresponds to trailing nul */
12587 TAND, TOR, TENDCASE /* if double occurrence */
12599 setprompt_if(needprompt, 2);
12600 for (;;) { /* until token or start of word found */
12602 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12606 while ((c = pgetc()) != '\n' && c != PEOF)
12609 } else if (c == '\\') {
12610 if (pgetc() != '\n') {
12612 break; /* return readtoken1(...) */
12618 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12624 p = strchr(xxreadtoken_chars, c);
12626 break; /* return readtoken1(...) */
12628 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12630 if (cc == c) { /* double occurrence? */
12631 p += xxreadtoken_doubles + 1;
12634 #if BASH_REDIR_OUTPUT
12635 if (c == '&' && cc == '>') /* &> */
12636 break; /* return readtoken1(...) */
12641 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12646 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12648 #else /* old xxreadtoken */
12649 #define RETURN(token) return lasttoken = token
12659 setprompt_if(needprompt, 2);
12660 for (;;) { /* until token or start of word found */
12663 case ' ': case '\t':
12664 IF_ASH_ALIAS(case PEOA:)
12667 while ((c = pgetc()) != '\n' && c != PEOF)
12672 if (pgetc() == '\n') {
12684 if (pgetc() == '&')
12689 if (pgetc() == '|')
12694 if (pgetc() == ';')
12707 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12710 #endif /* old xxreadtoken */
12716 int kwd = checkkwd;
12718 smallint alreadyseen = tokpushback;
12721 #if ENABLE_ASH_ALIAS
12737 if (t != TWORD || quoteflag) {
12742 * check for keywords
12744 if (kwd & CHKKWD) {
12745 const char *const *pp;
12747 pp = findkwd(wordtext);
12749 lasttoken = t = pp - tokname_array;
12750 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12755 if (checkkwd & CHKALIAS) {
12756 #if ENABLE_ASH_ALIAS
12758 ap = lookupalias(wordtext, 1);
12761 pushstring(ap->val, ap);
12771 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12773 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12789 * Read and parse a command. Returns NODE_EOF on end of file.
12790 * (NULL is a valid parse tree indicating a blank line.)
12792 static union node *
12793 parsecmd(int interact)
12798 doprompt = interact;
12799 setprompt_if(doprompt, doprompt);
12805 * Input any here documents.
12810 struct heredoc *here;
12813 here = heredoclist;
12814 heredoclist = NULL;
12817 setprompt_if(needprompt, 2);
12818 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12819 here->eofmark, here->striptabs);
12820 n = stzalloc(sizeof(struct narg));
12821 n->narg.type = NARG;
12822 /*n->narg.next = NULL; - stzalloc did it */
12823 n->narg.text = wordtext;
12824 n->narg.backquote = backquotelist;
12825 here->here->nhere.doc = n;
12831 static const char *
12832 expandstr(const char *ps, int syntax_type)
12837 /* XXX Fix (char *) cast. */
12838 setinputstring((char *)ps);
12840 saveprompt = doprompt;
12843 /* readtoken1() might die horribly.
12844 * Try a prompt with syntactically wrong command:
12845 * PS1='$(date "+%H:%M:%S) > '
12848 volatile int saveint;
12849 struct jmploc *volatile savehandler = exception_handler;
12850 struct jmploc jmploc;
12852 if (setjmp(jmploc.loc) == 0) {
12853 exception_handler = &jmploc;
12854 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12856 exception_handler = savehandler;
12857 RESTORE_INT(saveint);
12860 doprompt = saveprompt;
12864 n.narg.type = NARG;
12865 n.narg.next = NULL;
12866 n.narg.text = wordtext;
12867 n.narg.backquote = backquotelist;
12869 expandarg(&n, NULL, EXP_QUOTED);
12870 return stackblock();
12876 return tokpushback && lasttoken == TEOF;
12880 * Execute a command or commands contained in a string.
12883 evalstring(char *s, int flags)
12885 struct jmploc *volatile savehandler;
12886 struct jmploc jmploc;
12890 struct stackmark smark;
12895 setstackmark(&smark);
12898 /* On exception inside execution loop, we must popfile().
12899 * Try interactively:
12901 * command eval "a=b" # throws "is read only" error
12902 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12903 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12905 savehandler = exception_handler;
12906 ex = setjmp(jmploc.loc);
12909 exception_handler = &jmploc;
12911 while ((n = parsecmd(0)) != NODE_EOF) {
12914 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12917 popstackmark(&smark);
12922 popstackmark(&smark);
12926 exception_handler = savehandler;
12928 longjmp(exception_handler->loc, ex);
12934 * The eval command.
12936 static int FAST_FUNC
12937 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12946 STARTSTACKSTR(concat);
12948 concat = stack_putstr(p, concat);
12952 STPUTC(' ', concat);
12954 STPUTC('\0', concat);
12955 p = grabstackstr(concat);
12957 return evalstring(p, flags & EV_TESTED);
12963 * Read and execute commands.
12964 * "Top" is nonzero for the top level command loop;
12965 * it turns on prompting if the shell is interactive.
12971 struct stackmark smark;
12976 TRACE(("cmdloop(%d) called\n", top));
12980 setstackmark(&smark);
12983 showjobs(SHOW_CHANGED|SHOW_STDERR);
12986 if (iflag && top) {
12990 n = parsecmd(inter);
12992 if (DEBUG > 2 && debug && (n != NODE_EOF))
12995 if (n == NODE_EOF) {
12996 if (!top || numeof >= 50)
12998 if (!stoppedjobs()) {
13001 out2str("\nUse \"exit\" to leave shell.\n");
13004 } else if (nflag == 0) {
13007 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13010 i = evaltree(n, 0);
13014 popstackmark(&smark);
13018 evalskip &= ~SKIPFUNC;
13026 * Take commands from a file. To be compatible we should do a path
13027 * search for the file, which is necessary to find sub-commands.
13030 find_dot_file(char *name)
13033 const char *path = pathval();
13036 /* don't try this for absolute or relative paths */
13037 if (strchr(name, '/'))
13040 while ((fullname = path_advance(&path, name)) != NULL) {
13041 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13043 * Don't bother freeing here, since it will
13044 * be freed by the caller.
13048 if (fullname != name)
13049 stunalloc(fullname);
13051 /* not found in PATH */
13053 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13056 ash_msg_and_raise_error("%s: not found", name);
13061 static int FAST_FUNC
13062 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13064 /* "false; . empty_file; echo $?" should print 0, not 1: */
13068 char *args_need_save;
13069 volatile struct shparam saveparam;
13072 // struct strlist *sp;
13073 // for (sp = cmdenviron; sp; sp = sp->next)
13074 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13076 nextopt(nullstr); /* handle possible "--" */
13080 /* bash says: "bash: .: filename argument required" */
13081 return 2; /* bash compat */
13084 /* This aborts if file isn't found, which is POSIXly correct.
13085 * bash returns exitcode 1 instead.
13087 fullname = find_dot_file(argv[0]);
13089 args_need_save = argv[0];
13090 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13092 saveparam = shellparam;
13093 shellparam.malloced = 0;
13097 shellparam.nparam = argc;
13098 shellparam.p = argv;
13101 /* This aborts if file can't be opened, which is POSIXly correct.
13102 * bash returns exitcode 1 instead.
13104 setinputfile(fullname, INPUT_PUSH_FILE);
13105 commandname = fullname;
13106 status = cmdloop(0);
13109 if (args_need_save) {
13110 freeparam(&shellparam);
13111 shellparam = saveparam;
13117 static int FAST_FUNC
13118 exitcmd(int argc UNUSED_PARAM, char **argv)
13123 exitstatus = number(argv[1]);
13124 raise_exception(EXEXIT);
13129 * Read a file containing shell functions.
13132 readcmdfile(char *name)
13134 setinputfile(name, INPUT_PUSH_FILE);
13140 /* ============ find_command inplementation */
13143 * Resolve a command name. If you change this routine, you may have to
13144 * change the shellexec routine as well.
13147 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13149 struct tblentry *cmdp;
13156 struct builtincmd *bcmd;
13158 /* If name contains a slash, don't use PATH or hash table */
13159 if (strchr(name, '/') != NULL) {
13160 entry->u.index = -1;
13161 if (act & DO_ABS) {
13162 while (stat(name, &statb) < 0) {
13164 if (errno == EINTR)
13167 entry->cmdtype = CMDUNKNOWN;
13171 entry->cmdtype = CMDNORMAL;
13175 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13177 updatetbl = (path == pathval());
13180 if (strstr(path, "%builtin") != NULL)
13181 act |= DO_ALTBLTIN;
13184 /* If name is in the table, check answer will be ok */
13185 cmdp = cmdlookup(name, 0);
13186 if (cmdp != NULL) {
13189 switch (cmdp->cmdtype) {
13207 } else if (cmdp->rehash == 0)
13208 /* if not invalidated by cd, we're done */
13212 /* If %builtin not in path, check for builtin next */
13213 bcmd = find_builtin(name);
13215 if (IS_BUILTIN_REGULAR(bcmd))
13216 goto builtin_success;
13217 if (act & DO_ALTPATH) {
13218 if (!(act & DO_ALTBLTIN))
13219 goto builtin_success;
13220 } else if (builtinloc <= 0) {
13221 goto builtin_success;
13225 #if ENABLE_FEATURE_SH_STANDALONE
13227 int applet_no = find_applet_by_name(name);
13228 if (applet_no >= 0) {
13229 entry->cmdtype = CMDNORMAL;
13230 entry->u.index = -2 - applet_no;
13236 /* We have to search path. */
13237 prev = -1; /* where to start */
13238 if (cmdp && cmdp->rehash) { /* doing a rehash */
13239 if (cmdp->cmdtype == CMDBUILTIN)
13242 prev = cmdp->param.index;
13248 while ((fullname = path_advance(&path, name)) != NULL) {
13249 stunalloc(fullname);
13250 /* NB: code below will still use fullname
13251 * despite it being "unallocated" */
13254 if (prefix(pathopt, "builtin")) {
13256 goto builtin_success;
13259 if ((act & DO_NOFUNC)
13260 || !prefix(pathopt, "func")
13261 ) { /* ignore unimplemented options */
13265 /* if rehash, don't redo absolute path names */
13266 if (fullname[0] == '/' && idx <= prev) {
13269 TRACE(("searchexec \"%s\": no change\n", name));
13272 while (stat(fullname, &statb) < 0) {
13274 if (errno == EINTR)
13277 if (errno != ENOENT && errno != ENOTDIR)
13281 e = EACCES; /* if we fail, this will be the error */
13282 if (!S_ISREG(statb.st_mode))
13284 if (pathopt) { /* this is a %func directory */
13285 stalloc(strlen(fullname) + 1);
13286 /* NB: stalloc will return space pointed by fullname
13287 * (because we don't have any intervening allocations
13288 * between stunalloc above and this stalloc) */
13289 readcmdfile(fullname);
13290 cmdp = cmdlookup(name, 0);
13291 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13292 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13293 stunalloc(fullname);
13296 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13298 entry->cmdtype = CMDNORMAL;
13299 entry->u.index = idx;
13303 cmdp = cmdlookup(name, 1);
13304 cmdp->cmdtype = CMDNORMAL;
13305 cmdp->param.index = idx;
13310 /* We failed. If there was an entry for this command, delete it */
13311 if (cmdp && updatetbl)
13312 delete_cmd_entry();
13313 if (act & DO_ERR) {
13314 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13315 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13316 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13318 argv[0] = (char*) "command_not_found_handle";
13321 evalfun(hookp->param.func, 2, argv, 0);
13322 entry->cmdtype = CMDUNKNOWN;
13326 ash_msg("%s: %s", name, errmsg(e, "not found"));
13328 entry->cmdtype = CMDUNKNOWN;
13333 entry->cmdtype = CMDBUILTIN;
13334 entry->u.cmd = bcmd;
13338 cmdp = cmdlookup(name, 1);
13339 cmdp->cmdtype = CMDBUILTIN;
13340 cmdp->param.cmd = bcmd;
13344 entry->cmdtype = cmdp->cmdtype;
13345 entry->u = cmdp->param;
13350 * The trap builtin.
13352 static int FAST_FUNC
13353 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13357 int signo, exitcode;
13362 for (signo = 0; signo < NSIG; signo++) {
13363 char *tr = trap_ptr[signo];
13365 /* note: bash adds "SIG", but only if invoked
13366 * as "bash". If called as "sh", or if set -o posix,
13367 * then it prints short signal names.
13368 * We are printing short names: */
13369 out1fmt("trap -- %s %s\n",
13371 get_signame(signo));
13372 /* trap_ptr != trap only if we are in special-cased `trap` code.
13373 * In this case, we will exit very soon, no need to free(). */
13374 /* if (trap_ptr != trap && tp[0]) */
13379 if (trap_ptr != trap) {
13387 /* Why the second check?
13388 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13389 * In this case, NUM is signal no, not an action.
13392 if (ap[1] && !is_number(ap[0]))
13397 signo = get_signum(*ap);
13399 /* Mimic bash message exactly */
13400 ash_msg("%s: invalid signal specification", *ap);
13406 if (LONE_DASH(action))
13409 if (action[0]) /* not NULL and not "" and not "-" */
13410 may_have_traps = 1;
13411 action = ckstrdup(action);
13415 trap[signo] = action;
13426 /* ============ Builtins */
13428 #if ENABLE_ASH_HELP
13429 static int FAST_FUNC
13430 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13436 "Built-in commands:\n"
13437 "------------------\n");
13438 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13439 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13440 builtintab[i].name + 1);
13446 # if ENABLE_FEATURE_SH_STANDALONE
13448 const char *a = applet_names;
13450 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13455 while (*a++ != '\0')
13460 newline_and_flush(stdout);
13461 return EXIT_SUCCESS;
13466 static int FAST_FUNC
13467 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13469 show_history(line_input_state);
13470 return EXIT_SUCCESS;
13475 * The export and readonly commands.
13477 static int FAST_FUNC
13478 exportcmd(int argc UNUSED_PARAM, char **argv)
13488 /* "readonly" in bash accepts, but ignores -n.
13489 * We do the same: it saves a conditional in nextopt's param.
13492 while ((opt = nextopt("np")) != '\0') {
13494 flag_off = VEXPORT;
13497 if (argv[0][0] == 'r') {
13499 flag_off = 0; /* readonly ignores -n */
13501 flag_off = ~flag_off;
13503 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13509 p = strchr(name, '=');
13513 vp = *findvar(hashvar(name), name);
13515 vp->flags = ((vp->flags | flag) & flag_off);
13519 setvar(name, p, (flag & flag_off));
13520 } while ((name = *++aptr) != NULL);
13525 /* No arguments. Show the list of exported or readonly vars.
13528 showvars(argv[0], flag, 0);
13533 * Delete a function if it exists.
13536 unsetfunc(const char *name)
13538 struct tblentry *cmdp;
13540 cmdp = cmdlookup(name, 0);
13541 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13542 delete_cmd_entry();
13546 * The unset builtin command. We unset the function before we unset the
13547 * variable to allow a function to be unset when there is a readonly variable
13548 * with the same name.
13550 static int FAST_FUNC
13551 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13557 while ((i = nextopt("vf")) != 0) {
13561 for (ap = argptr; *ap; ap++) {
13572 static const unsigned char timescmd_str[] ALIGN1 = {
13573 ' ', offsetof(struct tms, tms_utime),
13574 '\n', offsetof(struct tms, tms_stime),
13575 ' ', offsetof(struct tms, tms_cutime),
13576 '\n', offsetof(struct tms, tms_cstime),
13579 static int FAST_FUNC
13580 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13583 const unsigned char *p;
13586 clk_tck = bb_clk_tck();
13591 unsigned sec, frac;
13593 t = *(clock_t *)(((char *) &buf) + p[1]);
13595 frac = t % clk_tck;
13596 out1fmt("%um%u.%03us%c",
13597 sec / 60, sec % 60,
13598 (frac * 1000) / clk_tck,
13606 #if ENABLE_FEATURE_SH_MATH
13608 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13609 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13611 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13613 static int FAST_FUNC
13614 letcmd(int argc UNUSED_PARAM, char **argv)
13620 ash_msg_and_raise_error("expression expected");
13622 i = ash_arith(*argv);
13630 * The read builtin. Options:
13631 * -r Do not interpret '\' specially
13632 * -s Turn off echo (tty only)
13633 * -n NCHARS Read NCHARS max
13634 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13635 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13636 * -u FD Read from given FD instead of fd 0
13637 * -d DELIM End on DELIM char, not newline
13638 * This uses unbuffered input, which may be avoidable in some cases.
13639 * TODO: bash also has:
13640 * -a ARRAY Read into array[0],[1],etc
13641 * -e Use line editing (tty only)
13643 static int FAST_FUNC
13644 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13646 char *opt_n = NULL;
13647 char *opt_p = NULL;
13648 char *opt_t = NULL;
13649 char *opt_u = NULL;
13650 char *opt_d = NULL; /* optimized out if !BASH */
13651 int read_flags = 0;
13655 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13664 read_flags |= BUILTIN_READ_SILENT;
13670 read_flags |= BUILTIN_READ_RAW;
13685 /* "read -s" needs to save/restore termios, can't allow ^C
13686 * to jump out of it.
13690 r = shell_builtin_read(setvar0,
13692 bltinlookup("IFS"), /* can be NULL */
13702 if ((uintptr_t)r == 1 && errno == EINTR) {
13703 /* To get SIGCHLD: sleep 1 & read x; echo $x
13704 * Correct behavior is to not exit "read"
13706 if (pending_sig == 0)
13710 if ((uintptr_t)r > 1)
13711 ash_msg_and_raise_error(r);
13713 return (uintptr_t)r;
13716 static int FAST_FUNC
13717 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13719 static const char permuser[3] ALIGN1 = "ogu";
13722 int symbolic_mode = 0;
13724 while (nextopt("S") != '\0') {
13733 if (*argptr == NULL) {
13734 if (symbolic_mode) {
13735 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13742 *p++ = permuser[i];
13744 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13745 if (!(mask & 0400)) *p++ = 'r';
13746 if (!(mask & 0200)) *p++ = 'w';
13747 if (!(mask & 0100)) *p++ = 'x';
13755 out1fmt("%04o\n", mask);
13758 char *modestr = *argptr;
13759 /* numeric umasks are taken as-is */
13760 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13761 if (!isdigit(modestr[0]))
13763 mask = bb_parse_mode(modestr, mask);
13764 if ((unsigned)mask > 0777) {
13765 ash_msg_and_raise_error("illegal mode: %s", modestr);
13767 if (!isdigit(modestr[0]))
13774 static int FAST_FUNC
13775 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13777 return shell_builtin_ulimit(argv);
13780 /* ============ main() and helpers */
13783 * Called to exit the shell.
13792 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13793 save_history(line_input_state);
13795 status = exitstatus;
13796 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13797 if (setjmp(loc.loc)) {
13798 if (exception_type == EXEXIT)
13799 status = exitstatus;
13802 exception_handler = &loc;
13808 /*free(p); - we'll exit soon */
13811 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13812 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13815 flush_stdout_stderr();
13820 /* Don't inline: conserve stack of caller from having our locals too */
13821 static NOINLINE void
13824 /* we will never free this */
13825 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13828 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13829 setsignal(SIGCHLD);
13831 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13832 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13834 signal(SIGHUP, SIG_DFL);
13841 for (envp = environ; envp && *envp; envp++) {
13843 * p = endofname(*envp);
13844 * if (p != *envp && *p == '=') {
13845 * here to weed out badly-named variables, but this breaks
13846 * scenarios where people do want them passed to children:
13848 * os.environ["test-test"]="test"
13849 * if os.fork() == 0:
13850 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
13851 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
13853 if (strchr(*envp, '=')) {
13854 setvareq(*envp, VEXPORT|VTEXTFIXED);
13858 setvareq((char*)defoptindvar, VTEXTFIXED);
13860 setvar0("PPID", utoa(getppid()));
13862 p = lookupvar("SHLVL");
13863 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13865 #if BASH_HOSTNAME_VAR
13866 if (!lookupvar("HOSTNAME")) {
13867 struct utsname uts;
13869 setvar0("HOSTNAME", uts.nodename);
13872 p = lookupvar("PWD");
13874 struct stat st1, st2;
13875 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13876 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13886 //usage:#define ash_trivial_usage
13887 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13888 //usage:#define ash_full_usage "\n\n"
13889 //usage: "Unix shell interpreter"
13892 * Process the shell command line arguments.
13895 procargs(char **argv)
13898 const char *xminusc;
13903 login_sh = xargv[0] && xargv[0][0] == '-';
13905 /* if (xargv[0]) - mmm, this is always true! */
13907 for (i = 0; i < NOPTS; i++)
13910 if (options(/*cmdline:*/ 1, &login_sh)) {
13911 /* it already printed err message */
13912 raise_exception(EXERROR);
13916 if (*xargv == NULL) {
13918 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13921 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13925 for (i = 0; i < NOPTS; i++)
13926 if (optlist[i] == 2)
13931 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13936 } else if (!sflag) {
13937 setinputfile(*xargv, 0);
13940 commandname = arg0;
13943 shellparam.p = xargv;
13944 #if ENABLE_ASH_GETOPTS
13945 shellparam.optind = 1;
13946 shellparam.optoff = -1;
13948 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13950 shellparam.nparam++;
13959 * Read /etc/profile, ~/.profile, $ENV.
13962 read_profile(const char *name)
13964 name = expandstr(name, DQSYNTAX);
13965 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13972 * This routine is called when an error or an interrupt occurs in an
13973 * interactive shell and control is returned to the main command loop.
13974 * (In dash, this function is auto-generated by build machinery).
13983 /* from expand.c: */
13986 /* from input.c: */
13987 g_parsefile->left_in_buffer = 0;
13988 g_parsefile->left_in_line = 0; /* clear input buffer */
13991 /* from redir.c: */
13995 unwindlocalvars(NULL);
13999 static short profile_buf[16384];
14000 extern int etext();
14004 * Main routine. We initialize things, parse the arguments, execute
14005 * profiles if we're a login shell, and then call cmdloop to execute
14006 * commands. The setjmp call sets up the location to jump to when an
14007 * exception occurs. When an exception occurs the variable "state"
14008 * is used to figure out how far we had gotten.
14010 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14011 int ash_main(int argc UNUSED_PARAM, char **argv)
14013 volatile smallint state;
14014 struct jmploc jmploc;
14015 struct stackmark smark;
14018 /* Initialize global data */
14022 #if ENABLE_ASH_ALIAS
14028 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14031 #if ENABLE_FEATURE_EDITING
14032 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
14035 if (setjmp(jmploc.loc)) {
14041 e = exception_type;
14043 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14047 newline_and_flush(stderr);
14050 popstackmark(&smark);
14051 FORCE_INT_ON; /* enable interrupts */
14060 exception_handler = &jmploc;
14061 rootpid = getpid();
14064 setstackmark(&smark);
14065 login_sh = procargs(argv);
14067 TRACE(("Shell args: "));
14068 trace_puts_args(argv);
14075 read_profile("/etc/profile");
14078 hp = lookupvar("HOME");
14080 read_profile("$HOME/.profile");
14086 getuid() == geteuid() && getgid() == getegid() &&
14090 const char *shinit = lookupvar("ENV");
14091 if (shinit != NULL && *shinit != '\0')
14092 read_profile(shinit);
14094 popstackmark(&smark);
14098 /* evalstring pushes parsefile stack.
14099 * Ensure we don't falsely claim that 0 (stdin)
14100 * is one of stacked source fds.
14101 * Testcase: ash -c 'exec 1>&0' must not complain. */
14102 // if (!sflag) g_parsefile->pf_fd = -1;
14103 // ^^ not necessary since now we special-case fd 0
14104 // in save_fd_on_redirect()
14105 evalstring(minusc, sflag ? 0 : EV_EXIT);
14108 if (sflag || minusc == NULL) {
14109 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14111 const char *hp = lookupvar("HISTFILE");
14113 hp = lookupvar("HOME");
14116 hp = concat_path_file(hp, ".ash_history");
14117 setvar0("HISTFILE", hp);
14120 hp = lookupvar("HISTFILE");
14124 line_input_state->hist_file = hp;
14125 # if ENABLE_FEATURE_SH_HISTFILESIZE
14126 hp = lookupvar("HISTFILESIZE");
14127 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14131 state4: /* XXX ??? - why isn't this before the "if" statement */
14139 extern void _mcleanup(void);
14143 TRACE(("End of main reached\n"));
14150 * Copyright (c) 1989, 1991, 1993, 1994
14151 * The Regents of the University of California. All rights reserved.
14153 * This code is derived from software contributed to Berkeley by
14154 * Kenneth Almquist.
14156 * Redistribution and use in source and binary forms, with or without
14157 * modification, are permitted provided that the following conditions
14159 * 1. Redistributions of source code must retain the above copyright
14160 * notice, this list of conditions and the following disclaimer.
14161 * 2. Redistributions in binary form must reproduce the above copyright
14162 * notice, this list of conditions and the following disclaimer in the
14163 * documentation and/or other materials provided with the distribution.
14164 * 3. Neither the name of the University nor the names of its contributors
14165 * may be used to endorse or promote products derived from this software
14166 * without specific prior written permission.
14168 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14169 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14170 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14171 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14172 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14173 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14174 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14175 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14176 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14177 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF