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.
20 * The following should be set to reflect the type of system you have:
21 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
26 * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
27 * debugging info will be written to ./trace and a quit signal
28 * will generate a core dump.
31 /* Tweak debug output verbosity here */
38 #define JOBS ENABLE_ASH_JOB_CONTROL
43 #include <sys/times.h>
45 #include "busybox.h" /* for applet_names */
48 #include "shell_common.h"
49 #if ENABLE_SH_MATH_SUPPORT
52 #if ENABLE_ASH_RANDOM_SUPPORT
55 # define CLEAR_RANDOM_T(rnd) ((void)0)
58 #include "NUM_APPLETS.h"
60 /* STANDALONE does not make sense, and won't compile */
61 # undef CONFIG_FEATURE_SH_STANDALONE
62 # undef ENABLE_FEATURE_SH_STANDALONE
63 # undef IF_FEATURE_SH_STANDALONE
64 # undef IF_NOT_FEATURE_SH_STANDALONE
65 # define ENABLE_FEATURE_SH_STANDALONE 0
66 # define IF_FEATURE_SH_STANDALONE(...)
67 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
71 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
75 # error "Do not even bother, ash will not run on NOMMU machine"
81 //config: depends on !NOMMU
83 //config: Tha 'ash' shell adds about 60k in the default configuration and is
84 //config: the most complete and most pedantically correct shell included with
85 //config: busybox. This shell is actually a derivative of the Debian 'dash'
86 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
87 //config: (written by Kenneth Almquist) from NetBSD.
89 //config:config ASH_BASH_COMPAT
90 //config: bool "bash-compatible extensions"
92 //config: depends on ASH
94 //config: Enable bash-compatible extensions.
96 //config:config ASH_IDLE_TIMEOUT
97 //config: bool "Idle timeout variable"
99 //config: depends on ASH
101 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
103 //config:config ASH_JOB_CONTROL
104 //config: bool "Job control"
106 //config: depends on ASH
108 //config: Enable job control in the ash shell.
110 //config:config ASH_ALIAS
111 //config: bool "Alias support"
113 //config: depends on ASH
115 //config: Enable alias support in the ash shell.
117 //config:config ASH_GETOPTS
118 //config: bool "Builtin getopt to parse positional parameters"
120 //config: depends on ASH
122 //config: Enable support for getopts builtin in ash.
124 //config:config ASH_BUILTIN_ECHO
125 //config: bool "Builtin version of 'echo'"
127 //config: depends on ASH
129 //config: Enable support for echo builtin in ash.
131 //config:config ASH_BUILTIN_PRINTF
132 //config: bool "Builtin version of 'printf'"
134 //config: depends on ASH
136 //config: Enable support for printf builtin in ash.
138 //config:config ASH_BUILTIN_TEST
139 //config: bool "Builtin version of 'test'"
141 //config: depends on ASH
143 //config: Enable support for test builtin in ash.
145 //config:config ASH_CMDCMD
146 //config: bool "'command' command to override shell builtins"
148 //config: depends on ASH
150 //config: Enable support for the ash 'command' builtin, which allows
151 //config: you to run the specified command with the specified arguments,
152 //config: even when there is an ash builtin command with the same name.
154 //config:config ASH_MAIL
155 //config: bool "Check for new mail on interactive shells"
157 //config: depends on ASH
159 //config: Enable "check for new mail" function in the ash shell.
161 //config:config ASH_OPTIMIZE_FOR_SIZE
162 //config: bool "Optimize for size instead of speed"
164 //config: depends on ASH
166 //config: Compile ash for reduced size at the price of speed.
168 //config:config ASH_RANDOM_SUPPORT
169 //config: bool "Pseudorandom generator and $RANDOM variable"
171 //config: depends on ASH
173 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
174 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
175 //config: You can reset the generator by using a specified start value.
176 //config: After "unset RANDOM" the generator will switch off and this
177 //config: variable will no longer have special treatment.
179 //config:config ASH_EXPAND_PRMT
180 //config: bool "Expand prompt string"
182 //config: depends on ASH
184 //config: "PS#" may contain volatile content, such as backquote commands.
185 //config: This option recreates the prompt string from the environment
186 //config: variable each time it is displayed.
189 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
190 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
191 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
193 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
194 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
197 /* ============ Hash table sizes. Configurable. */
201 #define CMDTABLESIZE 31 /* should be prime */
204 /* ============ Shell options */
206 static const char *const optletters_optnames
[] = {
221 #if ENABLE_ASH_BASH_COMPAT
230 #define optletters(n) optletters_optnames[n][0]
231 #define optnames(n) (optletters_optnames[n] + 1)
233 enum { NOPTS
= ARRAY_SIZE(optletters_optnames
) };
236 /* ============ Misc data */
238 #define msg_illnum "Illegal number: %s"
241 * We enclose jmp_buf in a structure so that we can declare pointers to
242 * jump locations. The global variable handler contains the location to
243 * jump to when an exception occurs, and the global variable exception_type
244 * contains a code identifying the exception. To implement nested
245 * exception handlers, the user should save the value of handler on entry
246 * to an inner scope, set handler to point to a jmploc structure for the
247 * inner scope, and restore handler on exit from the scope.
253 struct globals_misc
{
254 /* pid of main shell */
256 /* shell level: 0 for the main shell, 1 for its children, and so on */
258 #define rootshell (!shlvl)
259 char *minusc
; /* argument to -c option */
261 char *curdir
; // = nullstr; /* current working directory */
262 char *physdir
; // = nullstr; /* physical working directory */
264 char *arg0
; /* value of $0 */
266 struct jmploc
*exception_handler
;
268 volatile int suppress_int
; /* counter */
269 volatile /*sig_atomic_t*/ smallint pending_int
; /* 1 = got SIGINT */
270 /* last pending signal */
271 volatile /*sig_atomic_t*/ smallint pending_sig
;
272 smallint exception_type
; /* kind of exception (0..5) */
274 #define EXINT 0 /* SIGINT received */
275 #define EXERROR 1 /* a generic error */
276 #define EXSHELLPROC 2 /* execute a shell procedure */
277 #define EXEXEC 3 /* command execution failed */
278 #define EXEXIT 4 /* exit the shell */
279 #define EXSIG 5 /* trapped signal in wait(1) */
282 char nullstr
[1]; /* zero length string */
285 #define eflag optlist[0]
286 #define fflag optlist[1]
287 #define Iflag optlist[2]
288 #define iflag optlist[3]
289 #define mflag optlist[4]
290 #define nflag optlist[5]
291 #define sflag optlist[6]
292 #define xflag optlist[7]
293 #define vflag optlist[8]
294 #define Cflag optlist[9]
295 #define aflag optlist[10]
296 #define bflag optlist[11]
297 #define uflag optlist[12]
298 #define viflag optlist[13]
299 #if ENABLE_ASH_BASH_COMPAT
300 # define pipefail optlist[14]
305 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
306 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
309 /* trap handler commands */
311 * Sigmode records the current value of the signal handlers for the various
312 * modes. A value of zero means that the current handler is not known.
313 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
315 char sigmode
[NSIG
- 1];
316 #define S_DFL 1 /* default signal handling (SIG_DFL) */
317 #define S_CATCH 2 /* signal is caught */
318 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
319 #define S_HARD_IGN 4 /* signal is ignored permenantly */
321 /* indicates specified signal received */
322 uint8_t gotsig
[NSIG
- 1]; /* offset by 1: "signal" 0 is meaningless */
323 uint8_t may_have_traps
; /* 0: definitely no traps are set, 1: some traps may be set */
325 char **trap_ptr
; /* used only by "trap hack" */
327 /* Rarely referenced stuff */
328 #if ENABLE_ASH_RANDOM_SUPPORT
331 pid_t backgndpid
; /* pid of last background process */
332 smallint job_warning
; /* user was warned about stopped jobs (can be 2, 1 or 0). */
334 extern struct globals_misc
*const ash_ptr_to_globals_misc
;
335 #define G_misc (*ash_ptr_to_globals_misc)
336 #define rootpid (G_misc.rootpid )
337 #define shlvl (G_misc.shlvl )
338 #define minusc (G_misc.minusc )
339 #define curdir (G_misc.curdir )
340 #define physdir (G_misc.physdir )
341 #define arg0 (G_misc.arg0 )
342 #define exception_handler (G_misc.exception_handler)
343 #define exception_type (G_misc.exception_type )
344 #define suppress_int (G_misc.suppress_int )
345 #define pending_int (G_misc.pending_int )
346 #define pending_sig (G_misc.pending_sig )
347 #define isloginsh (G_misc.isloginsh )
348 #define nullstr (G_misc.nullstr )
349 #define optlist (G_misc.optlist )
350 #define sigmode (G_misc.sigmode )
351 #define gotsig (G_misc.gotsig )
352 #define may_have_traps (G_misc.may_have_traps )
353 #define trap (G_misc.trap )
354 #define trap_ptr (G_misc.trap_ptr )
355 #define random_gen (G_misc.random_gen )
356 #define backgndpid (G_misc.backgndpid )
357 #define job_warning (G_misc.job_warning)
358 #define INIT_G_misc() do { \
359 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
367 /* ============ DEBUG */
369 static void trace_printf(const char *fmt
, ...);
370 static void trace_vprintf(const char *fmt
, va_list va
);
371 # define TRACE(param) trace_printf param
372 # define TRACEV(param) trace_vprintf param
373 # define close(fd) do { \
375 if (close(dfd) < 0) \
376 bb_error_msg("bug on %d: closing %d(0x%x)", \
377 __LINE__, dfd, dfd); \
380 # define TRACE(param)
381 # define TRACEV(param)
385 /* ============ Utility functions */
386 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
388 static int isdigit_str9(const char *str
)
390 int maxlen
= 9 + 1; /* max 9 digits: 999999999 */
391 while (--maxlen
&& isdigit(*str
))
393 return (*str
== '\0');
396 static const char *var_end(const char *var
)
405 /* ============ Interrupts / exceptions */
407 static void exitshell(void) NORETURN
;
410 * These macros allow the user to suspend the handling of interrupt signals
411 * over a period of time. This is similar to SIGHOLD or to sigblock, but
412 * much more efficient and portable. (But hacking the kernel is so much
413 * more fun than worrying about efficiency and portability. :-))
415 #define INT_OFF do { \
421 * Called to raise an exception. Since C doesn't include exceptions, we
422 * just do a longjmp to the exception handler. The type of exception is
423 * stored in the global variable "exception_type".
425 static void raise_exception(int) NORETURN
;
427 raise_exception(int e
)
430 if (exception_handler
== NULL
)
435 longjmp(exception_handler
->loc
, 1);
438 #define raise_exception(e) do { \
439 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
440 raise_exception(e); \
445 * Called from trap.c when a SIGINT is received. (If the user specifies
446 * that SIGINT is to be trapped or ignored using the trap builtin, then
447 * this routine is not called.) Suppressint is nonzero when interrupts
448 * are held using the INT_OFF macro. (The test for iflag is just
449 * defensive programming.)
451 static void raise_interrupt(void) NORETURN
;
453 raise_interrupt(void)
458 /* Signal is not automatically unmasked after it is raised,
459 * do it ourself - unmask all signals */
460 sigprocmask_allsigs(SIG_UNBLOCK
);
461 /* pending_sig = 0; - now done in signal_handler() */
464 if (gotsig
[SIGINT
- 1] && !trap
[SIGINT
]) {
465 if (!(rootshell
&& iflag
)) {
466 /* Kill ourself with SIGINT */
467 signal(SIGINT
, SIG_DFL
);
472 raise_exception(ex_type
);
476 #define raise_interrupt() do { \
477 TRACE(("raising interrupt on line %d\n", __LINE__)); \
482 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
486 if (--suppress_int
== 0 && pending_int
) {
490 #define INT_ON int_on()
491 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
499 #define FORCE_INT_ON force_int_on()
501 #define SAVE_INT(v) ((v) = suppress_int)
503 #define RESTORE_INT(v) do { \
505 suppress_int = (v); \
506 if (suppress_int == 0 && pending_int) \
511 /* ============ Stdout/stderr output */
514 outstr(const char *p
, FILE *file
)
522 flush_stdout_stderr(void)
530 outcslow(int c
, FILE *dest
)
538 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__
,1,2)));
540 out1fmt(const char *fmt
, ...)
547 r
= vprintf(fmt
, ap
);
553 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__
,3,4)));
555 fmtstr(char *outbuf
, size_t length
, const char *fmt
, ...)
562 ret
= vsnprintf(outbuf
, length
, fmt
, ap
);
569 out1str(const char *p
)
575 out2str(const char *p
)
578 flush_stdout_stderr();
582 /* ============ Parser structures */
584 /* control characters in argument strings */
585 #define CTL_FIRST CTLESC
586 #define CTLESC ((unsigned char)'\201') /* escape next character */
587 #define CTLVAR ((unsigned char)'\202') /* variable defn */
588 #define CTLENDVAR ((unsigned char)'\203')
589 #define CTLBACKQ ((unsigned char)'\204')
590 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
591 /* CTLBACKQ | CTLQUOTE == '\205' */
592 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
593 #define CTLENDARI ((unsigned char)'\207')
594 #define CTLQUOTEMARK ((unsigned char)'\210')
595 #define CTL_LAST CTLQUOTEMARK
597 /* variable substitution byte (follows CTLVAR) */
598 #define VSTYPE 0x0f /* type of variable substitution */
599 #define VSNUL 0x10 /* colon--treat the empty string as unset */
600 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
602 /* values of VSTYPE field */
603 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
604 #define VSMINUS 0x2 /* ${var-text} */
605 #define VSPLUS 0x3 /* ${var+text} */
606 #define VSQUESTION 0x4 /* ${var?message} */
607 #define VSASSIGN 0x5 /* ${var=text} */
608 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
609 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
610 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
611 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
612 #define VSLENGTH 0xa /* ${#var} */
613 #if ENABLE_ASH_BASH_COMPAT
614 #define VSSUBSTR 0xc /* ${var:position:length} */
615 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
616 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
619 static const char dolatstr
[] ALIGN1
= {
620 CTLVAR
, VSNORMAL
|VSQUOTE
, '@', '=', '\0'
640 #if ENABLE_ASH_BASH_COMPAT
657 smallint type
; /* Nxxxx */
660 union node
*redirect
;
665 smallint pipe_backgnd
;
666 struct nodelist
*cmdlist
;
672 union node
*redirect
;
685 union node
*elsepart
;
712 struct nodelist
*backquote
;
715 /* nfile and ndup layout must match!
716 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
717 * that it is actually NTO2 (>&file), and change its type.
734 char *_unused_expfname
;
753 struct nredir nredir
;
754 struct nbinary nbinary
;
758 struct nclist nclist
;
767 * NODE_EOF is returned by parsecmd when it encounters an end of file.
768 * It must be distinct from NULL.
770 #define NODE_EOF ((union node *) -1L)
773 struct nodelist
*next
;
786 freefunc(struct funcnode
*f
)
788 if (f
&& --f
->count
< 0)
793 /* ============ Debugging output */
797 static FILE *tracefile
;
800 trace_printf(const char *fmt
, ...)
807 fprintf(tracefile
, "%u ", (int) time(NULL
));
809 fprintf(tracefile
, "[%u] ", (int) getpid());
811 fprintf(tracefile
, "pending s:%d i:%d(supp:%d) ", pending_sig
, pending_int
, suppress_int
);
813 vfprintf(tracefile
, fmt
, va
);
818 trace_vprintf(const char *fmt
, va_list va
)
823 fprintf(tracefile
, "%u ", (int) time(NULL
));
825 fprintf(tracefile
, "[%u] ", (int) getpid());
827 fprintf(tracefile
, "pending s:%d i:%d(supp:%d) ", pending_sig
, pending_int
, suppress_int
);
828 vfprintf(tracefile
, fmt
, va
);
832 trace_puts(const char *s
)
840 trace_puts_quoted(char *s
)
847 putc('"', tracefile
);
848 for (p
= s
; *p
; p
++) {
849 switch ((unsigned char)*p
) {
850 case '\n': c
= 'n'; goto backslash
;
851 case '\t': c
= 't'; goto backslash
;
852 case '\r': c
= 'r'; goto backslash
;
853 case '\"': c
= '\"'; goto backslash
;
854 case '\\': c
= '\\'; goto backslash
;
855 case CTLESC
: c
= 'e'; goto backslash
;
856 case CTLVAR
: c
= 'v'; goto backslash
;
857 case CTLVAR
+CTLQUOTE
: c
= 'V'; goto backslash
;
858 case CTLBACKQ
: c
= 'q'; goto backslash
;
859 case CTLBACKQ
+CTLQUOTE
: c
= 'Q'; goto backslash
;
861 putc('\\', tracefile
);
865 if (*p
>= ' ' && *p
<= '~')
868 putc('\\', tracefile
);
869 putc((*p
>> 6) & 03, tracefile
);
870 putc((*p
>> 3) & 07, tracefile
);
871 putc(*p
& 07, tracefile
);
876 putc('"', tracefile
);
880 trace_puts_args(char **ap
)
887 trace_puts_quoted(*ap
);
889 putc('\n', tracefile
);
892 putc(' ', tracefile
);
907 /* leave open because libedit might be using it */
910 strcpy(s
, "./trace");
912 if (!freopen(s
, "a", tracefile
)) {
913 fprintf(stderr
, "Can't re-open %s\n", s
);
918 tracefile
= fopen(s
, "a");
919 if (tracefile
== NULL
) {
920 fprintf(stderr
, "Can't open %s\n", s
);
926 flags
= fcntl(fileno(tracefile
), F_GETFL
);
928 fcntl(fileno(tracefile
), F_SETFL
, flags
| O_APPEND
);
930 setlinebuf(tracefile
);
931 fputs("\nTracing started.\n", tracefile
);
935 indent(int amount
, char *pfx
, FILE *fp
)
939 for (i
= 0; i
< amount
; i
++) {
940 if (pfx
&& i
== amount
- 1)
946 /* little circular references here... */
947 static void shtree(union node
*n
, int ind
, char *pfx
, FILE *fp
);
950 sharg(union node
*arg
, FILE *fp
)
953 struct nodelist
*bqlist
;
954 unsigned char subtype
;
956 if (arg
->type
!= NARG
) {
957 out1fmt("<node type %d>\n", arg
->type
);
960 bqlist
= arg
->narg
.backquote
;
961 for (p
= arg
->narg
.text
; *p
; p
++) {
962 switch ((unsigned char)*p
) {
971 if (subtype
== VSLENGTH
)
982 switch (subtype
& VSTYPE
) {
1008 case VSTRIMRIGHTMAX
:
1015 out1fmt("<subtype %d>", subtype
);
1022 case CTLBACKQ
|CTLQUOTE
:
1025 shtree(bqlist
->n
, -1, NULL
, fp
);
1036 shcmd(union node
*cmd
, FILE *fp
)
1044 for (np
= cmd
->ncmd
.args
; np
; np
= np
->narg
.next
) {
1050 for (np
= cmd
->ncmd
.redirect
; np
; np
= np
->nfile
.next
) {
1054 switch (np
->nfile
.type
) {
1055 case NTO
: s
= ">>"+1; dftfd
= 1; break;
1056 case NCLOBBER
: s
= ">|"; dftfd
= 1; break;
1057 case NAPPEND
: s
= ">>"; dftfd
= 1; break;
1058 #if ENABLE_ASH_BASH_COMPAT
1061 case NTOFD
: s
= ">&"; dftfd
= 1; break;
1062 case NFROM
: s
= "<"; break;
1063 case NFROMFD
: s
= "<&"; break;
1064 case NFROMTO
: s
= "<>"; break;
1065 default: s
= "*error*"; break;
1067 if (np
->nfile
.fd
!= dftfd
)
1068 fprintf(fp
, "%d", np
->nfile
.fd
);
1070 if (np
->nfile
.type
== NTOFD
|| np
->nfile
.type
== NFROMFD
) {
1071 fprintf(fp
, "%d", np
->ndup
.dupfd
);
1073 sharg(np
->nfile
.fname
, fp
);
1080 shtree(union node
*n
, int ind
, char *pfx
, FILE *fp
)
1082 struct nodelist
*lp
;
1088 indent(ind
, pfx
, fp
);
1090 if (n
== NODE_EOF
) {
1105 shtree(n
->nbinary
.ch1
, ind
, NULL
, fp
);
1108 shtree(n
->nbinary
.ch2
, ind
, NULL
, fp
);
1116 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
) {
1117 shtree(lp
->n
, 0, NULL
, fp
);
1121 if (n
->npipe
.pipe_backgnd
)
1127 fprintf(fp
, "<node type %d>", n
->type
);
1135 showtree(union node
*n
)
1137 trace_puts("showtree called\n");
1138 shtree(n
, 1, NULL
, stderr
);
1144 /* ============ Parser data */
1147 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1150 struct strlist
*next
;
1157 struct strpush
*prev
; /* preceding string on stack */
1159 int prev_left_in_line
;
1160 #if ENABLE_ASH_ALIAS
1161 struct alias
*ap
; /* if push was associated with an alias */
1163 char *string
; /* remember the string since it may change */
1167 struct parsefile
*prev
; /* preceding file on stack */
1168 int linno
; /* current line */
1169 int pf_fd
; /* file descriptor (or -1 if string) */
1170 int left_in_line
; /* number of chars left in this line */
1171 int left_in_buffer
; /* number of chars left in this buffer past the line */
1172 char *next_to_pgetc
; /* next char in buffer */
1173 char *buf
; /* input buffer */
1174 struct strpush
*strpush
; /* for pushing strings at this level */
1175 struct strpush basestrpush
; /* so pushing one is fast */
1178 static struct parsefile basepf
; /* top level input file */
1179 static struct parsefile
*g_parsefile
= &basepf
; /* current input file */
1180 static int startlinno
; /* line # where last token started */
1181 static char *commandname
; /* currently executing command */
1182 static struct strlist
*cmdenviron
; /* environment for builtin command */
1183 static uint8_t exitstatus
; /* exit status of last command */
1186 /* ============ Message printing */
1189 ash_vmsg(const char *msg
, va_list ap
)
1191 fprintf(stderr
, "%s: ", arg0
);
1193 if (strcmp(arg0
, commandname
))
1194 fprintf(stderr
, "%s: ", commandname
);
1195 if (!iflag
|| g_parsefile
->pf_fd
> 0)
1196 fprintf(stderr
, "line %d: ", startlinno
);
1198 vfprintf(stderr
, msg
, ap
);
1199 outcslow('\n', stderr
);
1203 * Exverror is called to raise the error exception. If the second argument
1204 * is not NULL then error prints an error message using printf style
1205 * formatting. It then raises the error exception.
1207 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN
;
1209 ash_vmsg_and_raise(int cond
, const char *msg
, va_list ap
)
1213 TRACE(("ash_vmsg_and_raise(%d, \"", cond
));
1215 TRACE(("\") pid=%d\n", getpid()));
1217 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond
, getpid()));
1222 flush_stdout_stderr();
1223 raise_exception(cond
);
1227 static void ash_msg_and_raise_error(const char *, ...) NORETURN
;
1229 ash_msg_and_raise_error(const char *msg
, ...)
1234 ash_vmsg_and_raise(EXERROR
, msg
, ap
);
1239 static void raise_error_syntax(const char *) NORETURN
;
1241 raise_error_syntax(const char *msg
)
1243 ash_msg_and_raise_error("syntax error: %s", msg
);
1247 static void ash_msg_and_raise(int, const char *, ...) NORETURN
;
1249 ash_msg_and_raise(int cond
, const char *msg
, ...)
1254 ash_vmsg_and_raise(cond
, msg
, ap
);
1260 * error/warning routines for external builtins
1263 ash_msg(const char *fmt
, ...)
1273 * Return a string describing an error. The returned string may be a
1274 * pointer to a static buffer that will be overwritten on the next call.
1275 * Action describes the operation that got the error.
1278 errmsg(int e
, const char *em
)
1280 if (e
== ENOENT
|| e
== ENOTDIR
) {
1287 /* ============ Memory allocation */
1290 /* I consider these wrappers nearly useless:
1291 * ok, they return you to nearest exception handler, but
1292 * how much memory do you leak in the process, making
1293 * memory starvation worse?
1296 ckrealloc(void * p
, size_t nbytes
)
1298 p
= realloc(p
, nbytes
);
1300 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1305 ckmalloc(size_t nbytes
)
1307 return ckrealloc(NULL
, nbytes
);
1311 ckzalloc(size_t nbytes
)
1313 return memset(ckmalloc(nbytes
), 0, nbytes
);
1317 ckstrdup(const char *s
)
1319 char *p
= strdup(s
);
1321 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1325 /* Using bbox equivalents. They exit if out of memory */
1326 # define ckrealloc xrealloc
1327 # define ckmalloc xmalloc
1328 # define ckzalloc xzalloc
1329 # define ckstrdup xstrdup
1333 * It appears that grabstackstr() will barf with such alignments
1334 * because stalloc() will return a string allocated in a new stackblock.
1336 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1338 /* Most machines require the value returned from malloc to be aligned
1339 * in some way. The following macro will get this right
1340 * on many machines. */
1341 SHELL_SIZE
= sizeof(union { int i
; char *cp
; double d
; }) - 1,
1342 /* Minimum size of a block */
1343 MINSIZE
= SHELL_ALIGN(504),
1346 struct stack_block
{
1347 struct stack_block
*prev
;
1348 char space
[MINSIZE
];
1352 struct stack_block
*stackp
;
1355 struct stackmark
*marknext
;
1359 struct globals_memstack
{
1360 struct stack_block
*g_stackp
; // = &stackbase;
1361 struct stackmark
*markp
;
1362 char *g_stacknxt
; // = stackbase.space;
1363 char *sstrend
; // = stackbase.space + MINSIZE;
1364 size_t g_stacknleft
; // = MINSIZE;
1365 int herefd
; // = -1;
1366 struct stack_block stackbase
;
1368 extern struct globals_memstack
*const ash_ptr_to_globals_memstack
;
1369 #define G_memstack (*ash_ptr_to_globals_memstack)
1370 #define g_stackp (G_memstack.g_stackp )
1371 #define markp (G_memstack.markp )
1372 #define g_stacknxt (G_memstack.g_stacknxt )
1373 #define sstrend (G_memstack.sstrend )
1374 #define g_stacknleft (G_memstack.g_stacknleft)
1375 #define herefd (G_memstack.herefd )
1376 #define stackbase (G_memstack.stackbase )
1377 #define INIT_G_memstack() do { \
1378 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1380 g_stackp = &stackbase; \
1381 g_stacknxt = stackbase.space; \
1382 g_stacknleft = MINSIZE; \
1383 sstrend = stackbase.space + MINSIZE; \
1388 #define stackblock() ((void *)g_stacknxt)
1389 #define stackblocksize() g_stacknleft
1392 * Parse trees for commands are allocated in lifo order, so we use a stack
1393 * to make this more efficient, and also to avoid all sorts of exception
1394 * handling code to handle interrupts in the middle of a parse.
1396 * The size 504 was chosen because the Ultrix malloc handles that size
1400 stalloc(size_t nbytes
)
1405 aligned
= SHELL_ALIGN(nbytes
);
1406 if (aligned
> g_stacknleft
) {
1409 struct stack_block
*sp
;
1411 blocksize
= aligned
;
1412 if (blocksize
< MINSIZE
)
1413 blocksize
= MINSIZE
;
1414 len
= sizeof(struct stack_block
) - MINSIZE
+ blocksize
;
1415 if (len
< blocksize
)
1416 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1419 sp
->prev
= g_stackp
;
1420 g_stacknxt
= sp
->space
;
1421 g_stacknleft
= blocksize
;
1422 sstrend
= g_stacknxt
+ blocksize
;
1427 g_stacknxt
+= aligned
;
1428 g_stacknleft
-= aligned
;
1433 stzalloc(size_t nbytes
)
1435 return memset(stalloc(nbytes
), 0, nbytes
);
1442 if (!p
|| (g_stacknxt
< (char *)p
) || ((char *)p
< g_stackp
->space
)) {
1443 write(STDERR_FILENO
, "stunalloc\n", 10);
1447 g_stacknleft
+= g_stacknxt
- (char *)p
;
1452 * Like strdup but works with the ash stack.
1455 ststrdup(const char *p
)
1457 size_t len
= strlen(p
) + 1;
1458 return memcpy(stalloc(len
), p
, len
);
1462 setstackmark(struct stackmark
*mark
)
1464 mark
->stackp
= g_stackp
;
1465 mark
->stacknxt
= g_stacknxt
;
1466 mark
->stacknleft
= g_stacknleft
;
1467 mark
->marknext
= markp
;
1472 popstackmark(struct stackmark
*mark
)
1474 struct stack_block
*sp
;
1480 markp
= mark
->marknext
;
1481 while (g_stackp
!= mark
->stackp
) {
1483 g_stackp
= sp
->prev
;
1486 g_stacknxt
= mark
->stacknxt
;
1487 g_stacknleft
= mark
->stacknleft
;
1488 sstrend
= mark
->stacknxt
+ mark
->stacknleft
;
1493 * When the parser reads in a string, it wants to stick the string on the
1494 * stack and only adjust the stack pointer when it knows how big the
1495 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1496 * of space on top of the stack and stackblocklen returns the length of
1497 * this block. Growstackblock will grow this space by at least one byte,
1498 * possibly moving it (like realloc). Grabstackblock actually allocates the
1499 * part of the block that has been used.
1502 growstackblock(void)
1506 newlen
= g_stacknleft
* 2;
1507 if (newlen
< g_stacknleft
)
1508 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1512 if (g_stacknxt
== g_stackp
->space
&& g_stackp
!= &stackbase
) {
1513 struct stack_block
*oldstackp
;
1514 struct stackmark
*xmark
;
1515 struct stack_block
*sp
;
1516 struct stack_block
*prevstackp
;
1520 oldstackp
= g_stackp
;
1522 prevstackp
= sp
->prev
;
1523 grosslen
= newlen
+ sizeof(struct stack_block
) - MINSIZE
;
1524 sp
= ckrealloc(sp
, grosslen
);
1525 sp
->prev
= prevstackp
;
1527 g_stacknxt
= sp
->space
;
1528 g_stacknleft
= newlen
;
1529 sstrend
= sp
->space
+ newlen
;
1532 * Stack marks pointing to the start of the old block
1533 * must be relocated to point to the new block
1536 while (xmark
!= NULL
&& xmark
->stackp
== oldstackp
) {
1537 xmark
->stackp
= g_stackp
;
1538 xmark
->stacknxt
= g_stacknxt
;
1539 xmark
->stacknleft
= g_stacknleft
;
1540 xmark
= xmark
->marknext
;
1544 char *oldspace
= g_stacknxt
;
1545 size_t oldlen
= g_stacknleft
;
1546 char *p
= stalloc(newlen
);
1548 /* free the space we just allocated */
1549 g_stacknxt
= memcpy(p
, oldspace
, oldlen
);
1550 g_stacknleft
+= newlen
;
1555 grabstackblock(size_t len
)
1557 len
= SHELL_ALIGN(len
);
1559 g_stacknleft
-= len
;
1563 * The following routines are somewhat easier to use than the above.
1564 * The user declares a variable of type STACKSTR, which may be declared
1565 * to be a register. The macro STARTSTACKSTR initializes things. Then
1566 * the user uses the macro STPUTC to add characters to the string. In
1567 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1568 * grown as necessary. When the user is done, she can just leave the
1569 * string there and refer to it using stackblock(). Or she can allocate
1570 * the space for it using grabstackstr(). If it is necessary to allow
1571 * someone else to use the stack temporarily and then continue to grow
1572 * the string, the user should use grabstack to allocate the space, and
1573 * then call ungrabstr(p) to return to the previous mode of operation.
1575 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1576 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1577 * is space for at least one character.
1582 size_t len
= stackblocksize();
1583 if (herefd
>= 0 && len
>= 1024) {
1584 full_write(herefd
, stackblock(), len
);
1585 return stackblock();
1588 return (char *)stackblock() + len
;
1592 * Called from CHECKSTRSPACE.
1595 makestrspace(size_t newlen
, char *p
)
1597 size_t len
= p
- g_stacknxt
;
1598 size_t size
= stackblocksize();
1603 size
= stackblocksize();
1605 if (nleft
>= newlen
)
1609 return (char *)stackblock() + len
;
1613 stack_nputstr(const char *s
, size_t n
, char *p
)
1615 p
= makestrspace(n
, p
);
1616 p
= (char *)memcpy(p
, s
, n
) + n
;
1621 stack_putstr(const char *s
, char *p
)
1623 return stack_nputstr(s
, strlen(s
), p
);
1627 _STPUTC(int c
, char *p
)
1635 #define STARTSTACKSTR(p) ((p) = stackblock())
1636 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1637 #define CHECKSTRSPACE(n, p) do { \
1640 size_t m = sstrend - q; \
1642 (p) = makestrspace(l, q); \
1644 #define USTPUTC(c, p) (*(p)++ = (c))
1645 #define STACKSTRNUL(p) do { \
1646 if ((p) == sstrend) \
1647 (p) = growstackstr(); \
1650 #define STUNPUTC(p) (--(p))
1651 #define STTOPC(p) ((p)[-1])
1652 #define STADJUST(amount, p) ((p) += (amount))
1654 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1655 #define ungrabstackstr(s, p) stunalloc(s)
1656 #define stackstrend() ((void *)sstrend)
1659 /* ============ String helpers */
1662 * prefix -- see if pfx is a prefix of string.
1665 prefix(const char *string
, const char *pfx
)
1668 if (*pfx
++ != *string
++)
1671 return (char *) string
;
1675 * Check for a valid number. This should be elsewhere.
1678 is_number(const char *p
)
1683 } while (*++p
!= '\0');
1688 * Convert a string of digits to an integer, printing an error message on
1692 number(const char *s
)
1695 ash_msg_and_raise_error(msg_illnum
, s
);
1700 * Produce a possibly single quoted string suitable as input to the shell.
1701 * The return string is allocated on the stack.
1704 single_quote(const char *s
)
1714 len
= strchrnul(s
, '\'') - s
;
1716 q
= p
= makestrspace(len
+ 3, p
);
1719 q
= (char *)memcpy(q
, s
, len
) + len
;
1728 do len
++; while (*++s
== '\'');
1730 q
= p
= makestrspace(len
+ 3, p
);
1733 q
= (char *)memcpy(q
, s
- len
, len
) + len
;
1741 return stackblock();
1745 /* ============ nextopt */
1747 static char **argptr
; /* argument list for builtin commands */
1748 static char *optionarg
; /* set by nextopt (like getopt) */
1749 static char *optptr
; /* used by nextopt */
1752 * XXX - should get rid of. Have all builtins use getopt(3).
1753 * The library getopt must have the BSD extension static variable
1754 * "optreset", otherwise it can't be used within the shell safely.
1756 * Standard option processing (a la getopt) for builtin routines.
1757 * The only argument that is passed to nextopt is the option string;
1758 * the other arguments are unnecessary. It returns the character,
1759 * or '\0' on end of input.
1762 nextopt(const char *optstring
)
1769 if (p
== NULL
|| *p
== '\0') {
1770 /* We ate entire "-param", take next one */
1776 if (*++p
== '\0') /* just "-" ? */
1779 if (LONE_DASH(p
)) /* "--" ? */
1781 /* p => next "-param" */
1783 /* p => some option char in the middle of a "-param" */
1785 for (q
= optstring
; *q
!= c
;) {
1787 ash_msg_and_raise_error("illegal option -%c", c
);
1795 ash_msg_and_raise_error("no arg for -%c option", c
);
1805 /* ============ Shell variables */
1808 * The parsefile structure pointed to by the global variable parsefile
1809 * contains information about the current file being read.
1812 int nparam
; /* # of positional parameters (without $0) */
1813 #if ENABLE_ASH_GETOPTS
1814 int optind
; /* next parameter to be processed by getopts */
1815 int optoff
; /* used by getopts */
1817 unsigned char malloced
; /* if parameter list dynamically allocated */
1818 char **p
; /* parameter list */
1822 * Free the list of positional parameters.
1825 freeparam(volatile struct shparam
*param
)
1827 if (param
->malloced
) {
1829 ap
= ap1
= param
->p
;
1836 #if ENABLE_ASH_GETOPTS
1837 static void FAST_FUNC
getoptsreset(const char *value
);
1841 struct var
*next
; /* next entry in hash list */
1842 int flags
; /* flags are defined above */
1843 const char *var_text
; /* name=value */
1844 void (*var_func
)(const char *) FAST_FUNC
; /* function to be called when */
1845 /* the variable gets set/unset */
1849 struct localvar
*next
; /* next local variable in list */
1850 struct var
*vp
; /* the variable that was made local */
1851 int flags
; /* saved flags */
1852 const char *text
; /* saved text */
1856 #define VEXPORT 0x01 /* variable is exported */
1857 #define VREADONLY 0x02 /* variable cannot be modified */
1858 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1859 #define VTEXTFIXED 0x08 /* text is statically allocated */
1860 #define VSTACK 0x10 /* text is allocated on the stack */
1861 #define VUNSET 0x20 /* the variable is not set */
1862 #define VNOFUNC 0x40 /* don't call the callback function */
1863 #define VNOSET 0x80 /* do not set variable - just readonly test */
1864 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1865 #if ENABLE_ASH_RANDOM_SUPPORT
1866 # define VDYNAMIC 0x200 /* dynamic variable */
1872 /* Need to be before varinit_data[] */
1873 #if ENABLE_LOCALE_SUPPORT
1874 static void FAST_FUNC
1875 change_lc_all(const char *value
)
1877 if (value
&& *value
!= '\0')
1878 setlocale(LC_ALL
, value
);
1880 static void FAST_FUNC
1881 change_lc_ctype(const char *value
)
1883 if (value
&& *value
!= '\0')
1884 setlocale(LC_CTYPE
, value
);
1888 static void chkmail(void);
1889 static void changemail(const char *var_value
) FAST_FUNC
;
1891 # define chkmail() ((void)0)
1893 static void changepath(const char *) FAST_FUNC
;
1894 #if ENABLE_ASH_RANDOM_SUPPORT
1895 static void change_random(const char *) FAST_FUNC
;
1898 static const struct {
1900 const char *var_text
;
1901 void (*var_func
)(const char *) FAST_FUNC
;
1902 } varinit_data
[] = {
1904 * Note: VEXPORT would not work correctly here for NOFORK applets:
1905 * some environment strings may be constant.
1907 { VSTRFIXED
|VTEXTFIXED
, defifsvar
, NULL
},
1909 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "MAIL" , changemail
},
1910 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "MAILPATH" , changemail
},
1912 { VSTRFIXED
|VTEXTFIXED
, bb_PATH_root_path
, changepath
},
1913 { VSTRFIXED
|VTEXTFIXED
, "PS1=$ " , NULL
},
1914 { VSTRFIXED
|VTEXTFIXED
, "PS2=> " , NULL
},
1915 { VSTRFIXED
|VTEXTFIXED
, "PS4=+ " , NULL
},
1916 #if ENABLE_ASH_GETOPTS
1917 { VSTRFIXED
|VTEXTFIXED
, "OPTIND=1" , getoptsreset
},
1919 #if ENABLE_ASH_RANDOM_SUPPORT
1920 { VSTRFIXED
|VTEXTFIXED
|VUNSET
|VDYNAMIC
, "RANDOM", change_random
},
1922 #if ENABLE_LOCALE_SUPPORT
1923 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "LC_ALL" , change_lc_all
},
1924 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "LC_CTYPE" , change_lc_ctype
},
1926 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1927 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "HISTFILE" , NULL
},
1933 struct globals_var
{
1934 struct shparam shellparam
; /* $@ current positional parameters */
1935 struct redirtab
*redirlist
;
1937 int preverrout_fd
; /* save fd2 before print debug if xflag is set. */
1938 struct var
*vartab
[VTABSIZE
];
1939 struct var varinit
[ARRAY_SIZE(varinit_data
)];
1941 extern struct globals_var
*const ash_ptr_to_globals_var
;
1942 #define G_var (*ash_ptr_to_globals_var)
1943 #define shellparam (G_var.shellparam )
1944 //#define redirlist (G_var.redirlist )
1945 #define g_nullredirs (G_var.g_nullredirs )
1946 #define preverrout_fd (G_var.preverrout_fd)
1947 #define vartab (G_var.vartab )
1948 #define varinit (G_var.varinit )
1949 #define INIT_G_var() do { \
1951 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1953 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1954 varinit[i].flags = varinit_data[i].flags; \
1955 varinit[i].var_text = varinit_data[i].var_text; \
1956 varinit[i].var_func = varinit_data[i].var_func; \
1960 #define vifs varinit[0]
1962 # define vmail (&vifs)[1]
1963 # define vmpath (&vmail)[1]
1964 # define vpath (&vmpath)[1]
1966 # define vpath (&vifs)[1]
1968 #define vps1 (&vpath)[1]
1969 #define vps2 (&vps1)[1]
1970 #define vps4 (&vps2)[1]
1971 #if ENABLE_ASH_GETOPTS
1972 # define voptind (&vps4)[1]
1973 # if ENABLE_ASH_RANDOM_SUPPORT
1974 # define vrandom (&voptind)[1]
1977 # if ENABLE_ASH_RANDOM_SUPPORT
1978 # define vrandom (&vps4)[1]
1983 * The following macros access the values of the above variables.
1984 * They have to skip over the name. They return the null string
1985 * for unset variables.
1987 #define ifsval() (vifs.var_text + 4)
1988 #define ifsset() ((vifs.flags & VUNSET) == 0)
1990 # define mailval() (vmail.var_text + 5)
1991 # define mpathval() (vmpath.var_text + 9)
1992 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1994 #define pathval() (vpath.var_text + 5)
1995 #define ps1val() (vps1.var_text + 4)
1996 #define ps2val() (vps2.var_text + 4)
1997 #define ps4val() (vps4.var_text + 4)
1998 #if ENABLE_ASH_GETOPTS
1999 # define optindval() (voptind.var_text + 7)
2002 #if ENABLE_ASH_GETOPTS
2003 static void FAST_FUNC
2004 getoptsreset(const char *value
)
2006 shellparam
.optind
= number(value
);
2007 shellparam
.optoff
= -1;
2011 /* math.h has these, otherwise define our private copies */
2012 #if !ENABLE_SH_MATH_SUPPORT
2013 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2014 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2016 * Return the pointer to the first char which is not part of a legal variable name
2017 * (a letter or underscore followed by letters, underscores, and digits).
2020 endofname(const char *name
)
2022 if (!is_name(*name
))
2025 if (!is_in_name(*name
))
2033 * Compares two strings up to the first = or '\0'. The first
2034 * string must be terminated by '='; the second may be terminated by
2035 * either '=' or '\0'.
2038 varcmp(const char *p
, const char *q
)
2042 while ((c
= *p
) == (d
= *q
)) {
2057 * Find the appropriate entry in the hash table from the name.
2059 static struct var
**
2060 hashvar(const char *p
)
2064 hashval
= ((unsigned char) *p
) << 4;
2065 while (*p
&& *p
!= '=')
2066 hashval
+= (unsigned char) *p
++;
2067 return &vartab
[hashval
% VTABSIZE
];
2071 vpcmp(const void *a
, const void *b
)
2073 return varcmp(*(const char **)a
, *(const char **)b
);
2077 * This routine initializes the builtin variables.
2087 * PS1 depends on uid
2089 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2090 vps1
.var_text
= "PS1=\\w \\$ ";
2093 vps1
.var_text
= "PS1=# ";
2096 end
= vp
+ ARRAY_SIZE(varinit
);
2098 vpp
= hashvar(vp
->var_text
);
2101 } while (++vp
< end
);
2104 static struct var
**
2105 findvar(struct var
**vpp
, const char *name
)
2107 for (; *vpp
; vpp
= &(*vpp
)->next
) {
2108 if (varcmp((*vpp
)->var_text
, name
) == 0) {
2116 * Find the value of a variable. Returns NULL if not set.
2118 static const char* FAST_FUNC
2119 lookupvar(const char *name
)
2123 v
= *findvar(hashvar(name
), name
);
2125 #if ENABLE_ASH_RANDOM_SUPPORT
2127 * Dynamic variables are implemented roughly the same way they are
2128 * in bash. Namely, they're "special" so long as they aren't unset.
2129 * As soon as they're unset, they're no longer dynamic, and dynamic
2130 * lookup will no longer happen at that point. -- PFM.
2132 if (v
->flags
& VDYNAMIC
)
2135 if (!(v
->flags
& VUNSET
))
2136 return var_end(v
->var_text
);
2142 * Search the environment of a builtin command.
2145 bltinlookup(const char *name
)
2149 for (sp
= cmdenviron
; sp
; sp
= sp
->next
) {
2150 if (varcmp(sp
->text
, name
) == 0)
2151 return var_end(sp
->text
);
2153 return lookupvar(name
);
2157 * Same as setvar except that the variable and value are passed in
2158 * the first argument as name=value. Since the first argument will
2159 * be actually stored in the table, it should not be a string that
2161 * Called with interrupts off.
2164 setvareq(char *s
, int flags
)
2166 struct var
*vp
, **vpp
;
2169 flags
|= (VEXPORT
& (((unsigned) (1 - aflag
)) - 1));
2170 vp
= *findvar(vpp
, s
);
2172 if ((vp
->flags
& (VREADONLY
|VDYNAMIC
)) == VREADONLY
) {
2175 if (flags
& VNOSAVE
)
2178 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n
, '=') - n
, n
);
2184 if (vp
->var_func
&& !(flags
& VNOFUNC
))
2185 vp
->var_func(var_end(s
));
2187 if (!(vp
->flags
& (VTEXTFIXED
|VSTACK
)))
2188 free((char*)vp
->var_text
);
2190 flags
|= vp
->flags
& ~(VTEXTFIXED
|VSTACK
|VNOSAVE
|VUNSET
);
2192 /* variable s is not found */
2195 vp
= ckzalloc(sizeof(*vp
));
2197 /*vp->func = NULL; - ckzalloc did it */
2200 if (!(flags
& (VTEXTFIXED
|VSTACK
|VNOSAVE
)))
2207 * Set the value of a variable. The flags argument is ored with the
2208 * flags of the variable. If val is NULL, the variable is unset.
2211 setvar(const char *name
, const char *val
, int flags
)
2219 q
= endofname(name
);
2220 p
= strchrnul(q
, '=');
2222 if (!namelen
|| p
!= q
)
2223 ash_msg_and_raise_error("%.*s: bad variable name", namelen
, name
);
2228 vallen
= strlen(val
);
2232 nameeq
= ckmalloc(namelen
+ vallen
+ 2);
2233 p
= memcpy(nameeq
, name
, namelen
) + namelen
;
2236 p
= memcpy(p
, val
, vallen
) + vallen
;
2239 setvareq(nameeq
, flags
| VNOSAVE
);
2243 static void FAST_FUNC
2244 setvar2(const char *name
, const char *val
)
2246 setvar(name
, val
, 0);
2249 #if ENABLE_ASH_GETOPTS
2251 * Safe version of setvar, returns 1 on success 0 on failure.
2254 setvarsafe(const char *name
, const char *val
, int flags
)
2257 volatile int saveint
;
2258 struct jmploc
*volatile savehandler
= exception_handler
;
2259 struct jmploc jmploc
;
2262 if (setjmp(jmploc
.loc
))
2265 exception_handler
= &jmploc
;
2266 setvar(name
, val
, flags
);
2269 exception_handler
= savehandler
;
2270 RESTORE_INT(saveint
);
2276 * Unset the specified variable.
2279 unsetvar(const char *s
)
2285 vpp
= findvar(hashvar(s
), s
);
2289 int flags
= vp
->flags
;
2292 if (flags
& VREADONLY
)
2294 #if ENABLE_ASH_RANDOM_SUPPORT
2295 vp
->flags
&= ~VDYNAMIC
;
2299 if ((flags
& VSTRFIXED
) == 0) {
2301 if ((flags
& (VTEXTFIXED
|VSTACK
)) == 0)
2302 free((char*)vp
->var_text
);
2308 vp
->flags
&= ~VEXPORT
;
2318 * Process a linked list of variable assignments.
2321 listsetvar(struct strlist
*list_set_var
, int flags
)
2323 struct strlist
*lp
= list_set_var
;
2329 setvareq(lp
->text
, flags
);
2336 * Generate a list of variables satisfying the given conditions.
2339 listvars(int on
, int off
, char ***end
)
2350 for (vp
= *vpp
; vp
; vp
= vp
->next
) {
2351 if ((vp
->flags
& mask
) == on
) {
2352 if (ep
== stackstrend())
2353 ep
= growstackstr();
2354 *ep
++ = (char*)vp
->var_text
;
2357 } while (++vpp
< vartab
+ VTABSIZE
);
2358 if (ep
== stackstrend())
2359 ep
= growstackstr();
2363 return grabstackstr(ep
);
2367 /* ============ Path search helper
2369 * The variable path (passed by reference) should be set to the start
2370 * of the path before the first call; path_advance will update
2371 * this value as it proceeds. Successive calls to path_advance will return
2372 * the possible path expansions in sequence. If an option (indicated by
2373 * a percent sign) appears in the path entry then the global variable
2374 * pathopt will be set to point to it; otherwise pathopt will be set to
2377 static const char *pathopt
; /* set by path_advance */
2380 path_advance(const char **path
, const char *name
)
2390 for (p
= start
; *p
&& *p
!= ':' && *p
!= '%'; p
++)
2392 len
= p
- start
+ strlen(name
) + 2; /* "2" is for '/' and '\0' */
2393 while (stackblocksize() < len
)
2397 memcpy(q
, start
, p
- start
);
2405 while (*p
&& *p
!= ':')
2412 return stalloc(len
);
2416 /* ============ Prompt */
2418 static smallint doprompt
; /* if set, prompt the user */
2419 static smallint needprompt
; /* true if interactive and at start of line */
2421 #if ENABLE_FEATURE_EDITING
2422 static line_input_t
*line_input_state
;
2423 static const char *cmdedit_prompt
;
2425 putprompt(const char *s
)
2427 if (ENABLE_ASH_EXPAND_PRMT
) {
2428 free((char*)cmdedit_prompt
);
2429 cmdedit_prompt
= ckstrdup(s
);
2436 putprompt(const char *s
)
2442 #if ENABLE_ASH_EXPAND_PRMT
2443 /* expandstr() needs parsing machinery, so it is far away ahead... */
2444 static const char *expandstr(const char *ps
);
2446 #define expandstr(s) s
2450 setprompt_if(smallint do_set
, int whichprompt
)
2453 IF_ASH_EXPAND_PRMT(struct stackmark smark
;)
2460 switch (whichprompt
) {
2470 #if ENABLE_ASH_EXPAND_PRMT
2471 setstackmark(&smark
);
2472 stalloc(stackblocksize());
2474 putprompt(expandstr(prompt
));
2475 #if ENABLE_ASH_EXPAND_PRMT
2476 popstackmark(&smark
);
2481 /* ============ The cd and pwd commands */
2483 #define CD_PHYSICAL 1
2493 while ((i
= nextopt("LP")) != '\0') {
2495 flags
^= CD_PHYSICAL
;
2504 * Update curdir (the name of the current directory) in response to a
2508 updatepwd(const char *dir
)
2515 cdcomppath
= ststrdup(dir
);
2518 if (curdir
== nullstr
)
2520 new = stack_putstr(curdir
, new);
2522 new = makestrspace(strlen(dir
) + 2, new);
2523 lim
= (char *)stackblock() + 1;
2527 if (new > lim
&& *lim
== '/')
2532 if (dir
[1] == '/' && dir
[2] != '/') {
2538 p
= strtok(cdcomppath
, "/");
2542 if (p
[1] == '.' && p
[2] == '\0') {
2554 new = stack_putstr(p
, new);
2562 return stackblock();
2566 * Find out what the current directory is. If we already know the current
2567 * directory, this routine returns immediately.
2572 char *dir
= getcwd(NULL
, 0); /* huh, using glibc extension? */
2573 return dir
? dir
: nullstr
;
2577 setpwd(const char *val
, int setold
)
2581 oldcur
= dir
= curdir
;
2584 setvar("OLDPWD", oldcur
, VEXPORT
);
2587 if (physdir
!= nullstr
) {
2588 if (physdir
!= oldcur
)
2592 if (oldcur
== val
|| !val
) {
2598 dir
= ckstrdup(val
);
2599 if (oldcur
!= dir
&& oldcur
!= nullstr
) {
2604 setvar("PWD", dir
, VEXPORT
);
2607 static void hashcd(void);
2610 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2611 * know that the current directory has changed.
2614 docd(const char *dest
, int flags
)
2616 const char *dir
= NULL
;
2619 TRACE(("docd(\"%s\", %d) called\n", dest
, flags
));
2622 if (!(flags
& CD_PHYSICAL
)) {
2623 dir
= updatepwd(dest
);
2637 static int FAST_FUNC
2638 cdcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
2650 dest
= bltinlookup("HOME");
2651 else if (LONE_DASH(dest
)) {
2652 dest
= bltinlookup("OLDPWD");
2674 path
= bltinlookup("CDPATH");
2683 p
= path_advance(&path
, dest
);
2684 if (stat(p
, &statb
) >= 0 && S_ISDIR(statb
.st_mode
)) {
2688 if (!docd(p
, flags
))
2693 ash_msg_and_raise_error("can't cd to %s", dest
);
2696 if (flags
& CD_PRINT
)
2697 out1fmt("%s\n", curdir
);
2701 static int FAST_FUNC
2702 pwdcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
2705 const char *dir
= curdir
;
2709 if (physdir
== nullstr
)
2713 out1fmt("%s\n", dir
);
2718 /* ============ ... */
2721 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2723 /* Syntax classes */
2724 #define CWORD 0 /* character is nothing special */
2725 #define CNL 1 /* newline character */
2726 #define CBACK 2 /* a backslash character */
2727 #define CSQUOTE 3 /* single quote */
2728 #define CDQUOTE 4 /* double quote */
2729 #define CENDQUOTE 5 /* a terminating quote */
2730 #define CBQUOTE 6 /* backwards single quote */
2731 #define CVAR 7 /* a dollar sign */
2732 #define CENDVAR 8 /* a '}' character */
2733 #define CLP 9 /* a left paren in arithmetic */
2734 #define CRP 10 /* a right paren in arithmetic */
2735 #define CENDFILE 11 /* end of file */
2736 #define CCTL 12 /* like CWORD, except it must be escaped */
2737 #define CSPCL 13 /* these terminate a word */
2738 #define CIGN 14 /* character should be ignored */
2741 #if ENABLE_ASH_ALIAS
2745 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2747 #if ENABLE_SH_MATH_SUPPORT
2748 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2750 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2752 static const uint16_t S_I_T
[] = {
2753 #if ENABLE_ASH_ALIAS
2754 SIT_ITEM(CSPCL
, CIGN
, CIGN
, CIGN
), /* 0, PEOA */
2756 SIT_ITEM(CSPCL
, CWORD
, CWORD
, CWORD
), /* 1, ' ' */
2757 SIT_ITEM(CNL
, CNL
, CNL
, CNL
), /* 2, \n */
2758 SIT_ITEM(CWORD
, CCTL
, CCTL
, CWORD
), /* 3, !*-/:=?[]~ */
2759 SIT_ITEM(CDQUOTE
, CENDQUOTE
, CWORD
, CWORD
), /* 4, '"' */
2760 SIT_ITEM(CVAR
, CVAR
, CWORD
, CVAR
), /* 5, $ */
2761 SIT_ITEM(CSQUOTE
, CWORD
, CENDQUOTE
, CWORD
), /* 6, "'" */
2762 SIT_ITEM(CSPCL
, CWORD
, CWORD
, CLP
), /* 7, ( */
2763 SIT_ITEM(CSPCL
, CWORD
, CWORD
, CRP
), /* 8, ) */
2764 SIT_ITEM(CBACK
, CBACK
, CCTL
, CBACK
), /* 9, \ */
2765 SIT_ITEM(CBQUOTE
, CBQUOTE
, CWORD
, CBQUOTE
), /* 10, ` */
2766 SIT_ITEM(CENDVAR
, CENDVAR
, CWORD
, CENDVAR
), /* 11, } */
2767 #if !USE_SIT_FUNCTION
2768 SIT_ITEM(CENDFILE
, CENDFILE
, CENDFILE
, CENDFILE
),/* 12, PEOF */
2769 SIT_ITEM(CWORD
, CWORD
, CWORD
, CWORD
), /* 13, 0-9A-Za-z */
2770 SIT_ITEM(CCTL
, CCTL
, CCTL
, CCTL
) /* 14, CTLESC ... */
2774 /* Constants below must match table above */
2776 #if ENABLE_ASH_ALIAS
2777 CSPCL_CIGN_CIGN_CIGN
, /* 0 */
2779 CSPCL_CWORD_CWORD_CWORD
, /* 1 */
2780 CNL_CNL_CNL_CNL
, /* 2 */
2781 CWORD_CCTL_CCTL_CWORD
, /* 3 */
2782 CDQUOTE_CENDQUOTE_CWORD_CWORD
, /* 4 */
2783 CVAR_CVAR_CWORD_CVAR
, /* 5 */
2784 CSQUOTE_CWORD_CENDQUOTE_CWORD
, /* 6 */
2785 CSPCL_CWORD_CWORD_CLP
, /* 7 */
2786 CSPCL_CWORD_CWORD_CRP
, /* 8 */
2787 CBACK_CBACK_CCTL_CBACK
, /* 9 */
2788 CBQUOTE_CBQUOTE_CWORD_CBQUOTE
, /* 10 */
2789 CENDVAR_CENDVAR_CWORD_CENDVAR
, /* 11 */
2790 CENDFILE_CENDFILE_CENDFILE_CENDFILE
, /* 12 */
2791 CWORD_CWORD_CWORD_CWORD
, /* 13 */
2792 CCTL_CCTL_CCTL_CCTL
, /* 14 */
2795 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2796 * caller must ensure proper cast on it if c is *char_ptr!
2798 /* Values for syntax param */
2799 #define BASESYNTAX 0 /* not in quotes */
2800 #define DQSYNTAX 1 /* in double quotes */
2801 #define SQSYNTAX 2 /* in single quotes */
2802 #define ARISYNTAX 3 /* in arithmetic */
2803 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2805 #if USE_SIT_FUNCTION
2808 SIT(int c
, int syntax
)
2810 static const char spec_symbls
[] ALIGN1
= "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2811 # if ENABLE_ASH_ALIAS
2812 static const uint8_t syntax_index_table
[] ALIGN1
= {
2813 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2814 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2815 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2819 static const uint8_t syntax_index_table
[] ALIGN1
= {
2820 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2821 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2822 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2831 # if ENABLE_ASH_ALIAS
2837 /* Cast is purely for paranoia here,
2838 * just in case someone passed signed char to us */
2839 if ((unsigned char)c
>= CTL_FIRST
2840 && (unsigned char)c
<= CTL_LAST
2844 s
= strchrnul(spec_symbls
, c
);
2847 indx
= syntax_index_table
[s
- spec_symbls
];
2849 return (S_I_T
[indx
] >> (syntax
*4)) & 0xf;
2852 #else /* !USE_SIT_FUNCTION */
2854 static const uint8_t syntax_index_table
[] = {
2855 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2856 /* 0 */ CWORD_CWORD_CWORD_CWORD
,
2857 /* 1 */ CWORD_CWORD_CWORD_CWORD
,
2858 /* 2 */ CWORD_CWORD_CWORD_CWORD
,
2859 /* 3 */ CWORD_CWORD_CWORD_CWORD
,
2860 /* 4 */ CWORD_CWORD_CWORD_CWORD
,
2861 /* 5 */ CWORD_CWORD_CWORD_CWORD
,
2862 /* 6 */ CWORD_CWORD_CWORD_CWORD
,
2863 /* 7 */ CWORD_CWORD_CWORD_CWORD
,
2864 /* 8 */ CWORD_CWORD_CWORD_CWORD
,
2865 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD
,
2866 /* 10 "\n" */ CNL_CNL_CNL_CNL
,
2867 /* 11 */ CWORD_CWORD_CWORD_CWORD
,
2868 /* 12 */ CWORD_CWORD_CWORD_CWORD
,
2869 /* 13 */ CWORD_CWORD_CWORD_CWORD
,
2870 /* 14 */ CWORD_CWORD_CWORD_CWORD
,
2871 /* 15 */ CWORD_CWORD_CWORD_CWORD
,
2872 /* 16 */ CWORD_CWORD_CWORD_CWORD
,
2873 /* 17 */ CWORD_CWORD_CWORD_CWORD
,
2874 /* 18 */ CWORD_CWORD_CWORD_CWORD
,
2875 /* 19 */ CWORD_CWORD_CWORD_CWORD
,
2876 /* 20 */ CWORD_CWORD_CWORD_CWORD
,
2877 /* 21 */ CWORD_CWORD_CWORD_CWORD
,
2878 /* 22 */ CWORD_CWORD_CWORD_CWORD
,
2879 /* 23 */ CWORD_CWORD_CWORD_CWORD
,
2880 /* 24 */ CWORD_CWORD_CWORD_CWORD
,
2881 /* 25 */ CWORD_CWORD_CWORD_CWORD
,
2882 /* 26 */ CWORD_CWORD_CWORD_CWORD
,
2883 /* 27 */ CWORD_CWORD_CWORD_CWORD
,
2884 /* 28 */ CWORD_CWORD_CWORD_CWORD
,
2885 /* 29 */ CWORD_CWORD_CWORD_CWORD
,
2886 /* 30 */ CWORD_CWORD_CWORD_CWORD
,
2887 /* 31 */ CWORD_CWORD_CWORD_CWORD
,
2888 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD
,
2889 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD
,
2890 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD
,
2891 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD
,
2892 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR
,
2893 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD
,
2894 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD
,
2895 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD
,
2896 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP
,
2897 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP
,
2898 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD
,
2899 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD
,
2900 /* 44 "," */ CWORD_CWORD_CWORD_CWORD
,
2901 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD
,
2902 /* 46 "." */ CWORD_CWORD_CWORD_CWORD
,
2903 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD
,
2904 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD
,
2905 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD
,
2906 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD
,
2907 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD
,
2908 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD
,
2909 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD
,
2910 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD
,
2911 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD
,
2912 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD
,
2913 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD
,
2914 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD
,
2915 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD
,
2916 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD
,
2917 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD
,
2918 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD
,
2919 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD
,
2920 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD
,
2921 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD
,
2922 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD
,
2923 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD
,
2924 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD
,
2925 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD
,
2926 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD
,
2927 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD
,
2928 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD
,
2929 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD
,
2930 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD
,
2931 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD
,
2932 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD
,
2933 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD
,
2934 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD
,
2935 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD
,
2936 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD
,
2937 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD
,
2938 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD
,
2939 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD
,
2940 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD
,
2941 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD
,
2942 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD
,
2943 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD
,
2944 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD
,
2945 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD
,
2946 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD
,
2947 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD
,
2948 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK
,
2949 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD
,
2950 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD
,
2951 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD
,
2952 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE
,
2953 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD
,
2954 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD
,
2955 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD
,
2956 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD
,
2957 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD
,
2958 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD
,
2959 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD
,
2960 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD
,
2961 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD
,
2962 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD
,
2963 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD
,
2964 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD
,
2965 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD
,
2966 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD
,
2967 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD
,
2968 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD
,
2969 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD
,
2970 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD
,
2971 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD
,
2972 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD
,
2973 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD
,
2974 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD
,
2975 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD
,
2976 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD
,
2977 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD
,
2978 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD
,
2979 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD
,
2980 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD
,
2981 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR
,
2982 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD
,
2983 /* 127 del */ CWORD_CWORD_CWORD_CWORD
,
2984 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD
,
2985 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL
,
2986 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL
,
2987 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL
,
2988 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL
,
2989 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL
,
2990 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL
,
2991 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL
,
2992 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL
,
2993 /* 137 */ CWORD_CWORD_CWORD_CWORD
,
2994 /* 138 */ CWORD_CWORD_CWORD_CWORD
,
2995 /* 139 */ CWORD_CWORD_CWORD_CWORD
,
2996 /* 140 */ CWORD_CWORD_CWORD_CWORD
,
2997 /* 141 */ CWORD_CWORD_CWORD_CWORD
,
2998 /* 142 */ CWORD_CWORD_CWORD_CWORD
,
2999 /* 143 */ CWORD_CWORD_CWORD_CWORD
,
3000 /* 144 */ CWORD_CWORD_CWORD_CWORD
,
3001 /* 145 */ CWORD_CWORD_CWORD_CWORD
,
3002 /* 146 */ CWORD_CWORD_CWORD_CWORD
,
3003 /* 147 */ CWORD_CWORD_CWORD_CWORD
,
3004 /* 148 */ CWORD_CWORD_CWORD_CWORD
,
3005 /* 149 */ CWORD_CWORD_CWORD_CWORD
,
3006 /* 150 */ CWORD_CWORD_CWORD_CWORD
,
3007 /* 151 */ CWORD_CWORD_CWORD_CWORD
,
3008 /* 152 */ CWORD_CWORD_CWORD_CWORD
,
3009 /* 153 */ CWORD_CWORD_CWORD_CWORD
,
3010 /* 154 */ CWORD_CWORD_CWORD_CWORD
,
3011 /* 155 */ CWORD_CWORD_CWORD_CWORD
,
3012 /* 156 */ CWORD_CWORD_CWORD_CWORD
,
3013 /* 157 */ CWORD_CWORD_CWORD_CWORD
,
3014 /* 158 */ CWORD_CWORD_CWORD_CWORD
,
3015 /* 159 */ CWORD_CWORD_CWORD_CWORD
,
3016 /* 160 */ CWORD_CWORD_CWORD_CWORD
,
3017 /* 161 */ CWORD_CWORD_CWORD_CWORD
,
3018 /* 162 */ CWORD_CWORD_CWORD_CWORD
,
3019 /* 163 */ CWORD_CWORD_CWORD_CWORD
,
3020 /* 164 */ CWORD_CWORD_CWORD_CWORD
,
3021 /* 165 */ CWORD_CWORD_CWORD_CWORD
,
3022 /* 166 */ CWORD_CWORD_CWORD_CWORD
,
3023 /* 167 */ CWORD_CWORD_CWORD_CWORD
,
3024 /* 168 */ CWORD_CWORD_CWORD_CWORD
,
3025 /* 169 */ CWORD_CWORD_CWORD_CWORD
,
3026 /* 170 */ CWORD_CWORD_CWORD_CWORD
,
3027 /* 171 */ CWORD_CWORD_CWORD_CWORD
,
3028 /* 172 */ CWORD_CWORD_CWORD_CWORD
,
3029 /* 173 */ CWORD_CWORD_CWORD_CWORD
,
3030 /* 174 */ CWORD_CWORD_CWORD_CWORD
,
3031 /* 175 */ CWORD_CWORD_CWORD_CWORD
,
3032 /* 176 */ CWORD_CWORD_CWORD_CWORD
,
3033 /* 177 */ CWORD_CWORD_CWORD_CWORD
,
3034 /* 178 */ CWORD_CWORD_CWORD_CWORD
,
3035 /* 179 */ CWORD_CWORD_CWORD_CWORD
,
3036 /* 180 */ CWORD_CWORD_CWORD_CWORD
,
3037 /* 181 */ CWORD_CWORD_CWORD_CWORD
,
3038 /* 182 */ CWORD_CWORD_CWORD_CWORD
,
3039 /* 183 */ CWORD_CWORD_CWORD_CWORD
,
3040 /* 184 */ CWORD_CWORD_CWORD_CWORD
,
3041 /* 185 */ CWORD_CWORD_CWORD_CWORD
,
3042 /* 186 */ CWORD_CWORD_CWORD_CWORD
,
3043 /* 187 */ CWORD_CWORD_CWORD_CWORD
,
3044 /* 188 */ CWORD_CWORD_CWORD_CWORD
,
3045 /* 189 */ CWORD_CWORD_CWORD_CWORD
,
3046 /* 190 */ CWORD_CWORD_CWORD_CWORD
,
3047 /* 191 */ CWORD_CWORD_CWORD_CWORD
,
3048 /* 192 */ CWORD_CWORD_CWORD_CWORD
,
3049 /* 193 */ CWORD_CWORD_CWORD_CWORD
,
3050 /* 194 */ CWORD_CWORD_CWORD_CWORD
,
3051 /* 195 */ CWORD_CWORD_CWORD_CWORD
,
3052 /* 196 */ CWORD_CWORD_CWORD_CWORD
,
3053 /* 197 */ CWORD_CWORD_CWORD_CWORD
,
3054 /* 198 */ CWORD_CWORD_CWORD_CWORD
,
3055 /* 199 */ CWORD_CWORD_CWORD_CWORD
,
3056 /* 200 */ CWORD_CWORD_CWORD_CWORD
,
3057 /* 201 */ CWORD_CWORD_CWORD_CWORD
,
3058 /* 202 */ CWORD_CWORD_CWORD_CWORD
,
3059 /* 203 */ CWORD_CWORD_CWORD_CWORD
,
3060 /* 204 */ CWORD_CWORD_CWORD_CWORD
,
3061 /* 205 */ CWORD_CWORD_CWORD_CWORD
,
3062 /* 206 */ CWORD_CWORD_CWORD_CWORD
,
3063 /* 207 */ CWORD_CWORD_CWORD_CWORD
,
3064 /* 208 */ CWORD_CWORD_CWORD_CWORD
,
3065 /* 209 */ CWORD_CWORD_CWORD_CWORD
,
3066 /* 210 */ CWORD_CWORD_CWORD_CWORD
,
3067 /* 211 */ CWORD_CWORD_CWORD_CWORD
,
3068 /* 212 */ CWORD_CWORD_CWORD_CWORD
,
3069 /* 213 */ CWORD_CWORD_CWORD_CWORD
,
3070 /* 214 */ CWORD_CWORD_CWORD_CWORD
,
3071 /* 215 */ CWORD_CWORD_CWORD_CWORD
,
3072 /* 216 */ CWORD_CWORD_CWORD_CWORD
,
3073 /* 217 */ CWORD_CWORD_CWORD_CWORD
,
3074 /* 218 */ CWORD_CWORD_CWORD_CWORD
,
3075 /* 219 */ CWORD_CWORD_CWORD_CWORD
,
3076 /* 220 */ CWORD_CWORD_CWORD_CWORD
,
3077 /* 221 */ CWORD_CWORD_CWORD_CWORD
,
3078 /* 222 */ CWORD_CWORD_CWORD_CWORD
,
3079 /* 223 */ CWORD_CWORD_CWORD_CWORD
,
3080 /* 224 */ CWORD_CWORD_CWORD_CWORD
,
3081 /* 225 */ CWORD_CWORD_CWORD_CWORD
,
3082 /* 226 */ CWORD_CWORD_CWORD_CWORD
,
3083 /* 227 */ CWORD_CWORD_CWORD_CWORD
,
3084 /* 228 */ CWORD_CWORD_CWORD_CWORD
,
3085 /* 229 */ CWORD_CWORD_CWORD_CWORD
,
3086 /* 230 */ CWORD_CWORD_CWORD_CWORD
,
3087 /* 231 */ CWORD_CWORD_CWORD_CWORD
,
3088 /* 232 */ CWORD_CWORD_CWORD_CWORD
,
3089 /* 233 */ CWORD_CWORD_CWORD_CWORD
,
3090 /* 234 */ CWORD_CWORD_CWORD_CWORD
,
3091 /* 235 */ CWORD_CWORD_CWORD_CWORD
,
3092 /* 236 */ CWORD_CWORD_CWORD_CWORD
,
3093 /* 237 */ CWORD_CWORD_CWORD_CWORD
,
3094 /* 238 */ CWORD_CWORD_CWORD_CWORD
,
3095 /* 239 */ CWORD_CWORD_CWORD_CWORD
,
3096 /* 230 */ CWORD_CWORD_CWORD_CWORD
,
3097 /* 241 */ CWORD_CWORD_CWORD_CWORD
,
3098 /* 242 */ CWORD_CWORD_CWORD_CWORD
,
3099 /* 243 */ CWORD_CWORD_CWORD_CWORD
,
3100 /* 244 */ CWORD_CWORD_CWORD_CWORD
,
3101 /* 245 */ CWORD_CWORD_CWORD_CWORD
,
3102 /* 246 */ CWORD_CWORD_CWORD_CWORD
,
3103 /* 247 */ CWORD_CWORD_CWORD_CWORD
,
3104 /* 248 */ CWORD_CWORD_CWORD_CWORD
,
3105 /* 249 */ CWORD_CWORD_CWORD_CWORD
,
3106 /* 250 */ CWORD_CWORD_CWORD_CWORD
,
3107 /* 251 */ CWORD_CWORD_CWORD_CWORD
,
3108 /* 252 */ CWORD_CWORD_CWORD_CWORD
,
3109 /* 253 */ CWORD_CWORD_CWORD_CWORD
,
3110 /* 254 */ CWORD_CWORD_CWORD_CWORD
,
3111 /* 255 */ CWORD_CWORD_CWORD_CWORD
,
3112 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE
,
3113 # if ENABLE_ASH_ALIAS
3114 /* PEOA */ CSPCL_CIGN_CIGN_CIGN
,
3118 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3120 #endif /* !USE_SIT_FUNCTION */
3123 /* ============ Alias handling */
3125 #if ENABLE_ASH_ALIAS
3127 #define ALIASINUSE 1
3138 static struct alias
**atab
; // [ATABSIZE];
3139 #define INIT_G_alias() do { \
3140 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3144 static struct alias
**
3145 __lookupalias(const char *name
) {
3146 unsigned int hashval
;
3153 ch
= (unsigned char)*p
;
3157 ch
= (unsigned char)*++p
;
3159 app
= &atab
[hashval
% ATABSIZE
];
3161 for (; *app
; app
= &(*app
)->next
) {
3162 if (strcmp(name
, (*app
)->name
) == 0) {
3170 static struct alias
*
3171 lookupalias(const char *name
, int check
)
3173 struct alias
*ap
= *__lookupalias(name
);
3175 if (check
&& ap
&& (ap
->flag
& ALIASINUSE
))
3180 static struct alias
*
3181 freealias(struct alias
*ap
)
3185 if (ap
->flag
& ALIASINUSE
) {
3186 ap
->flag
|= ALIASDEAD
;
3198 setalias(const char *name
, const char *val
)
3200 struct alias
*ap
, **app
;
3202 app
= __lookupalias(name
);
3206 if (!(ap
->flag
& ALIASINUSE
)) {
3209 ap
->val
= ckstrdup(val
);
3210 ap
->flag
&= ~ALIASDEAD
;
3213 ap
= ckzalloc(sizeof(struct alias
));
3214 ap
->name
= ckstrdup(name
);
3215 ap
->val
= ckstrdup(val
);
3216 /*ap->flag = 0; - ckzalloc did it */
3217 /*ap->next = NULL;*/
3224 unalias(const char *name
)
3228 app
= __lookupalias(name
);
3232 *app
= freealias(*app
);
3243 struct alias
*ap
, **app
;
3247 for (i
= 0; i
< ATABSIZE
; i
++) {
3249 for (ap
= *app
; ap
; ap
= *app
) {
3250 *app
= freealias(*app
);
3260 printalias(const struct alias
*ap
)
3262 out1fmt("%s=%s\n", ap
->name
, single_quote(ap
->val
));
3266 * TODO - sort output
3268 static int FAST_FUNC
3269 aliascmd(int argc UNUSED_PARAM
, char **argv
)
3278 for (i
= 0; i
< ATABSIZE
; i
++) {
3279 for (ap
= atab
[i
]; ap
; ap
= ap
->next
) {
3285 while ((n
= *++argv
) != NULL
) {
3286 v
= strchr(n
+1, '=');
3287 if (v
== NULL
) { /* n+1: funny ksh stuff */
3288 ap
= *__lookupalias(n
);
3290 fprintf(stderr
, "%s: %s not found\n", "alias", n
);
3303 static int FAST_FUNC
3304 unaliascmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
3308 while ((i
= nextopt("a")) != '\0') {
3314 for (i
= 0; *argptr
; argptr
++) {
3315 if (unalias(*argptr
)) {
3316 fprintf(stderr
, "%s: %s not found\n", "unalias", *argptr
);
3324 #endif /* ASH_ALIAS */
3327 /* ============ jobs.c */
3329 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3332 #define FORK_NOJOB 2
3334 /* mode flags for showjob(s) */
3335 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3336 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3337 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3340 * A job structure contains information about a job. A job is either a
3341 * single process or a set of processes contained in a pipeline. In the
3342 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3346 pid_t ps_pid
; /* process id */
3347 int ps_status
; /* last process status from wait() */
3348 char *ps_cmd
; /* text of command being run */
3352 struct procstat ps0
; /* status of process */
3353 struct procstat
*ps
; /* status or processes when more than one */
3355 int stopstatus
; /* status of a stopped job */
3358 nprocs
: 16, /* number of processes */
3360 #define JOBRUNNING 0 /* at least one proc running */
3361 #define JOBSTOPPED 1 /* all procs are stopped */
3362 #define JOBDONE 2 /* all procs are completed */
3364 sigint
: 1, /* job was killed by SIGINT */
3365 jobctl
: 1, /* job running under job control */
3367 waited
: 1, /* true if this entry has been waited for */
3368 used
: 1, /* true if this entry is in used */
3369 changed
: 1; /* true if status has changed */
3370 struct job
*prev_job
; /* previous job */
3373 static struct job
*makejob(/*union node *,*/ int);
3374 static int forkshell(struct job
*, union node
*, int);
3375 static int waitforjob(struct job
*);
3378 enum { doing_jobctl
= 0 };
3379 #define setjobctl(on) do {} while (0)
3381 static smallint doing_jobctl
; //references:8
3382 static void setjobctl(int);
3389 ignoresig(int signo
)
3391 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3392 if (sigmode
[signo
- 1] != S_IGN
&& sigmode
[signo
- 1] != S_HARD_IGN
) {
3393 /* No, need to do it */
3394 signal(signo
, SIG_IGN
);
3396 sigmode
[signo
- 1] = S_HARD_IGN
;
3400 * Only one usage site - in setsignal()
3403 signal_handler(int signo
)
3405 gotsig
[signo
- 1] = 1;
3407 if (signo
== SIGINT
&& !trap
[SIGINT
]) {
3408 if (!suppress_int
) {
3410 raise_interrupt(); /* does not return */
3414 pending_sig
= signo
;
3419 * Set the signal handler for the specified signal. The routine figures
3420 * out what it should be set to.
3423 setsignal(int signo
)
3426 char cur_act
, new_act
;
3427 struct sigaction act
;
3431 if (t
!= NULL
) { /* trap for this sig is set */
3433 if (t
[0] == '\0') /* trap is "": ignore this sig */
3437 if (rootshell
&& new_act
== S_DFL
) {
3440 if (iflag
|| minusc
|| sflag
== 0)
3449 * "In all cases, bash ignores SIGQUIT. Non-builtin
3450 * commands run by bash have signal handlers
3451 * set to the values inherited by the shell
3452 * from its parent". */
3468 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3469 //whereas we have to restore it to what shell got on entry
3470 //from the parent. See comment above
3472 t
= &sigmode
[signo
- 1];
3475 /* current setting is not yet known */
3476 if (sigaction(signo
, NULL
, &act
)) {
3477 /* pretend it worked; maybe we should give a warning,
3478 * but other shells don't. We don't alter sigmode,
3479 * so we retry every time.
3480 * btw, in Linux it never fails. --vda */
3483 if (act
.sa_handler
== SIG_IGN
) {
3484 cur_act
= S_HARD_IGN
;
3486 && (signo
== SIGTSTP
|| signo
== SIGTTIN
|| signo
== SIGTTOU
)
3488 cur_act
= S_IGN
; /* don't hard ignore these */
3492 if (cur_act
== S_HARD_IGN
|| cur_act
== new_act
)
3495 act
.sa_handler
= SIG_DFL
;
3498 act
.sa_handler
= signal_handler
;
3501 act
.sa_handler
= SIG_IGN
;
3505 /* flags and mask matter only if !DFL and !IGN, but we do it
3506 * for all cases for more deterministic behavior:
3509 sigfillset(&act
.sa_mask
);
3511 sigaction_set(signo
, &act
);
3516 /* mode flags for set_curjob */
3517 #define CUR_DELETE 2
3518 #define CUR_RUNNING 1
3519 #define CUR_STOPPED 0
3521 /* mode flags for dowait */
3522 #define DOWAIT_NONBLOCK WNOHANG
3523 #define DOWAIT_BLOCK 0
3526 /* pgrp of shell on invocation */
3527 static int initialpgrp
; //references:2
3528 static int ttyfd
= -1; //5
3531 static struct job
*jobtab
; //5
3533 static unsigned njobs
; //4
3535 static struct job
*curjob
; //lots
3536 /* number of presumed living untracked jobs */
3537 static int jobless
; //4
3540 set_curjob(struct job
*jp
, unsigned mode
)
3543 struct job
**jpp
, **curp
;
3545 /* first remove from list */
3546 jpp
= curp
= &curjob
;
3551 jpp
= &jp1
->prev_job
;
3553 *jpp
= jp1
->prev_job
;
3555 /* Then re-insert in correct position */
3563 /* job being deleted */
3566 /* newly created job or backgrounded job,
3567 * put after all stopped jobs.
3572 if (!jp1
|| jp1
->state
!= JOBSTOPPED
)
3575 jpp
= &jp1
->prev_job
;
3581 /* newly stopped job - becomes curjob */
3582 jp
->prev_job
= *jpp
;
3590 jobno(const struct job
*jp
)
3592 return jp
- jobtab
+ 1;
3597 * Convert a job name to a job structure.
3600 #define getjob(name, getctl) getjob(name)
3603 getjob(const char *name
, int getctl
)
3607 const char *err_msg
= "%s: no such job";
3611 char *(*match
)(const char *, const char *);
3626 if (c
== '+' || c
== '%') {
3628 err_msg
= "No current job";
3634 err_msg
= "No previous job";
3645 jp
= jobtab
+ num
- 1;
3660 if (match(jp
->ps
[0].ps_cmd
, p
)) {
3664 err_msg
= "%s: ambiguous";
3674 err_msg
= "job %s not created under job control";
3675 if (getctl
&& jp
->jobctl
== 0)
3680 ash_msg_and_raise_error(err_msg
, name
);
3684 * Mark a job structure as unused.
3687 freejob(struct job
*jp
)
3689 struct procstat
*ps
;
3693 for (i
= jp
->nprocs
, ps
= jp
->ps
; --i
>= 0; ps
++) {
3694 if (ps
->ps_cmd
!= nullstr
)
3697 if (jp
->ps
!= &jp
->ps0
)
3700 set_curjob(jp
, CUR_DELETE
);
3706 xtcsetpgrp(int fd
, pid_t pgrp
)
3708 if (tcsetpgrp(fd
, pgrp
))
3709 ash_msg_and_raise_error("can't set tty process group (%m)");
3713 * Turn job control on and off.
3715 * Note: This code assumes that the third arg to ioctl is a character
3716 * pointer, which is true on Berkeley systems but not System V. Since
3717 * System V doesn't have job control yet, this isn't a problem now.
3719 * Called with interrupts off.
3727 if (on
== doing_jobctl
|| rootshell
== 0)
3731 ofd
= fd
= open(_PATH_TTY
, O_RDWR
);
3733 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3734 * That sometimes helps to acquire controlling tty.
3735 * Obviously, a workaround for bugs when someone
3736 * failed to provide a controlling tty to bash! :) */
3742 fd
= fcntl(fd
, F_DUPFD
, 10);
3747 /* fd is a tty at this point */
3748 close_on_exec_on(fd
);
3749 while (1) { /* while we are in the background */
3750 pgrp
= tcgetpgrp(fd
);
3753 ash_msg("can't access tty; job control turned off");
3757 if (pgrp
== getpgrp())
3768 xtcsetpgrp(fd
, pgrp
);
3770 /* turning job control off */
3773 /* was xtcsetpgrp, but this can make exiting ash
3774 * loop forever if pty is already deleted */
3775 tcsetpgrp(fd
, pgrp
);
3789 static int FAST_FUNC
3790 killcmd(int argc
, char **argv
)
3792 if (argv
[1] && strcmp(argv
[1], "-l") != 0) {
3795 if (argv
[i
][0] == '%') {
3797 * "kill %N" - job kill
3798 * Converting to pgrp / pid kill
3804 jp
= getjob(argv
[i
], 0);
3806 * In jobs started under job control, we signal
3807 * entire process group by kill -PGRP_ID.
3808 * This happens, f.e., in interactive shell.
3810 * Otherwise, we signal each child via
3811 * kill PID1 PID2 PID3.
3813 * sh -c 'sleep 1|sleep 1 & kill %1'
3814 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3815 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3817 n
= jp
->nprocs
; /* can't be 0 (I hope) */
3820 dst
= alloca(n
* sizeof(int)*4);
3822 for (j
= 0; j
< n
; j
++) {
3823 struct procstat
*ps
= &jp
->ps
[j
];
3824 /* Skip non-running and not-stopped members
3825 * (i.e. dead members) of the job
3827 if (ps
->ps_status
!= -1 && !WIFSTOPPED(ps
->ps_status
))
3830 * kill_main has matching code to expect
3831 * leading space. Needed to not confuse
3832 * negative pids with "kill -SIGNAL_NO" syntax
3834 dst
+= sprintf(dst
, jp
->jobctl
? " -%u" : " %u", (int)ps
->ps_pid
);
3838 } while (argv
[++i
]);
3840 return kill_main(argc
, argv
);
3844 showpipe(struct job
*jp
/*, FILE *out*/)
3846 struct procstat
*ps
;
3847 struct procstat
*psend
;
3849 psend
= jp
->ps
+ jp
->nprocs
;
3850 for (ps
= jp
->ps
+ 1; ps
< psend
; ps
++)
3851 printf(" | %s", ps
->ps_cmd
);
3852 outcslow('\n', stdout
);
3853 flush_stdout_stderr();
3858 restartjob(struct job
*jp
, int mode
)
3860 struct procstat
*ps
;
3866 if (jp
->state
== JOBDONE
)
3868 jp
->state
= JOBRUNNING
;
3869 pgid
= jp
->ps
[0].ps_pid
;
3870 if (mode
== FORK_FG
)
3871 xtcsetpgrp(ttyfd
, pgid
);
3872 killpg(pgid
, SIGCONT
);
3876 if (WIFSTOPPED(ps
->ps_status
)) {
3882 status
= (mode
== FORK_FG
) ? waitforjob(jp
) : 0;
3887 static int FAST_FUNC
3888 fg_bgcmd(int argc UNUSED_PARAM
, char **argv
)
3894 mode
= (**argv
== 'f') ? FORK_FG
: FORK_BG
;
3898 jp
= getjob(*argv
, 1);
3899 if (mode
== FORK_BG
) {
3900 set_curjob(jp
, CUR_RUNNING
);
3901 printf("[%d] ", jobno(jp
));
3903 out1str(jp
->ps
[0].ps_cmd
);
3904 showpipe(jp
/*, stdout*/);
3905 retval
= restartjob(jp
, mode
);
3906 } while (*argv
&& *++argv
);
3912 sprint_status(char *s
, int status
, int sigonly
)
3918 if (!WIFEXITED(status
)) {
3920 if (WIFSTOPPED(status
))
3921 st
= WSTOPSIG(status
);
3924 st
= WTERMSIG(status
);
3926 if (st
== SIGINT
|| st
== SIGPIPE
)
3929 if (WIFSTOPPED(status
))
3934 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3935 col
= fmtstr(s
, 32, strsignal(st
));
3936 if (WCOREDUMP(status
)) {
3937 col
+= fmtstr(s
+ col
, 16, " (core dumped)");
3939 } else if (!sigonly
) {
3940 st
= WEXITSTATUS(status
);
3942 col
= fmtstr(s
, 16, "Done(%d)", st
);
3944 col
= fmtstr(s
, 16, "Done");
3951 dowait(int wait_flags
, struct job
*job
)
3956 struct job
*thisjob
;
3959 TRACE(("dowait(0x%x) called\n", wait_flags
));
3961 /* Do a wait system call. If job control is compiled in, we accept
3962 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3963 * NB: _not_ safe_waitpid, we need to detect EINTR */
3965 wait_flags
|= WUNTRACED
;
3966 pid
= waitpid(-1, &status
, wait_flags
);
3967 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3968 pid
, status
, errno
, strerror(errno
)));
3974 for (jp
= curjob
; jp
; jp
= jp
->prev_job
) {
3975 struct procstat
*ps
;
3976 struct procstat
*psend
;
3977 if (jp
->state
== JOBDONE
)
3981 psend
= ps
+ jp
->nprocs
;
3983 if (ps
->ps_pid
== pid
) {
3984 TRACE(("Job %d: changing status of proc %d "
3985 "from 0x%x to 0x%x\n",
3986 jobno(jp
), pid
, ps
->ps_status
, status
));
3987 ps
->ps_status
= status
;
3990 if (ps
->ps_status
== -1)
3993 if (state
== JOBRUNNING
)
3995 if (WIFSTOPPED(ps
->ps_status
)) {
3996 jp
->stopstatus
= ps
->ps_status
;
4000 } while (++ps
< psend
);
4005 if (!WIFSTOPPED(status
))
4011 if (state
!= JOBRUNNING
) {
4012 thisjob
->changed
= 1;
4014 if (thisjob
->state
!= state
) {
4015 TRACE(("Job %d: changing state from %d to %d\n",
4016 jobno(thisjob
), thisjob
->state
, state
));
4017 thisjob
->state
= state
;
4019 if (state
== JOBSTOPPED
) {
4020 set_curjob(thisjob
, CUR_STOPPED
);
4029 if (thisjob
&& thisjob
== job
) {
4033 len
= sprint_status(s
, status
, 1);
4044 blocking_wait_with_raise_on_sig(void)
4046 pid_t pid
= dowait(DOWAIT_BLOCK
, NULL
);
4047 if (pid
<= 0 && pending_sig
)
4048 raise_exception(EXSIG
);
4054 showjob(FILE *out
, struct job
*jp
, int mode
)
4056 struct procstat
*ps
;
4057 struct procstat
*psend
;
4064 if (mode
& SHOW_ONLY_PGID
) { /* jobs -p */
4065 /* just output process (group) id of pipeline */
4066 fprintf(out
, "%d\n", ps
->ps_pid
);
4070 col
= fmtstr(s
, 16, "[%d] ", jobno(jp
));
4075 else if (curjob
&& jp
== curjob
->prev_job
)
4078 if (mode
& SHOW_PIDS
)
4079 col
+= fmtstr(s
+ col
, 16, "%d ", ps
->ps_pid
);
4081 psend
= ps
+ jp
->nprocs
;
4083 if (jp
->state
== JOBRUNNING
) {
4084 strcpy(s
+ col
, "Running");
4085 col
+= sizeof("Running") - 1;
4087 int status
= psend
[-1].ps_status
;
4088 if (jp
->state
== JOBSTOPPED
)
4089 status
= jp
->stopstatus
;
4090 col
+= sprint_status(s
+ col
, status
, 0);
4092 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4094 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4095 * or prints several "PID | <cmdN>" lines,
4096 * depending on SHOW_PIDS bit.
4097 * We do not print status of individual processes
4098 * between PID and <cmdN>. bash does it, but not very well:
4099 * first line shows overall job status, not process status,
4100 * making it impossible to know 1st process status.
4104 /* for each process */
4107 if (mode
& SHOW_PIDS
)
4108 col
= fmtstr(s
, 48, "\n%*c%d ", indent_col
, ' ', ps
->ps_pid
) - 1;
4110 fprintf(out
, "%s%*c%s%s",
4112 33 - col
>= 0 ? 33 - col
: 0, ' ',
4113 ps
== jp
->ps
? "" : "| ",
4116 } while (++ps
!= psend
);
4117 outcslow('\n', out
);
4121 if (jp
->state
== JOBDONE
) {
4122 TRACE(("showjob: freeing job %d\n", jobno(jp
)));
4128 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4129 * statuses have changed since the last call to showjobs.
4132 showjobs(FILE *out
, int mode
)
4136 TRACE(("showjobs(0x%x) called\n", mode
));
4138 /* Handle all finished jobs */
4139 while (dowait(DOWAIT_NONBLOCK
, NULL
) > 0)
4142 for (jp
= curjob
; jp
; jp
= jp
->prev_job
) {
4143 if (!(mode
& SHOW_CHANGED
) || jp
->changed
) {
4144 showjob(out
, jp
, mode
);
4149 static int FAST_FUNC
4150 jobscmd(int argc UNUSED_PARAM
, char **argv
)
4155 while ((m
= nextopt("lp")) != '\0') {
4159 mode
|= SHOW_ONLY_PGID
;
4165 showjob(stdout
, getjob(*argv
, 0), mode
);
4168 showjobs(stdout
, mode
);
4175 /* Called only on finished or stopped jobs (no members are running) */
4177 getstatus(struct job
*job
)
4181 struct procstat
*ps
;
4183 /* Fetch last member's status */
4184 ps
= job
->ps
+ job
->nprocs
- 1;
4185 status
= ps
->ps_status
;
4187 /* "set -o pipefail" mode: use last _nonzero_ status */
4188 while (status
== 0 && --ps
>= job
->ps
)
4189 status
= ps
->ps_status
;
4192 retval
= WEXITSTATUS(status
);
4193 if (!WIFEXITED(status
)) {
4195 retval
= WSTOPSIG(status
);
4196 if (!WIFSTOPPED(status
))
4199 /* XXX: limits number of signals */
4200 retval
= WTERMSIG(status
);
4202 if (retval
== SIGINT
)
4208 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4209 jobno(job
), job
->nprocs
, status
, retval
));
4213 static int FAST_FUNC
4214 waitcmd(int argc UNUSED_PARAM
, char **argv
)
4221 raise_exception(EXSIG
);
4228 /* wait for all jobs */
4232 if (!jp
) /* no running procs */
4234 if (jp
->state
== JOBRUNNING
)
4239 blocking_wait_with_raise_on_sig();
4241 * "When bash is waiting for an asynchronous command via
4242 * the wait builtin, the reception of a signal for which a trap
4243 * has been set will cause the wait builtin to return immediately
4244 * with an exit status greater than 128, immediately after which
4245 * the trap is executed."
4247 * blocking_wait_with_raise_on_sig raises signal handlers
4248 * if it gets no pid (pid < 0). However,
4249 * if child sends us a signal *and immediately exits*,
4250 * blocking_wait_with_raise_on_sig gets pid > 0
4251 * and does not handle pending_sig. Check this case: */
4253 raise_exception(EXSIG
);
4259 if (**argv
!= '%') {
4260 pid_t pid
= number(*argv
);
4265 if (job
->ps
[job
->nprocs
- 1].ps_pid
== pid
)
4267 job
= job
->prev_job
;
4270 job
= getjob(*argv
, 0);
4272 /* loop until process terminated or stopped */
4273 while (job
->state
== JOBRUNNING
)
4274 blocking_wait_with_raise_on_sig();
4276 retval
= getstatus(job
);
4289 struct job
*jp
, *jq
;
4291 len
= njobs
* sizeof(*jp
);
4293 jp
= ckrealloc(jq
, len
+ 4 * sizeof(*jp
));
4295 offset
= (char *)jp
- (char *)jq
;
4297 /* Relocate pointers */
4300 jq
= (struct job
*)((char *)jq
+ l
);
4304 #define joff(p) ((struct job *)((char *)(p) + l))
4305 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4306 if (joff(jp
)->ps
== &jq
->ps0
)
4307 jmove(joff(jp
)->ps
);
4308 if (joff(jp
)->prev_job
)
4309 jmove(joff(jp
)->prev_job
);
4319 jp
= (struct job
*)((char *)jp
+ len
);
4323 } while (--jq
>= jp
);
4328 * Return a new job structure.
4329 * Called with interrupts off.
4332 makejob(/*union node *node,*/ int nprocs
)
4337 for (i
= njobs
, jp
= jobtab
; ; jp
++) {
4344 if (jp
->state
!= JOBDONE
|| !jp
->waited
)
4353 memset(jp
, 0, sizeof(*jp
));
4355 /* jp->jobctl is a bitfield.
4356 * "jp->jobctl |= jobctl" likely to give awful code */
4360 jp
->prev_job
= curjob
;
4365 jp
->ps
= ckmalloc(nprocs
* sizeof(struct procstat
));
4367 TRACE(("makejob(%d) returns %%%d\n", nprocs
,
4374 * Return a string identifying a command (to be printed by the
4377 static char *cmdnextc
;
4380 cmdputs(const char *s
)
4382 static const char vstype
[VSTYPE
+ 1][3] = {
4383 "", "}", "-", "+", "?", "=",
4384 "%", "%%", "#", "##"
4385 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4388 const char *p
, *str
;
4392 unsigned char subtype
= 0;
4396 nextc
= makestrspace((strlen(s
) + 1) * 8, cmdnextc
);
4398 while ((c
= *p
++) != '\0') {
4406 if ((subtype
& VSTYPE
) == VSLENGTH
)
4410 if (!(subtype
& VSQUOTE
) == !(quoted
& 1))
4416 str
= "\"}" + !(quoted
& 1);
4423 case CTLBACKQ
+CTLQUOTE
:
4426 #if ENABLE_SH_MATH_SUPPORT
4441 if ((subtype
& VSTYPE
) != VSNORMAL
)
4443 str
= vstype
[subtype
& VSTYPE
];
4444 if (subtype
& VSNUL
)
4453 /* These can only happen inside quotes */
4466 while ((c
= *str
++) != '\0') {
4469 } /* while *p++ not NUL */
4472 USTPUTC('"', nextc
);
4478 /* cmdtxt() and cmdlist() call each other */
4479 static void cmdtxt(union node
*n
);
4482 cmdlist(union node
*np
, int sep
)
4484 for (; np
; np
= np
->narg
.next
) {
4488 if (sep
&& np
->narg
.next
)
4494 cmdtxt(union node
*n
)
4497 struct nodelist
*lp
;
4508 lp
= n
->npipe
.cmdlist
;
4526 cmdtxt(n
->nbinary
.ch1
);
4542 cmdtxt(n
->nif
.test
);
4544 if (n
->nif
.elsepart
) {
4545 cmdtxt(n
->nif
.ifpart
);
4547 n
= n
->nif
.elsepart
;
4565 cmdtxt(n
->nbinary
.ch1
);
4575 cmdputs(n
->nfor
.var
);
4577 cmdlist(n
->nfor
.args
, 1);
4582 cmdputs(n
->narg
.text
);
4586 cmdlist(n
->ncmd
.args
, 1);
4587 cmdlist(n
->ncmd
.redirect
, 0);
4600 cmdputs(n
->ncase
.expr
->narg
.text
);
4602 for (np
= n
->ncase
.cases
; np
; np
= np
->nclist
.next
) {
4603 cmdtxt(np
->nclist
.pattern
);
4605 cmdtxt(np
->nclist
.body
);
4619 #if ENABLE_ASH_BASH_COMPAT
4634 cmdputs(utoa(n
->nfile
.fd
));
4636 if (n
->type
== NTOFD
|| n
->type
== NFROMFD
) {
4637 cmdputs(utoa(n
->ndup
.dupfd
));
4646 commandtext(union node
*n
)
4650 STARTSTACKSTR(cmdnextc
);
4652 name
= stackblock();
4653 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4654 name
, cmdnextc
, cmdnextc
));
4655 return ckstrdup(name
);
4660 * Fork off a subshell. If we are doing job control, give the subshell its
4661 * own process group. Jp is a job structure that the job is to be added to.
4662 * N is the command that will be evaluated by the child. Both jp and n may
4663 * be NULL. The mode parameter can be one of the following:
4664 * FORK_FG - Fork off a foreground process.
4665 * FORK_BG - Fork off a background process.
4666 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4667 * process group even if job control is on.
4669 * When job control is turned off, background processes have their standard
4670 * input redirected to /dev/null (except for the second and later processes
4673 * Called with interrupts off.
4676 * Clear traps on a fork.
4683 for (tp
= trap
; tp
< &trap
[NSIG
]; tp
++) {
4684 if (*tp
&& **tp
) { /* trap not NULL or "" (SIG_IGN) */
4686 if (trap_ptr
== trap
)
4688 /* else: it "belongs" to trap_ptr vector, don't free */
4690 if ((tp
- trap
) != 0)
4691 setsignal(tp
- trap
);
4698 /* Lives far away from here, needed for forkchild */
4699 static void closescript(void);
4701 /* Called after fork(), in child */
4702 static NOINLINE
void
4703 forkchild(struct job
*jp
, union node
*n
, int mode
)
4707 TRACE(("Child shell %d\n", getpid()));
4711 /* man bash: "Non-builtin commands run by bash have signal handlers
4712 * set to the values inherited by the shell from its parent".
4713 * Do we do it correctly? */
4717 if (mode
== FORK_NOJOB
/* is it `xxx` ? */
4718 && n
&& n
->type
== NCMD
/* is it single cmd? */
4719 /* && n->ncmd.args->type == NARG - always true? */
4720 && n
->ncmd
.args
&& strcmp(n
->ncmd
.args
->narg
.text
, "trap") == 0
4721 && n
->ncmd
.args
->narg
.next
== NULL
/* "trap" with no arguments */
4722 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4724 TRACE(("Trap hack\n"));
4725 /* Awful hack for `trap` or $(trap).
4727 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4728 * contains an example where "trap" is executed in a subshell:
4730 * save_traps=$(trap)
4732 * eval "$save_traps"
4734 * Standard does not say that "trap" in subshell shall print
4735 * parent shell's traps. It only says that its output
4736 * must have suitable form, but then, in the above example
4737 * (which is not supposed to be normative), it implies that.
4739 * bash (and probably other shell) does implement it
4740 * (traps are reset to defaults, but "trap" still shows them),
4741 * but as a result, "trap" logic is hopelessly messed up:
4744 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4745 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4746 * # true | trap <--- trap is in subshell - no output (ditto)
4747 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4748 * trap -- 'echo Ho' SIGWINCH
4749 * # echo `(trap)` <--- in subshell in subshell - output
4750 * trap -- 'echo Ho' SIGWINCH
4751 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4752 * trap -- 'echo Ho' SIGWINCH
4754 * The rules when to forget and when to not forget traps
4755 * get really complex and nonsensical.
4757 * Our solution: ONLY bare $(trap) or `trap` is special.
4759 /* Save trap handler strings for trap builtin to print */
4760 trap_ptr
= memcpy(xmalloc(sizeof(trap
)), trap
, sizeof(trap
));
4761 /* Fall through into clearing traps */
4765 /* do job control only in root shell */
4767 if (mode
!= FORK_NOJOB
&& jp
->jobctl
&& oldlvl
== 0) {
4770 if (jp
->nprocs
== 0)
4773 pgrp
= jp
->ps
[0].ps_pid
;
4774 /* this can fail because we are doing it in the parent also */
4776 if (mode
== FORK_FG
)
4777 xtcsetpgrp(ttyfd
, pgrp
);
4782 if (mode
== FORK_BG
) {
4783 /* man bash: "When job control is not in effect,
4784 * asynchronous commands ignore SIGINT and SIGQUIT" */
4787 if (jp
->nprocs
== 0) {
4789 if (open(bb_dev_null
, O_RDONLY
) != 0)
4790 ash_msg_and_raise_error("can't open '%s'", bb_dev_null
);
4794 if (iflag
) { /* why if iflag only? */
4799 * "In all cases, bash ignores SIGQUIT. Non-builtin
4800 * commands run by bash have signal handlers
4801 * set to the values inherited by the shell
4803 * Take care of the second rule: */
4807 if (n
&& n
->type
== NCMD
4808 && n
->ncmd
.args
&& strcmp(n
->ncmd
.args
->narg
.text
, "jobs") == 0
4810 TRACE(("Job hack\n"));
4811 /* "jobs": we do not want to clear job list for it,
4812 * instead we remove only _its_ own_ job from job list.
4813 * This makes "jobs .... | cat" more useful.
4819 for (jp
= curjob
; jp
; jp
= jp
->prev_job
)
4824 /* Called after fork(), in parent */
4826 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4829 forkparent(struct job
*jp
, union node
*n
, int mode
, pid_t pid
)
4831 TRACE(("In parent shell: child = %d\n", pid
));
4833 while (jobless
&& dowait(DOWAIT_NONBLOCK
, NULL
) > 0)
4839 if (mode
!= FORK_NOJOB
&& jp
->jobctl
) {
4842 if (jp
->nprocs
== 0)
4845 pgrp
= jp
->ps
[0].ps_pid
;
4846 /* This can fail because we are doing it in the child also */
4850 if (mode
== FORK_BG
) {
4851 backgndpid
= pid
; /* set $! */
4852 set_curjob(jp
, CUR_RUNNING
);
4855 struct procstat
*ps
= &jp
->ps
[jp
->nprocs
++];
4858 ps
->ps_cmd
= nullstr
;
4860 if (doing_jobctl
&& n
)
4861 ps
->ps_cmd
= commandtext(n
);
4867 forkshell(struct job
*jp
, union node
*n
, int mode
)
4871 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp
), n
, mode
));
4874 TRACE(("Fork failed, errno=%d", errno
));
4877 ash_msg_and_raise_error("can't fork");
4880 CLEAR_RANDOM_T(&random_gen
); /* or else $RANDOM repeats in child */
4881 forkchild(jp
, n
, mode
);
4883 forkparent(jp
, n
, mode
, pid
);
4889 * Wait for job to finish.
4891 * Under job control we have the problem that while a child process
4892 * is running interrupts generated by the user are sent to the child
4893 * but not to the shell. This means that an infinite loop started by
4894 * an interactive user may be hard to kill. With job control turned off,
4895 * an interactive user may place an interactive program inside a loop.
4896 * If the interactive program catches interrupts, the user doesn't want
4897 * these interrupts to also abort the loop. The approach we take here
4898 * is to have the shell ignore interrupt signals while waiting for a
4899 * foreground process to terminate, and then send itself an interrupt
4900 * signal if the child process was terminated by an interrupt signal.
4901 * Unfortunately, some programs want to do a bit of cleanup and then
4902 * exit on interrupt; unless these processes terminate themselves by
4903 * sending a signal to themselves (instead of calling exit) they will
4904 * confuse this approach.
4906 * Called with interrupts off.
4909 waitforjob(struct job
*jp
)
4913 TRACE(("waitforjob(%%%d) called\n", jobno(jp
)));
4916 while (jp
->state
== JOBRUNNING
) {
4917 /* In non-interactive shells, we _can_ get
4918 * a keyboard signal here and be EINTRed,
4919 * but we just loop back, waiting for command to complete.
4922 * "If bash is waiting for a command to complete and receives
4923 * a signal for which a trap has been set, the trap
4924 * will not be executed until the command completes."
4926 * Reality is that even if trap is not set, bash
4927 * will not act on the signal until command completes.
4928 * Try this. sleep5intoff.c:
4929 * #include <signal.h>
4930 * #include <unistd.h>
4933 * sigemptyset(&set);
4934 * sigaddset(&set, SIGINT);
4935 * sigaddset(&set, SIGQUIT);
4936 * sigprocmask(SIG_BLOCK, &set, NULL);
4940 * $ bash -c './sleep5intoff; echo hi'
4941 * ^C^C^C^C <--- pressing ^C once a second
4943 * $ bash -c './sleep5intoff; echo hi'
4944 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4947 dowait(DOWAIT_BLOCK
, jp
);
4954 xtcsetpgrp(ttyfd
, rootpid
);
4956 * This is truly gross.
4957 * If we're doing job control, then we did a TIOCSPGRP which
4958 * caused us (the shell) to no longer be in the controlling
4959 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4960 * intuit from the subprocess exit status whether a SIGINT
4961 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4963 if (jp
->sigint
) /* TODO: do the same with all signals */
4964 raise(SIGINT
); /* ... by raise(jp->sig) instead? */
4966 if (jp
->state
== JOBDONE
)
4973 * return 1 if there are stopped jobs, otherwise 0
4985 if (jp
&& jp
->state
== JOBSTOPPED
) {
4986 out2str("You have stopped jobs.\n");
4995 /* ============ redir.c
4997 * Code for dealing with input/output redirection.
5002 #define EMPTY -2 /* marks an unused slot in redirtab */
5003 #define CLOSED -3 /* marks a slot of previously-closed fd */
5006 * Open a file in noclobber mode.
5007 * The code was copied from bash.
5010 noclobberopen(const char *fname
)
5013 struct stat finfo
, finfo2
;
5016 * If the file exists and is a regular file, return an error
5019 r
= stat(fname
, &finfo
);
5020 if (r
== 0 && S_ISREG(finfo
.st_mode
)) {
5026 * If the file was not present (r != 0), make sure we open it
5027 * exclusively so that if it is created before we open it, our open
5028 * will fail. Make sure that we do not truncate an existing file.
5029 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5030 * file was not a regular file, we leave O_EXCL off.
5033 return open(fname
, O_WRONLY
|O_CREAT
|O_EXCL
, 0666);
5034 fd
= open(fname
, O_WRONLY
|O_CREAT
, 0666);
5036 /* If the open failed, return the file descriptor right away. */
5041 * OK, the open succeeded, but the file may have been changed from a
5042 * non-regular file to a regular file between the stat and the open.
5043 * We are assuming that the O_EXCL open handles the case where FILENAME
5044 * did not exist and is symlinked to an existing file between the stat
5049 * If we can open it and fstat the file descriptor, and neither check
5050 * revealed that it was a regular file, and the file has not been
5051 * replaced, return the file descriptor.
5053 if (fstat(fd
, &finfo2
) == 0
5054 && !S_ISREG(finfo2
.st_mode
)
5055 && finfo
.st_dev
== finfo2
.st_dev
5056 && finfo
.st_ino
== finfo2
.st_ino
5061 /* The file has been replaced. badness. */
5068 * Handle here documents. Normally we fork off a process to write the
5069 * data to a pipe. If the document is short, we can stuff the data in
5070 * the pipe without forking.
5072 /* openhere needs this forward reference */
5073 static void expandhere(union node
*arg
, int fd
);
5075 openhere(union node
*redir
)
5081 ash_msg_and_raise_error("pipe call failed");
5082 if (redir
->type
== NHERE
) {
5083 len
= strlen(redir
->nhere
.doc
->narg
.text
);
5084 if (len
<= PIPE_BUF
) {
5085 full_write(pip
[1], redir
->nhere
.doc
->narg
.text
, len
);
5089 if (forkshell((struct job
*)NULL
, (union node
*)NULL
, FORK_NOJOB
) == 0) {
5092 ignoresig(SIGINT
); //signal(SIGINT, SIG_IGN);
5093 ignoresig(SIGQUIT
); //signal(SIGQUIT, SIG_IGN);
5094 ignoresig(SIGHUP
); //signal(SIGHUP, SIG_IGN);
5095 ignoresig(SIGTSTP
); //signal(SIGTSTP, SIG_IGN);
5096 signal(SIGPIPE
, SIG_DFL
);
5097 if (redir
->type
== NHERE
)
5098 full_write(pip
[1], redir
->nhere
.doc
->narg
.text
, len
);
5100 expandhere(redir
->nhere
.doc
, pip
[1]);
5101 _exit(EXIT_SUCCESS
);
5109 openredirect(union node
*redir
)
5114 fname
= redir
->nfile
.expfname
;
5115 switch (redir
->nfile
.type
) {
5117 f
= open(fname
, O_RDONLY
);
5122 f
= open(fname
, O_RDWR
|O_CREAT
, 0666);
5127 #if ENABLE_ASH_BASH_COMPAT
5130 /* Take care of noclobber mode. */
5132 f
= noclobberopen(fname
);
5139 f
= open(fname
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0666);
5144 f
= open(fname
, O_WRONLY
|O_CREAT
|O_APPEND
, 0666);
5152 /* Fall through to eliminate warning. */
5153 /* Our single caller does this itself */
5160 f
= openhere(redir
);
5166 ash_msg_and_raise_error("can't create %s: %s", fname
, errmsg(errno
, "nonexistent directory"));
5168 ash_msg_and_raise_error("can't open %s: %s", fname
, errmsg(errno
, "no such file"));
5172 * Copy a file descriptor to be >= to. Returns -1
5173 * if the source file descriptor is closed, EMPTY if there are no unused
5174 * file descriptors left.
5176 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5177 * old code was doing close(to) prior to copyfd() to achieve the same */
5179 COPYFD_EXACT
= (int)~(INT_MAX
),
5180 COPYFD_RESTORE
= (int)((unsigned)COPYFD_EXACT
>> 1),
5183 copyfd(int from
, int to
)
5187 if (to
& COPYFD_EXACT
) {
5188 to
&= ~COPYFD_EXACT
;
5190 newfd
= dup2(from
, to
);
5192 newfd
= fcntl(from
, F_DUPFD
, to
);
5195 if (errno
== EMFILE
)
5197 /* Happens when source fd is not open: try "echo >&99" */
5198 ash_msg_and_raise_error("%d: %m", from
);
5203 /* Struct def and variable are moved down to the first usage site */
5208 struct redirtab
*next
;
5211 struct two_fd_t two_fd
[];
5213 #define redirlist (G_var.redirlist)
5215 static int need_to_remember(struct redirtab
*rp
, int fd
)
5219 if (!rp
) /* remembering was not requested */
5222 for (i
= 0; i
< rp
->pair_count
; i
++) {
5223 if (rp
->two_fd
[i
].orig
== fd
) {
5224 /* already remembered */
5231 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5232 static int is_hidden_fd(struct redirtab
*rp
, int fd
)
5235 struct parsefile
*pf
;
5239 /* Check open scripts' fds */
5242 /* We skip pf_fd == 0 case because of the following case:
5243 * $ ash # running ash interactively
5245 * and in script.sh: "exec 9>&0".
5246 * Even though top-level pf_fd _is_ 0,
5247 * it's still ok to use it: "read" builtin uses it,
5248 * why should we cripple "exec" builtin?
5250 if (pf
->pf_fd
> 0 && fd
== pf
->pf_fd
) {
5258 /* Check saved fds of redirects */
5259 fd
|= COPYFD_RESTORE
;
5260 for (i
= 0; i
< rp
->pair_count
; i
++) {
5261 if (rp
->two_fd
[i
].copy
== fd
) {
5269 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5270 * old file descriptors are stashed away so that the redirection can be
5271 * undone by calling popredir.
5273 /* flags passed to redirect */
5274 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5275 #define REDIR_SAVEFD2 03 /* set preverrout */
5277 redirect(union node
*redir
, int flags
)
5279 struct redirtab
*sv
;
5284 int copied_fd2
= -1;
5294 if (flags
& REDIR_PUSH
) {
5295 union node
*tmp
= redir
;
5298 #if ENABLE_ASH_BASH_COMPAT
5299 if (tmp
->nfile
.type
== NTO2
)
5302 tmp
= tmp
->nfile
.next
;
5304 sv
= ckmalloc(sizeof(*sv
) + sv_pos
* sizeof(sv
->two_fd
[0]));
5305 sv
->next
= redirlist
;
5306 sv
->pair_count
= sv_pos
;
5308 sv
->nullredirs
= g_nullredirs
- 1;
5310 while (sv_pos
> 0) {
5312 sv
->two_fd
[sv_pos
].orig
= sv
->two_fd
[sv_pos
].copy
= EMPTY
;
5318 fd
= redir
->nfile
.fd
;
5319 if (redir
->nfile
.type
== NTOFD
|| redir
->nfile
.type
== NFROMFD
) {
5320 right_fd
= redir
->ndup
.dupfd
;
5321 //bb_error_msg("doing %d > %d", fd, right_fd);
5322 /* redirect from/to same file descriptor? */
5325 /* "echo >&10" and 10 is a fd opened to a sh script? */
5326 if (is_hidden_fd(sv
, right_fd
)) {
5327 errno
= EBADF
; /* as if it is closed */
5328 ash_msg_and_raise_error("%d: %m", right_fd
);
5332 newfd
= openredirect(redir
); /* always >= 0 */
5334 /* Descriptor wasn't open before redirect.
5335 * Mark it for close in the future */
5336 if (need_to_remember(sv
, fd
)) {
5337 goto remember_to_close
;
5342 #if ENABLE_ASH_BASH_COMPAT
5345 if (need_to_remember(sv
, fd
)) {
5346 /* Copy old descriptor */
5347 /* Careful to not accidentally "save"
5348 * to the same fd as right side fd in N>&M */
5349 int minfd
= right_fd
< 10 ? 10 : right_fd
+ 1;
5350 i
= fcntl(fd
, F_DUPFD
, minfd
);
5351 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5352 * are closed in popredir() in the child, preventing them from leaking
5353 * into child. (popredir() also cleans up the mess in case of failures)
5358 /* Strange error (e.g. "too many files" EMFILE?) */
5362 ash_msg_and_raise_error("%d: %m", fd
);
5365 /* EBADF: it is not open - good, remember to close it */
5368 } else { /* fd is open, save its copy */
5369 /* "exec fd>&-" should not close fds
5370 * which point to script file(s).
5371 * Force them to be restored afterwards */
5372 if (is_hidden_fd(sv
, fd
))
5373 i
|= COPYFD_RESTORE
;
5377 sv
->two_fd
[sv_pos
].orig
= fd
;
5378 sv
->two_fd
[sv_pos
].copy
= i
;
5382 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5383 if (redir
->ndup
.dupfd
< 0) { /* "fd>&-" */
5384 /* Don't want to trigger debugging */
5388 copyfd(redir
->ndup
.dupfd
, fd
| COPYFD_EXACT
);
5390 } else if (fd
!= newfd
) { /* move newfd to fd */
5391 copyfd(newfd
, fd
| COPYFD_EXACT
);
5392 #if ENABLE_ASH_BASH_COMPAT
5393 if (!(redir
->nfile
.type
== NTO2
&& fd
== 2))
5397 #if ENABLE_ASH_BASH_COMPAT
5398 if (redir
->nfile
.type
== NTO2
&& fd
== 1) {
5399 /* We already redirected it to fd 1, now copy it to 2 */
5405 } while ((redir
= redir
->nfile
.next
) != NULL
);
5408 if ((flags
& REDIR_SAVEFD2
) && copied_fd2
>= 0)
5409 preverrout_fd
= copied_fd2
;
5413 * Undo the effects of the last redirection.
5416 popredir(int drop
, int restore
)
5418 struct redirtab
*rp
;
5421 if (--g_nullredirs
>= 0)
5425 for (i
= 0; i
< rp
->pair_count
; i
++) {
5426 int fd
= rp
->two_fd
[i
].orig
;
5427 int copy
= rp
->two_fd
[i
].copy
;
5428 if (copy
== CLOSED
) {
5433 if (copy
!= EMPTY
) {
5434 if (!drop
|| (restore
&& (copy
& COPYFD_RESTORE
))) {
5435 copy
&= ~COPYFD_RESTORE
;
5437 copyfd(copy
, fd
| COPYFD_EXACT
);
5439 close(copy
& ~COPYFD_RESTORE
);
5442 redirlist
= rp
->next
;
5443 g_nullredirs
= rp
->nullredirs
;
5449 * Undo all redirections. Called on error or interrupt.
5453 * Discard all saved file descriptors.
5456 clearredir(int drop
)
5462 popredir(drop
, /*restore:*/ 0);
5467 redirectsafe(union node
*redir
, int flags
)
5470 volatile int saveint
;
5471 struct jmploc
*volatile savehandler
= exception_handler
;
5472 struct jmploc jmploc
;
5475 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5476 err
= setjmp(jmploc
.loc
); // huh?? was = setjmp(jmploc.loc) * 2;
5478 exception_handler
= &jmploc
;
5479 redirect(redir
, flags
);
5481 exception_handler
= savehandler
;
5482 if (err
&& exception_type
!= EXERROR
)
5483 longjmp(exception_handler
->loc
, 1);
5484 RESTORE_INT(saveint
);
5489 /* ============ Routines to expand arguments to commands
5491 * We have to deal with backquotes, shell variables, and file metacharacters.
5494 #if ENABLE_SH_MATH_SUPPORT
5496 ash_arith(const char *s
)
5498 arith_state_t math_state
;
5501 math_state
.lookupvar
= lookupvar
;
5502 math_state
.setvar
= setvar2
;
5503 //math_state.endofname = endofname;
5506 result
= arith(&math_state
, s
);
5507 if (math_state
.errmsg
)
5508 ash_msg_and_raise_error(math_state
.errmsg
);
5518 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5519 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5520 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5521 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5522 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5523 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5524 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5525 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5526 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5530 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5531 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5532 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5533 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5534 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5537 * Structure specifying which parts of the string should be searched
5538 * for IFS characters.
5541 struct ifsregion
*next
; /* next region in list */
5542 int begoff
; /* offset of start of region */
5543 int endoff
; /* offset of end of region */
5544 int nulonly
; /* search for nul bytes only */
5548 struct strlist
*list
;
5549 struct strlist
**lastp
;
5552 /* output of current string */
5553 static char *expdest
;
5554 /* list of back quote expressions */
5555 static struct nodelist
*argbackq
;
5556 /* first struct in list of ifs regions */
5557 static struct ifsregion ifsfirst
;
5558 /* last struct in list */
5559 static struct ifsregion
*ifslastp
;
5560 /* holds expanded arg list */
5561 static struct arglist exparg
;
5566 #if !ENABLE_SH_MATH_SUPPORT
5567 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5568 typedef long arith_t
;
5569 # define ARITH_FMT "%ld"
5576 expdest
= makestrspace(32, expdest
);
5577 len
= fmtstr(expdest
, 32, ARITH_FMT
, num
);
5578 STADJUST(len
, expdest
);
5583 esclen(const char *start
, const char *p
)
5587 while (p
> start
&& (unsigned char)*--p
== CTLESC
) {
5594 * Remove any CTLESC characters from a string.
5597 rmescapes(char *str
, int flag
)
5599 static const char qchars
[] ALIGN1
= { CTLESC
, CTLQUOTEMARK
, '\0' };
5603 unsigned protect_against_glob
;
5606 p
= strpbrk(str
, qchars
);
5612 if (flag
& RMESCAPE_ALLOC
) {
5613 size_t len
= p
- str
;
5614 size_t fulllen
= len
+ strlen(p
) + 1;
5616 if (flag
& RMESCAPE_GROW
) {
5617 int strloc
= str
- (char *)stackblock();
5618 r
= makestrspace(fulllen
, expdest
);
5619 /* p and str may be invalidated by makestrspace */
5620 str
= (char *)stackblock() + strloc
;
5622 } else if (flag
& RMESCAPE_HEAP
) {
5623 r
= ckmalloc(fulllen
);
5625 r
= stalloc(fulllen
);
5629 q
= (char *)memcpy(q
, str
, len
) + len
;
5633 inquotes
= (flag
& RMESCAPE_QUOTED
) ^ RMESCAPE_QUOTED
;
5634 globbing
= flag
& RMESCAPE_GLOB
;
5635 protect_against_glob
= globbing
;
5637 if ((unsigned char)*p
== CTLQUOTEMARK
) {
5638 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5639 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5640 // Note: both inquotes and protect_against_glob only affect whether
5641 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5642 inquotes
= ~inquotes
;
5644 protect_against_glob
= globbing
;
5648 /* naked back slash */
5649 protect_against_glob
= 0;
5652 if ((unsigned char)*p
== CTLESC
) {
5654 if (protect_against_glob
&& inquotes
&& *p
!= '/') {
5658 protect_against_glob
= globbing
;
5663 if (flag
& RMESCAPE_GROW
) {
5665 STADJUST(q
- r
+ 1, expdest
);
5669 #define pmatch(a, b) !fnmatch((a), (b), 0)
5672 * Prepare a pattern for a expmeta (internal glob(3)) call.
5674 * Returns an stalloced string.
5677 preglob(const char *pattern
, int quoted
, int flag
)
5679 flag
|= RMESCAPE_GLOB
;
5681 flag
|= RMESCAPE_QUOTED
;
5683 return rmescapes((char *)pattern
, flag
);
5687 * Put a string on the stack.
5690 memtodest(const char *p
, size_t len
, int syntax
, int quotes
)
5694 q
= makestrspace(quotes
? len
* 2 : len
, q
);
5697 unsigned char c
= *p
++;
5701 int n
= SIT(c
, syntax
);
5702 if (n
== CCTL
|| n
== CBACK
)
5712 strtodest(const char *p
, int syntax
, int quotes
)
5714 memtodest(p
, strlen(p
), syntax
, quotes
);
5718 * Record the fact that we have to scan this region of the
5719 * string for IFS characters.
5722 recordregion(int start
, int end
, int nulonly
)
5724 struct ifsregion
*ifsp
;
5726 if (ifslastp
== NULL
) {
5730 ifsp
= ckzalloc(sizeof(*ifsp
));
5731 /*ifsp->next = NULL; - ckzalloc did it */
5732 ifslastp
->next
= ifsp
;
5736 ifslastp
->begoff
= start
;
5737 ifslastp
->endoff
= end
;
5738 ifslastp
->nulonly
= nulonly
;
5742 removerecordregions(int endoff
)
5744 if (ifslastp
== NULL
)
5747 if (ifsfirst
.endoff
> endoff
) {
5748 while (ifsfirst
.next
) {
5749 struct ifsregion
*ifsp
;
5751 ifsp
= ifsfirst
.next
->next
;
5752 free(ifsfirst
.next
);
5753 ifsfirst
.next
= ifsp
;
5756 if (ifsfirst
.begoff
> endoff
) {
5759 ifslastp
= &ifsfirst
;
5760 ifsfirst
.endoff
= endoff
;
5765 ifslastp
= &ifsfirst
;
5766 while (ifslastp
->next
&& ifslastp
->next
->begoff
< endoff
)
5767 ifslastp
= ifslastp
->next
;
5768 while (ifslastp
->next
) {
5769 struct ifsregion
*ifsp
;
5771 ifsp
= ifslastp
->next
->next
;
5772 free(ifslastp
->next
);
5773 ifslastp
->next
= ifsp
;
5776 if (ifslastp
->endoff
> endoff
)
5777 ifslastp
->endoff
= endoff
;
5781 exptilde(char *startp
, char *p
, int flags
)
5787 int quotes
= flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
);
5792 while ((c
= *++p
) != '\0') {
5799 if (flags
& EXP_VARTILDE
)
5809 if (*name
== '\0') {
5810 home
= lookupvar("HOME");
5812 pw
= getpwnam(name
);
5817 if (!home
|| !*home
)
5820 startloc
= expdest
- (char *)stackblock();
5821 strtodest(home
, SQSYNTAX
, quotes
);
5822 recordregion(startloc
, expdest
- (char *)stackblock(), 0);
5830 * Execute a command inside back quotes. If it's a builtin command, we
5831 * want to save its output in a block obtained from malloc. Otherwise
5832 * we fork off a subprocess and get the output of the command via a pipe.
5833 * Should be called with interrupts off.
5835 struct backcmd
{ /* result of evalbackcmd */
5836 int fd
; /* file descriptor to read from */
5837 int nleft
; /* number of chars in buffer */
5838 char *buf
; /* buffer */
5839 struct job
*jp
; /* job structure for command */
5842 /* These forward decls are needed to use "eval" code for backticks handling: */
5843 static uint8_t back_exitstatus
; /* exit status of backquoted command */
5844 #define EV_EXIT 01 /* exit after evaluating tree */
5845 static void evaltree(union node
*, int);
5847 static void FAST_FUNC
5848 evalbackcmd(union node
*n
, struct backcmd
*result
)
5859 saveherefd
= herefd
;
5867 ash_msg_and_raise_error("pipe call failed");
5868 jp
= makejob(/*n,*/ 1);
5869 if (forkshell(jp
, n
, FORK_NOJOB
) == 0) {
5874 copyfd(pip
[1], 1 | COPYFD_EXACT
);
5878 evaltree(n
, EV_EXIT
); /* actually evaltreenr... */
5882 result
->fd
= pip
[0];
5885 herefd
= saveherefd
;
5887 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5888 result
->fd
, result
->buf
, result
->nleft
, result
->jp
));
5892 * Expand stuff in backwards quotes.
5895 expbackq(union node
*cmd
, int quoted
, int quotes
)
5903 int syntax
= quoted
? DQSYNTAX
: BASESYNTAX
;
5904 struct stackmark smark
;
5907 setstackmark(&smark
);
5909 startloc
= dest
- (char *)stackblock();
5911 evalbackcmd(cmd
, &in
);
5912 popstackmark(&smark
);
5919 memtodest(p
, i
, syntax
, quotes
);
5923 i
= nonblock_immune_read(in
.fd
, buf
, sizeof(buf
), /*loop_on_EINTR:*/ 1);
5924 TRACE(("expbackq: read returns %d\n", i
));
5933 back_exitstatus
= waitforjob(in
.jp
);
5937 /* Eat all trailing newlines */
5939 for (; dest
> (char *)stackblock() && dest
[-1] == '\n';)
5944 recordregion(startloc
, dest
- (char *)stackblock(), 0);
5945 TRACE(("evalbackq: size:%d:'%.*s'\n",
5946 (int)((dest
- (char *)stackblock()) - startloc
),
5947 (int)((dest
- (char *)stackblock()) - startloc
),
5948 stackblock() + startloc
));
5951 #if ENABLE_SH_MATH_SUPPORT
5953 * Expand arithmetic expression. Backup to start of expression,
5954 * evaluate, place result in (backed up) result, adjust string position.
5967 * This routine is slightly over-complicated for
5968 * efficiency. Next we scan backwards looking for the
5969 * start of arithmetic.
5971 start
= stackblock();
5978 while ((unsigned char)*p
!= CTLARI
) {
5982 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5987 esc
= esclen(start
, p
);
5997 removerecordregions(begoff
);
6004 rmescapes(p
+ 2, 0);
6006 len
= cvtnum(ash_arith(p
+ 2));
6009 recordregion(begoff
, begoff
+ len
, 0);
6013 /* argstr needs it */
6014 static char *evalvar(char *p
, int flags
, struct strlist
*var_str_list
);
6017 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6018 * characters to allow for further processing. Otherwise treat
6019 * $@ like $* since no splitting will be performed.
6021 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6022 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6023 * for correct expansion of "B=$A" word.
6026 argstr(char *p
, int flags
, struct strlist
*var_str_list
)
6028 static const char spclchars
[] ALIGN1
= {
6036 CTLBACKQ
| CTLQUOTE
,
6037 #if ENABLE_SH_MATH_SUPPORT
6042 const char *reject
= spclchars
;
6043 int quotes
= flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
); /* do CTLESC */
6044 int breakall
= flags
& EXP_WORD
;
6049 if (!(flags
& EXP_VARTILDE
)) {
6051 } else if (flags
& EXP_VARTILDE2
) {
6056 if (flags
& EXP_TILDE
) {
6059 flags
&= ~EXP_TILDE
;
6062 if ((unsigned char)*q
== CTLESC
&& (flags
& EXP_QWORD
))
6065 p
= exptilde(p
, q
, flags
);
6068 startloc
= expdest
- (char *)stackblock();
6072 length
+= strcspn(p
+ length
, reject
);
6076 IF_SH_MATH_SUPPORT(|| c
== CTLENDARI
)
6078 /* c == '=' || c == ':' || c == CTLENDARI */
6084 expdest
= stack_nputstr(p
, length
, expdest
);
6085 newloc
= expdest
- (char *)stackblock();
6086 if (breakall
&& !inquotes
&& newloc
> startloc
) {
6087 recordregion(startloc
, newloc
, 0);
6098 if (flags
& EXP_VARTILDE2
) {
6102 flags
|= EXP_VARTILDE2
;
6107 * sort of a hack - expand tildes in variable
6108 * assignments (after the first '=' and after ':'s).
6117 case CTLENDVAR
: /* ??? */
6120 /* "$@" syntax adherence hack */
6122 && memcmp(p
, dolatstr
, 4) == 0
6123 && ( p
[4] == (char)CTLQUOTEMARK
6124 || (p
[4] == (char)CTLENDVAR
&& p
[5] == (char)CTLQUOTEMARK
)
6127 p
= evalvar(p
+ 1, flags
, /* var_str_list: */ NULL
) + 1;
6130 inquotes
= !inquotes
;
6143 TRACE(("argstr: evalvar('%s')\n", p
));
6144 p
= evalvar(p
, flags
, var_str_list
);
6145 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6149 case CTLBACKQ
|CTLQUOTE
:
6150 expbackq(argbackq
->n
, c
, quotes
);
6151 argbackq
= argbackq
->next
;
6153 #if ENABLE_SH_MATH_SUPPORT
6165 scanleft(char *startp
, char *rmesc
, char *rmescend UNUSED_PARAM
,
6166 char *pattern
, int quotes
, int zero
)
6175 const char *s
= loc2
;
6182 match
= pmatch(pattern
, s
);
6187 if (quotes
&& (unsigned char)*loc
== CTLESC
)
6196 scanright(char *startp
, char *rmesc
, char *rmescend
,
6197 char *pattern
, int quotes
, int match_at_start
)
6199 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6200 int try2optimize
= match_at_start
;
6206 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6207 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6208 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6210 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6211 * and on each iteration they go back two/one char until they reach the beginning.
6212 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6214 /* TODO: document in what other circumstances we are called. */
6216 for (loc
= pattern
- 1, loc2
= rmescend
; loc
>= startp
; loc2
--) {
6219 const char *s
= loc2
;
6220 if (match_at_start
) {
6224 match
= pmatch(pattern
, s
);
6225 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6229 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6231 /* Maybe we can optimize this:
6232 * if pattern ends with unescaped *, we can avoid checking
6233 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6234 * it wont match truncated "raw_value_of_" strings too.
6236 unsigned plen
= strlen(pattern
);
6237 /* Does it end with "*"? */
6238 if (plen
!= 0 && pattern
[--plen
] == '*') {
6239 /* "xxxx*" is not escaped */
6240 /* "xxx\*" is escaped */
6241 /* "xx\\*" is not escaped */
6242 /* "x\\\*" is escaped */
6244 while (plen
!= 0 && pattern
[--plen
] == '\\')
6247 break; /* ends with unescaped "*" */
6255 esc
= esclen(startp
, loc
);
6266 static void varunset(const char *, const char *, const char *, int) NORETURN
;
6268 varunset(const char *end
, const char *var
, const char *umsg
, int varflags
)
6274 msg
= "parameter not set";
6276 if ((unsigned char)*end
== CTLENDVAR
) {
6277 if (varflags
& VSNUL
)
6283 ash_msg_and_raise_error("%.*s: %s%s", (int)(end
- var
- 1), var
, msg
, tail
);
6286 #if ENABLE_ASH_BASH_COMPAT
6288 parse_sub_pattern(char *arg
, int varflags
)
6290 char *idx
, *repl
= NULL
;
6293 //char *org_arg = arg;
6294 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6301 /* Only the first '/' seen is our separator */
6310 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6311 * The result is a_\_z_c (not a\_\_z_c)!
6313 * Enable debug prints in this function and you'll see:
6314 * ash: arg:'\\b/_\\_z_' varflags:d
6315 * ash: pattern:'\\b' repl:'_\_z_'
6316 * That is, \\b is interpreted as \\b, but \\_ as \_!
6317 * IOW: search pattern and replace string treat backslashes
6318 * differently! That is the reason why we check repl below:
6320 if (c
== '\\' && *arg
== '\\' && repl
&& !(varflags
& VSQUOTE
))
6321 arg
++; /* skip both '\', not just first one */
6324 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6328 #endif /* ENABLE_ASH_BASH_COMPAT */
6331 subevalvar(char *p
, char *varname
, int strloc
, int subtype
,
6332 int startloc
, int varflags
, int quotes
, struct strlist
*var_str_list
)
6334 struct nodelist
*saveargbackq
= argbackq
;
6337 char *rmesc
, *rmescend
;
6339 IF_ASH_BASH_COMPAT(const char *repl
= NULL
;)
6340 IF_ASH_BASH_COMPAT(int pos
, len
, orig_len
;)
6341 int saveherefd
= herefd
;
6342 int amount
, resetloc
;
6343 IF_ASH_BASH_COMPAT(int workloc
;)
6345 char *(*scan
)(char*, char*, char*, char*, int, int);
6347 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6348 // p, varname, strloc, subtype, startloc, varflags, quotes);
6351 argstr(p
, (subtype
!= VSASSIGN
&& subtype
!= VSQUESTION
) ? EXP_CASE
: 0,
6353 STPUTC('\0', expdest
);
6354 herefd
= saveherefd
;
6355 argbackq
= saveargbackq
;
6356 startp
= (char *)stackblock() + startloc
;
6360 setvar(varname
, startp
, 0);
6361 amount
= startp
- expdest
;
6362 STADJUST(amount
, expdest
);
6366 varunset(p
, varname
, startp
, varflags
);
6369 #if ENABLE_ASH_BASH_COMPAT
6371 loc
= str
= stackblock() + strloc
;
6372 /* Read POS in ${var:POS:LEN} */
6373 pos
= atoi(loc
); /* number(loc) errors out on "1:4" */
6374 len
= str
- startp
- 1;
6376 /* *loc != '\0', guaranteed by parser */
6380 /* Adjust the length by the number of escapes */
6381 for (ptr
= startp
; ptr
< (str
- 1); ptr
++) {
6382 if ((unsigned char)*ptr
== CTLESC
) {
6390 if (*loc
++ == ':') {
6394 /* Skip POS in ${var:POS:LEN} */
6396 while (*loc
&& *loc
!= ':') {
6398 * bash complains on: var=qwe; echo ${var:1a:123}
6400 ash_msg_and_raise_error(msg_illnum, str);
6404 if (*loc
++ == ':') {
6408 if (pos
>= orig_len
) {
6412 if (len
> (orig_len
- pos
))
6413 len
= orig_len
- pos
;
6415 for (str
= startp
; pos
; str
++, pos
--) {
6416 if (quotes
&& (unsigned char)*str
== CTLESC
)
6419 for (loc
= startp
; len
; len
--) {
6420 if (quotes
&& (unsigned char)*str
== CTLESC
)
6425 amount
= loc
- expdest
;
6426 STADJUST(amount
, expdest
);
6431 resetloc
= expdest
- (char *)stackblock();
6433 /* We'll comeback here if we grow the stack while handling
6434 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6435 * stack will need rebasing, and we'll need to remove our work
6438 IF_ASH_BASH_COMPAT(restart
:)
6440 amount
= expdest
- ((char *)stackblock() + resetloc
);
6441 STADJUST(-amount
, expdest
);
6442 startp
= (char *)stackblock() + startloc
;
6445 rmescend
= (char *)stackblock() + strloc
;
6447 rmesc
= rmescapes(startp
, RMESCAPE_ALLOC
| RMESCAPE_GROW
);
6448 if (rmesc
!= startp
) {
6450 startp
= (char *)stackblock() + startloc
;
6454 str
= (char *)stackblock() + strloc
;
6455 preglob(str
, varflags
& VSQUOTE
, 0);
6457 #if ENABLE_ASH_BASH_COMPAT
6458 workloc
= expdest
- (char *)stackblock();
6459 if (subtype
== VSREPLACE
|| subtype
== VSREPLACEALL
) {
6463 repl
= parse_sub_pattern(str
, varflags
);
6464 //bb_error_msg("repl:'%s'", repl);
6469 /* If there's no pattern to match, return the expansion unmolested */
6478 loc
= scanright(idx
, rmesc
, rmescend
, str
, quotes
, 1);
6479 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6481 /* No match, advance */
6482 char *restart_detect
= stackblock();
6484 STPUTC(*idx
, expdest
);
6485 if (quotes
&& (unsigned char)*idx
== CTLESC
) {
6488 STPUTC(*idx
, expdest
);
6490 if (stackblock() != restart_detect
)
6495 /* continue; - prone to quadratic behavior, smarter code: */
6498 if (str
[0] == '*') {
6499 /* Pattern is "*foo". If "*foo" does not match "long_string",
6500 * it would never match "ong_string" etc, no point in trying.
6507 if (subtype
== VSREPLACEALL
) {
6509 if (quotes
&& (unsigned char)*idx
== CTLESC
)
6518 //bb_error_msg("repl:'%s'", repl);
6519 for (loc
= (char*)repl
; *loc
; loc
++) {
6520 char *restart_detect
= stackblock();
6521 if (quotes
&& *loc
== '\\') {
6522 STPUTC(CTLESC
, expdest
);
6525 STPUTC(*loc
, expdest
);
6526 if (stackblock() != restart_detect
)
6531 if (subtype
== VSREPLACE
) {
6532 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6534 char *restart_detect
= stackblock();
6535 STPUTC(*idx
, expdest
);
6536 if (stackblock() != restart_detect
)
6545 /* We've put the replaced text into a buffer at workloc, now
6546 * move it to the right place and adjust the stack.
6548 STPUTC('\0', expdest
);
6549 startp
= (char *)stackblock() + startloc
;
6550 memmove(startp
, (char *)stackblock() + workloc
, len
+ 1);
6551 //bb_error_msg("startp:'%s'", startp);
6552 amount
= expdest
- (startp
+ len
);
6553 STADJUST(-amount
, expdest
);
6556 #endif /* ENABLE_ASH_BASH_COMPAT */
6558 subtype
-= VSTRIMRIGHT
;
6560 if (subtype
< 0 || subtype
> 7)
6563 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6564 zero
= subtype
>> 1;
6565 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6566 scan
= (subtype
& 1) ^ zero
? scanleft
: scanright
;
6568 loc
= scan(startp
, rmesc
, rmescend
, str
, quotes
, zero
);
6571 memmove(startp
, loc
, str
- loc
);
6572 loc
= startp
+ (str
- loc
) - 1;
6575 amount
= loc
- expdest
;
6576 STADJUST(amount
, expdest
);
6582 * Add the value of a specialized variable to the stack string.
6583 * name parameter (examples):
6584 * ash -c 'echo $1' name:'1='
6585 * ash -c 'echo $qwe' name:'qwe='
6586 * ash -c 'echo $$' name:'$='
6587 * ash -c 'echo ${$}' name:'$='
6588 * ash -c 'echo ${$##q}' name:'$=q'
6589 * ash -c 'echo ${#$}' name:'$='
6590 * note: examples with bad shell syntax:
6591 * ash -c 'echo ${#$1}' name:'$=1'
6592 * ash -c 'echo ${#1#}' name:'1=#'
6594 static NOINLINE ssize_t
6595 varvalue(char *name
, int varflags
, int flags
, struct strlist
*var_str_list
)
6602 int subtype
= varflags
& VSTYPE
;
6603 int quotes
= flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
);
6604 int quoted
= varflags
& VSQUOTE
;
6605 int syntax
= quoted
? DQSYNTAX
: BASESYNTAX
;
6615 num
= shellparam
.nparam
;
6623 goto check_1char_name
;
6625 expdest
= makestrspace(NOPTS
, expdest
);
6626 for (i
= NOPTS
- 1; i
>= 0; i
--) {
6628 USTPUTC(optletters(i
), expdest
);
6634 /* handles cases similar to ${#$1} */
6635 if (name
[2] != '\0')
6636 raise_error_syntax("bad substitution");
6643 if (quoted
&& (flags
& EXP_FULL
)) {
6644 /* note: this is not meant as PEOF value */
6645 sep
= 1 << CHAR_BIT
;
6650 sep
= ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6651 i
= SIT(sep
, syntax
);
6652 if (quotes
&& (i
== CCTL
|| i
== CBACK
))
6658 while ((p
= *ap
++) != NULL
) {
6661 partlen
= strlen(p
);
6664 if (!(subtype
== VSPLUS
|| subtype
== VSLENGTH
))
6665 memtodest(p
, partlen
, syntax
, quotes
);
6671 if (subtype
== VSPLUS
|| subtype
== VSLENGTH
) {
6677 /* note: may put NUL despite sep != 0
6678 * (see sep = 1 << CHAR_BIT above) */
6684 } /* case '@' and '*' */
6695 num
= atoi(name
); /* number(name) fails on ${N#str} etc */
6696 if (num
< 0 || num
> shellparam
.nparam
)
6698 p
= num
? shellparam
.p
[num
- 1] : arg0
;
6701 /* NB: name has form "VAR=..." */
6703 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6704 * which should be considered before we check variables. */
6706 unsigned name_len
= (strchrnul(name
, '=') - name
) + 1;
6710 str
= var_str_list
->text
;
6711 eq
= strchr(str
, '=');
6712 if (!eq
) /* stop at first non-assignment */
6715 if (name_len
== (unsigned)(eq
- str
)
6716 && strncmp(str
, name
, name_len
) == 0
6719 /* goto value; - WRONG! */
6720 /* think "A=1 A=2 B=$A" */
6722 var_str_list
= var_str_list
->next
;
6723 } while (var_str_list
);
6727 p
= lookupvar(name
);
6733 if (!(subtype
== VSPLUS
|| subtype
== VSLENGTH
))
6734 memtodest(p
, len
, syntax
, quotes
);
6738 if (subtype
== VSPLUS
|| subtype
== VSLENGTH
)
6739 STADJUST(-len
, expdest
);
6744 * Expand a variable, and return a pointer to the next character in the
6748 evalvar(char *p
, int flags
, struct strlist
*var_str_list
)
6759 varflags
= (unsigned char) *p
++;
6760 subtype
= varflags
& VSTYPE
;
6761 quoted
= varflags
& VSQUOTE
;
6763 easy
= (!quoted
|| (*var
== '@' && shellparam
.nparam
));
6764 startloc
= expdest
- (char *)stackblock();
6765 p
= strchr(p
, '=') + 1; //TODO: use var_end(p)?
6768 varlen
= varvalue(var
, varflags
, flags
, var_str_list
);
6769 if (varflags
& VSNUL
)
6772 if (subtype
== VSPLUS
) {
6773 varlen
= -1 - varlen
;
6777 if (subtype
== VSMINUS
) {
6782 flags
| (quoted
? EXP_TILDE
|EXP_QWORD
: EXP_TILDE
|EXP_WORD
),
6792 if (subtype
== VSASSIGN
|| subtype
== VSQUESTION
) {
6794 if (subevalvar(p
, var
, /* strloc: */ 0,
6795 subtype
, startloc
, varflags
,
6801 * Remove any recorded regions beyond
6804 removerecordregions(startloc
);
6814 if (varlen
< 0 && uflag
)
6815 varunset(p
, var
, 0, 0);
6817 if (subtype
== VSLENGTH
) {
6818 cvtnum(varlen
> 0 ? varlen
: 0);
6822 if (subtype
== VSNORMAL
) {
6833 case VSTRIMRIGHTMAX
:
6834 #if ENABLE_ASH_BASH_COMPAT
6847 * Terminate the string and start recording the pattern
6850 STPUTC('\0', expdest
);
6851 patloc
= expdest
- (char *)stackblock();
6852 if (NULL
== subevalvar(p
, /* varname: */ NULL
, patloc
, subtype
,
6854 /* quotes: */ flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
),
6857 int amount
= expdest
- (
6858 (char *)stackblock() + patloc
- 1
6860 STADJUST(-amount
, expdest
);
6862 /* Remove any recorded regions beyond start of variable */
6863 removerecordregions(startloc
);
6865 recordregion(startloc
, expdest
- (char *)stackblock(), quoted
);
6869 if (subtype
!= VSNORMAL
) { /* skip to end of alternative */
6872 unsigned char c
= *p
++;
6875 else if (c
== CTLBACKQ
|| c
== (CTLBACKQ
|CTLQUOTE
)) {
6877 argbackq
= argbackq
->next
;
6878 } else if (c
== CTLVAR
) {
6879 if ((*p
++ & VSTYPE
) != VSNORMAL
)
6881 } else if (c
== CTLENDVAR
) {
6891 * Break the argument string into pieces based upon IFS and add the
6892 * strings to the argument list. The regions of the string to be
6893 * searched for IFS characters have been stored by recordregion.
6896 ifsbreakup(char *string
, struct arglist
*arglist
)
6898 struct ifsregion
*ifsp
;
6903 const char *ifs
, *realifs
;
6908 if (ifslastp
!= NULL
) {
6911 realifs
= ifsset() ? ifsval() : defifs
;
6914 p
= string
+ ifsp
->begoff
;
6915 nulonly
= ifsp
->nulonly
;
6916 ifs
= nulonly
? nullstr
: realifs
;
6918 while (p
< string
+ ifsp
->endoff
) {
6920 if ((unsigned char)*p
== CTLESC
)
6922 if (!strchr(ifs
, *p
)) {
6927 ifsspc
= (strchr(defifs
, *p
) != NULL
);
6928 /* Ignore IFS whitespace at start */
6929 if (q
== start
&& ifsspc
) {
6935 sp
= stzalloc(sizeof(*sp
));
6937 *arglist
->lastp
= sp
;
6938 arglist
->lastp
= &sp
->next
;
6942 if (p
>= string
+ ifsp
->endoff
) {
6946 if ((unsigned char)*p
== CTLESC
)
6948 if (strchr(ifs
, *p
) == NULL
) {
6952 if (strchr(defifs
, *p
) == NULL
) {
6967 } while (ifsp
!= NULL
);
6976 sp
= stzalloc(sizeof(*sp
));
6978 *arglist
->lastp
= sp
;
6979 arglist
->lastp
= &sp
->next
;
6985 struct ifsregion
*p
;
6990 struct ifsregion
*ifsp
;
6996 ifsfirst
.next
= NULL
;
7001 * Add a file name to the list.
7004 addfname(const char *name
)
7008 sp
= stzalloc(sizeof(*sp
));
7009 sp
->text
= ststrdup(name
);
7011 exparg
.lastp
= &sp
->next
;
7015 * Do metacharacter (i.e. *, ?, [...]) expansion.
7018 expmeta(char *expdir
, char *enddir
, char *name
)
7033 for (p
= name
; *p
; p
++) {
7034 if (*p
== '*' || *p
== '?')
7036 else if (*p
== '[') {
7043 if (*q
== '/' || *q
== '\0')
7050 } else if (*p
== '\\')
7052 else if (*p
== '/') {
7059 if (metaflag
== 0) { /* we've reached the end of the file name */
7060 if (enddir
!= expdir
)
7068 if (metaflag
== 0 || lstat(expdir
, &statb
) >= 0)
7079 } while (p
< start
);
7081 if (enddir
== expdir
) {
7083 } else if (enddir
== expdir
+ 1 && *expdir
== '/') {
7092 if (enddir
!= expdir
)
7094 if (*endname
== 0) {
7106 while (!pending_int
&& (dp
= readdir(dirp
)) != NULL
) {
7107 if (dp
->d_name
[0] == '.' && !matchdot
)
7109 if (pmatch(start
, dp
->d_name
)) {
7111 strcpy(enddir
, dp
->d_name
);
7114 for (p
= enddir
, cp
= dp
->d_name
; (*p
++ = *cp
++) != '\0';)
7117 expmeta(expdir
, p
, endname
);
7126 static struct strlist
*
7127 msort(struct strlist
*list
, int len
)
7129 struct strlist
*p
, *q
= NULL
;
7130 struct strlist
**lpp
;
7138 for (n
= half
; --n
>= 0;) {
7142 q
->next
= NULL
; /* terminate first half of list */
7143 q
= msort(list
, half
); /* sort first half of list */
7144 p
= msort(p
, len
- half
); /* sort second half */
7147 #if ENABLE_LOCALE_SUPPORT
7148 if (strcoll(p
->text
, q
->text
) < 0)
7150 if (strcmp(p
->text
, q
->text
) < 0)
7174 * Sort the results of file name expansion. It calculates the number of
7175 * strings to sort and then calls msort (short for merge sort) to do the
7178 static struct strlist
*
7179 expsort(struct strlist
*str
)
7185 for (sp
= str
; sp
; sp
= sp
->next
)
7187 return msort(str
, len
);
7191 expandmeta(struct strlist
*str
/*, int flag*/)
7193 static const char metachars
[] ALIGN1
= {
7196 /* TODO - EXP_REDIR */
7200 struct strlist
**savelastp
;
7206 if (!strpbrk(str
->text
, metachars
))
7208 savelastp
= exparg
.lastp
;
7211 p
= preglob(str
->text
, 0, RMESCAPE_ALLOC
| RMESCAPE_HEAP
);
7213 int i
= strlen(str
->text
);
7214 expdir
= ckmalloc(i
< 2048 ? 2048 : i
); /* XXX */
7216 expmeta(expdir
, expdir
, p
);
7221 if (exparg
.lastp
== savelastp
) {
7226 *exparg
.lastp
= str
;
7227 rmescapes(str
->text
, 0);
7228 exparg
.lastp
= &str
->next
;
7230 *exparg
.lastp
= NULL
;
7231 *savelastp
= sp
= expsort(*savelastp
);
7232 while (sp
->next
!= NULL
)
7234 exparg
.lastp
= &sp
->next
;
7241 * Perform variable substitution and command substitution on an argument,
7242 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7243 * perform splitting and file name expansion. When arglist is NULL, perform
7244 * here document expansion.
7247 expandarg(union node
*arg
, struct arglist
*arglist
, int flag
)
7252 argbackq
= arg
->narg
.backquote
;
7253 STARTSTACKSTR(expdest
);
7254 ifsfirst
.next
= NULL
;
7256 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg
->narg
.text
, flag
));
7257 argstr(arg
->narg
.text
, flag
,
7258 /* var_str_list: */ arglist
? arglist
->list
: NULL
);
7259 p
= _STPUTC('\0', expdest
);
7261 if (arglist
== NULL
) {
7262 return; /* here document expanded */
7264 p
= grabstackstr(p
);
7265 TRACE(("expandarg: p:'%s'\n", p
));
7266 exparg
.lastp
= &exparg
.list
;
7270 if (flag
& EXP_FULL
) {
7271 ifsbreakup(p
, &exparg
);
7272 *exparg
.lastp
= NULL
;
7273 exparg
.lastp
= &exparg
.list
;
7274 expandmeta(exparg
.list
/*, flag*/);
7276 if (flag
& EXP_REDIR
) { /*XXX - for now, just remove escapes */
7278 TRACE(("expandarg: rmescapes:'%s'\n", p
));
7280 sp
= stzalloc(sizeof(*sp
));
7283 exparg
.lastp
= &sp
->next
;
7287 *exparg
.lastp
= NULL
;
7289 *arglist
->lastp
= exparg
.list
;
7290 arglist
->lastp
= exparg
.lastp
;
7295 * Expand shell variables and backquotes inside a here document.
7298 expandhere(union node
*arg
, int fd
)
7301 expandarg(arg
, (struct arglist
*)NULL
, 0);
7302 full_write(fd
, stackblock(), expdest
- (char *)stackblock());
7306 * Returns true if the pattern matches the string.
7309 patmatch(char *pattern
, const char *string
)
7311 return pmatch(preglob(pattern
, 0, 0), string
);
7315 * See if a pattern matches in a case statement.
7318 casematch(union node
*pattern
, char *val
)
7320 struct stackmark smark
;
7323 setstackmark(&smark
);
7324 argbackq
= pattern
->narg
.backquote
;
7325 STARTSTACKSTR(expdest
);
7327 argstr(pattern
->narg
.text
, EXP_TILDE
| EXP_CASE
,
7328 /* var_str_list: */ NULL
);
7329 STACKSTRNUL(expdest
);
7330 result
= patmatch(stackblock(), val
);
7331 popstackmark(&smark
);
7336 /* ============ find_command */
7340 int (*builtin
)(int, char **) FAST_FUNC
;
7341 /* unsigned flags; */
7343 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7344 /* "regular" builtins always take precedence over commands,
7345 * regardless of PATH=....%builtin... position */
7346 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7347 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7350 smallint cmdtype
; /* CMDxxx */
7353 /* index >= 0 for commands without path (slashes) */
7354 /* (TODO: what exactly does the value mean? PATH position?) */
7355 /* index == -1 for commands with slashes */
7356 /* index == (-2 - applet_no) for NOFORK applets */
7357 const struct builtincmd
*cmd
;
7358 struct funcnode
*func
;
7361 /* values of cmdtype */
7362 #define CMDUNKNOWN -1 /* no entry in table for command */
7363 #define CMDNORMAL 0 /* command is an executable program */
7364 #define CMDFUNCTION 1 /* command is a shell function */
7365 #define CMDBUILTIN 2 /* command is a shell builtin */
7367 /* action to find_command() */
7368 #define DO_ERR 0x01 /* prints errors */
7369 #define DO_ABS 0x02 /* checks absolute paths */
7370 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7371 #define DO_ALTPATH 0x08 /* using alternate path */
7372 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7374 static void find_command(char *, struct cmdentry
*, int, const char *);
7377 /* ============ Hashing commands */
7380 * When commands are first encountered, they are entered in a hash table.
7381 * This ensures that a full path search will not have to be done for them
7382 * on each invocation.
7384 * We should investigate converting to a linear search, even though that
7385 * would make the command name "hash" a misnomer.
7389 struct tblentry
*next
; /* next entry in hash chain */
7390 union param param
; /* definition of builtin function */
7391 smallint cmdtype
; /* CMDxxx */
7392 char rehash
; /* if set, cd done since entry created */
7393 char cmdname
[1]; /* name of command */
7396 static struct tblentry
**cmdtable
;
7397 #define INIT_G_cmdtable() do { \
7398 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7401 static int builtinloc
= -1; /* index in path of %builtin, or -1 */
7405 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no
,) char *cmd
, char **argv
, char **envp
)
7407 #if ENABLE_FEATURE_SH_STANDALONE
7408 if (applet_no
>= 0) {
7409 if (APPLET_IS_NOEXEC(applet_no
)) {
7413 run_applet_no_and_exit(applet_no
, argv
);
7415 /* re-exec ourselves with the new arguments */
7416 execve(bb_busybox_exec_path
, argv
, envp
);
7417 /* If they called chroot or otherwise made the binary no longer
7418 * executable, fall through */
7425 execve(cmd
, argv
, envp
);
7426 } while (errno
== EINTR
);
7428 execve(cmd
, argv
, envp
);
7430 if (cmd
== (char*) bb_busybox_exec_path
) {
7431 /* We already visited ENOEXEC branch below, don't do it again */
7432 //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
7436 if (errno
== ENOEXEC
) {
7437 /* Run "cmd" as a shell script:
7438 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7439 * "If the execve() function fails with ENOEXEC, the shell
7440 * shall execute a command equivalent to having a shell invoked
7441 * with the command name as its first operand,
7442 * with any remaining arguments passed to the new shell"
7444 * That is, do not use $SHELL, user's shell, or /bin/sh;
7445 * just call ourselves.
7447 * Note that bash reads ~80 chars of the file, and if it sees
7448 * a zero byte before it sees newline, it doesn't try to
7449 * interpret it, but fails with "cannot execute binary file"
7450 * message and exit code 126. For one, this prevents attempts
7451 * to interpret foreign ELF binaries as shell scripts.
7456 for (ap
= argv
; *ap
; ap
++)
7458 new = ckmalloc((ap
- argv
+ 2) * sizeof(new[0]));
7459 new[0] = (char*) "ash";
7462 while ((*ap
++ = *++argv
) != NULL
)
7464 cmd
= (char*) bb_busybox_exec_path
;
7471 * Exec a program. Never returns. If you change this routine, you may
7472 * have to change the find_command routine as well.
7474 static void shellexec(char **, const char *, int) NORETURN
;
7476 shellexec(char **argv
, const char *path
, int idx
)
7482 int applet_no
= -1; /* used only by FEATURE_SH_STANDALONE */
7484 clearredir(/*drop:*/ 1);
7485 envp
= listvars(VEXPORT
, VUNSET
, /*end:*/ NULL
);
7486 if (strchr(argv
[0], '/') != NULL
7487 #if ENABLE_FEATURE_SH_STANDALONE
7488 || (applet_no
= find_applet_by_name(argv
[0])) >= 0
7491 tryexec(IF_FEATURE_SH_STANDALONE(applet_no
,) argv
[0], argv
, envp
);
7492 if (applet_no
>= 0) {
7493 /* We tried execing ourself, but it didn't work.
7494 * Maybe /proc/self/exe doesn't exist?
7503 while ((cmdname
= path_advance(&path
, argv
[0])) != NULL
) {
7504 if (--idx
< 0 && pathopt
== NULL
) {
7505 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname
, argv
, envp
);
7506 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
7513 /* Map to POSIX errors */
7525 exitstatus
= exerrno
;
7526 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7527 argv
[0], e
, suppress_int
));
7528 ash_msg_and_raise(EXEXEC
, "%s: %s", argv
[0], errmsg(e
, "not found"));
7533 printentry(struct tblentry
*cmdp
)
7539 idx
= cmdp
->param
.index
;
7542 name
= path_advance(&path
, cmdp
->cmdname
);
7544 } while (--idx
>= 0);
7545 out1fmt("%s%s\n", name
, (cmdp
->rehash
? "*" : nullstr
));
7549 * Clear out command entries. The argument specifies the first entry in
7550 * PATH which has changed.
7553 clearcmdentry(int firstchange
)
7555 struct tblentry
**tblp
;
7556 struct tblentry
**pp
;
7557 struct tblentry
*cmdp
;
7560 for (tblp
= cmdtable
; tblp
< &cmdtable
[CMDTABLESIZE
]; tblp
++) {
7562 while ((cmdp
= *pp
) != NULL
) {
7563 if ((cmdp
->cmdtype
== CMDNORMAL
&&
7564 cmdp
->param
.index
>= firstchange
)
7565 || (cmdp
->cmdtype
== CMDBUILTIN
&&
7566 builtinloc
>= firstchange
)
7579 * Locate a command in the command hash table. If "add" is nonzero,
7580 * add the command to the table if it is not already present. The
7581 * variable "lastcmdentry" is set to point to the address of the link
7582 * pointing to the entry, so that delete_cmd_entry can delete the
7585 * Interrupts must be off if called with add != 0.
7587 static struct tblentry
**lastcmdentry
;
7589 static struct tblentry
*
7590 cmdlookup(const char *name
, int add
)
7592 unsigned int hashval
;
7594 struct tblentry
*cmdp
;
7595 struct tblentry
**pp
;
7598 hashval
= (unsigned char)*p
<< 4;
7600 hashval
+= (unsigned char)*p
++;
7602 pp
= &cmdtable
[hashval
% CMDTABLESIZE
];
7603 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
7604 if (strcmp(cmdp
->cmdname
, name
) == 0)
7608 if (add
&& cmdp
== NULL
) {
7609 cmdp
= *pp
= ckzalloc(sizeof(struct tblentry
)
7611 /* + 1 - already done because
7612 * tblentry::cmdname is char[1] */);
7613 /*cmdp->next = NULL; - ckzalloc did it */
7614 cmdp
->cmdtype
= CMDUNKNOWN
;
7615 strcpy(cmdp
->cmdname
, name
);
7622 * Delete the command entry returned on the last lookup.
7625 delete_cmd_entry(void)
7627 struct tblentry
*cmdp
;
7630 cmdp
= *lastcmdentry
;
7631 *lastcmdentry
= cmdp
->next
;
7632 if (cmdp
->cmdtype
== CMDFUNCTION
)
7633 freefunc(cmdp
->param
.func
);
7639 * Add a new command entry, replacing any existing command entry for
7640 * the same name - except special builtins.
7643 addcmdentry(char *name
, struct cmdentry
*entry
)
7645 struct tblentry
*cmdp
;
7647 cmdp
= cmdlookup(name
, 1);
7648 if (cmdp
->cmdtype
== CMDFUNCTION
) {
7649 freefunc(cmdp
->param
.func
);
7651 cmdp
->cmdtype
= entry
->cmdtype
;
7652 cmdp
->param
= entry
->u
;
7656 static int FAST_FUNC
7657 hashcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
7659 struct tblentry
**pp
;
7660 struct tblentry
*cmdp
;
7662 struct cmdentry entry
;
7665 if (nextopt("r") != '\0') {
7670 if (*argptr
== NULL
) {
7671 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
]; pp
++) {
7672 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
7673 if (cmdp
->cmdtype
== CMDNORMAL
)
7681 while ((name
= *argptr
) != NULL
) {
7682 cmdp
= cmdlookup(name
, 0);
7684 && (cmdp
->cmdtype
== CMDNORMAL
7685 || (cmdp
->cmdtype
== CMDBUILTIN
&& builtinloc
>= 0))
7689 find_command(name
, &entry
, DO_ERR
, pathval());
7690 if (entry
.cmdtype
== CMDUNKNOWN
)
7698 * Called when a cd is done. Marks all commands so the next time they
7699 * are executed they will be rehashed.
7704 struct tblentry
**pp
;
7705 struct tblentry
*cmdp
;
7707 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
]; pp
++) {
7708 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
7709 if (cmdp
->cmdtype
== CMDNORMAL
7710 || (cmdp
->cmdtype
== CMDBUILTIN
7711 && !IS_BUILTIN_REGULAR(cmdp
->param
.cmd
)
7721 * Fix command hash table when PATH changed.
7722 * Called before PATH is changed. The argument is the new value of PATH;
7723 * pathval() still returns the old value at this point.
7724 * Called with interrupts off.
7726 static void FAST_FUNC
7727 changepath(const char *new)
7735 firstchange
= 9999; /* assume no change */
7741 if ((*old
== '\0' && *new == ':')
7742 || (*old
== ':' && *new == '\0')
7746 old
= new; /* ignore subsequent differences */
7750 if (*new == '%' && idx_bltin
< 0 && prefix(new + 1, "builtin"))
7757 if (builtinloc
< 0 && idx_bltin
>= 0)
7758 builtinloc
= idx_bltin
; /* zap builtins */
7759 if (builtinloc
>= 0 && idx_bltin
< 0)
7761 clearcmdentry(firstchange
);
7762 builtinloc
= idx_bltin
;
7777 #define TENDBQUOTE 12
7794 typedef smallint token_id_t
;
7796 /* first char is indicating which tokens mark the end of a list */
7797 static const char *const tokname_array
[] = {
7811 #define KWDOFFSET 13
7812 /* the following are keywords */
7831 /* Wrapper around strcmp for qsort/bsearch/... */
7833 pstrcmp(const void *a
, const void *b
)
7835 return strcmp((char*) a
, (*(char**) b
) + 1);
7838 static const char *const *
7839 findkwd(const char *s
)
7841 return bsearch(s
, tokname_array
+ KWDOFFSET
,
7842 ARRAY_SIZE(tokname_array
) - KWDOFFSET
,
7843 sizeof(tokname_array
[0]), pstrcmp
);
7847 * Locate and print what a word is...
7850 describe_command(char *command
, int describe_command_verbose
)
7852 struct cmdentry entry
;
7853 struct tblentry
*cmdp
;
7854 #if ENABLE_ASH_ALIAS
7855 const struct alias
*ap
;
7857 const char *path
= pathval();
7859 if (describe_command_verbose
) {
7863 /* First look at the keywords */
7864 if (findkwd(command
)) {
7865 out1str(describe_command_verbose
? " is a shell keyword" : command
);
7869 #if ENABLE_ASH_ALIAS
7870 /* Then look at the aliases */
7871 ap
= lookupalias(command
, 0);
7873 if (!describe_command_verbose
) {
7878 out1fmt(" is an alias for %s", ap
->val
);
7882 /* Then check if it is a tracked alias */
7883 cmdp
= cmdlookup(command
, 0);
7885 entry
.cmdtype
= cmdp
->cmdtype
;
7886 entry
.u
= cmdp
->param
;
7888 /* Finally use brute force */
7889 find_command(command
, &entry
, DO_ABS
, path
);
7892 switch (entry
.cmdtype
) {
7894 int j
= entry
.u
.index
;
7900 p
= path_advance(&path
, command
);
7904 if (describe_command_verbose
) {
7906 (cmdp
? " a tracked alias for" : nullstr
), p
7915 if (describe_command_verbose
) {
7916 out1str(" is a shell function");
7923 if (describe_command_verbose
) {
7924 out1fmt(" is a %sshell builtin",
7925 IS_BUILTIN_SPECIAL(entry
.u
.cmd
) ?
7926 "special " : nullstr
7934 if (describe_command_verbose
) {
7935 out1str(": not found\n");
7944 static int FAST_FUNC
7945 typecmd(int argc UNUSED_PARAM
, char **argv
)
7951 /* type -p ... ? (we don't bother checking for 'p') */
7952 if (argv
[1] && argv
[1][0] == '-') {
7957 err
|= describe_command(argv
[i
++], verbose
);
7962 #if ENABLE_ASH_CMDCMD
7963 static int FAST_FUNC
7964 commandcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
7972 while ((c
= nextopt("pvV")) != '\0')
7974 verify
|= VERIFY_VERBOSE
;
7976 verify
|= VERIFY_BRIEF
;
7981 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7982 if (verify
&& (*argptr
!= NULL
)) {
7983 return describe_command(*argptr
, verify
- VERIFY_BRIEF
);
7991 /* ============ eval.c */
7993 static int funcblocksize
; /* size of structures in function */
7994 static int funcstringsize
; /* size of strings in node */
7995 static void *funcblock
; /* block to allocate function from */
7996 static char *funcstring
; /* block to allocate strings from */
7998 /* flags in argument to evaltree */
7999 #define EV_EXIT 01 /* exit after evaluating tree */
8000 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8001 #define EV_BACKCMD 04 /* command executing within back quotes */
8003 static const uint8_t nodesize
[N_NUMBER
] = {
8004 [NCMD
] = SHELL_ALIGN(sizeof(struct ncmd
)),
8005 [NPIPE
] = SHELL_ALIGN(sizeof(struct npipe
)),
8006 [NREDIR
] = SHELL_ALIGN(sizeof(struct nredir
)),
8007 [NBACKGND
] = SHELL_ALIGN(sizeof(struct nredir
)),
8008 [NSUBSHELL
] = SHELL_ALIGN(sizeof(struct nredir
)),
8009 [NAND
] = SHELL_ALIGN(sizeof(struct nbinary
)),
8010 [NOR
] = SHELL_ALIGN(sizeof(struct nbinary
)),
8011 [NSEMI
] = SHELL_ALIGN(sizeof(struct nbinary
)),
8012 [NIF
] = SHELL_ALIGN(sizeof(struct nif
)),
8013 [NWHILE
] = SHELL_ALIGN(sizeof(struct nbinary
)),
8014 [NUNTIL
] = SHELL_ALIGN(sizeof(struct nbinary
)),
8015 [NFOR
] = SHELL_ALIGN(sizeof(struct nfor
)),
8016 [NCASE
] = SHELL_ALIGN(sizeof(struct ncase
)),
8017 [NCLIST
] = SHELL_ALIGN(sizeof(struct nclist
)),
8018 [NDEFUN
] = SHELL_ALIGN(sizeof(struct narg
)),
8019 [NARG
] = SHELL_ALIGN(sizeof(struct narg
)),
8020 [NTO
] = SHELL_ALIGN(sizeof(struct nfile
)),
8021 #if ENABLE_ASH_BASH_COMPAT
8022 [NTO2
] = SHELL_ALIGN(sizeof(struct nfile
)),
8024 [NCLOBBER
] = SHELL_ALIGN(sizeof(struct nfile
)),
8025 [NFROM
] = SHELL_ALIGN(sizeof(struct nfile
)),
8026 [NFROMTO
] = SHELL_ALIGN(sizeof(struct nfile
)),
8027 [NAPPEND
] = SHELL_ALIGN(sizeof(struct nfile
)),
8028 [NTOFD
] = SHELL_ALIGN(sizeof(struct ndup
)),
8029 [NFROMFD
] = SHELL_ALIGN(sizeof(struct ndup
)),
8030 [NHERE
] = SHELL_ALIGN(sizeof(struct nhere
)),
8031 [NXHERE
] = SHELL_ALIGN(sizeof(struct nhere
)),
8032 [NNOT
] = SHELL_ALIGN(sizeof(struct nnot
)),
8035 static void calcsize(union node
*n
);
8038 sizenodelist(struct nodelist
*lp
)
8041 funcblocksize
+= SHELL_ALIGN(sizeof(struct nodelist
));
8048 calcsize(union node
*n
)
8052 funcblocksize
+= nodesize
[n
->type
];
8055 calcsize(n
->ncmd
.redirect
);
8056 calcsize(n
->ncmd
.args
);
8057 calcsize(n
->ncmd
.assign
);
8060 sizenodelist(n
->npipe
.cmdlist
);
8065 calcsize(n
->nredir
.redirect
);
8066 calcsize(n
->nredir
.n
);
8073 calcsize(n
->nbinary
.ch2
);
8074 calcsize(n
->nbinary
.ch1
);
8077 calcsize(n
->nif
.elsepart
);
8078 calcsize(n
->nif
.ifpart
);
8079 calcsize(n
->nif
.test
);
8082 funcstringsize
+= strlen(n
->nfor
.var
) + 1;
8083 calcsize(n
->nfor
.body
);
8084 calcsize(n
->nfor
.args
);
8087 calcsize(n
->ncase
.cases
);
8088 calcsize(n
->ncase
.expr
);
8091 calcsize(n
->nclist
.body
);
8092 calcsize(n
->nclist
.pattern
);
8093 calcsize(n
->nclist
.next
);
8097 sizenodelist(n
->narg
.backquote
);
8098 funcstringsize
+= strlen(n
->narg
.text
) + 1;
8099 calcsize(n
->narg
.next
);
8102 #if ENABLE_ASH_BASH_COMPAT
8109 calcsize(n
->nfile
.fname
);
8110 calcsize(n
->nfile
.next
);
8114 calcsize(n
->ndup
.vname
);
8115 calcsize(n
->ndup
.next
);
8119 calcsize(n
->nhere
.doc
);
8120 calcsize(n
->nhere
.next
);
8123 calcsize(n
->nnot
.com
);
8129 nodeckstrdup(char *s
)
8131 char *rtn
= funcstring
;
8133 strcpy(funcstring
, s
);
8134 funcstring
+= strlen(s
) + 1;
8138 static union node
*copynode(union node
*);
8140 static struct nodelist
*
8141 copynodelist(struct nodelist
*lp
)
8143 struct nodelist
*start
;
8144 struct nodelist
**lpp
;
8149 funcblock
= (char *) funcblock
+ SHELL_ALIGN(sizeof(struct nodelist
));
8150 (*lpp
)->n
= copynode(lp
->n
);
8152 lpp
= &(*lpp
)->next
;
8159 copynode(union node
*n
)
8166 funcblock
= (char *) funcblock
+ nodesize
[n
->type
];
8170 new->ncmd
.redirect
= copynode(n
->ncmd
.redirect
);
8171 new->ncmd
.args
= copynode(n
->ncmd
.args
);
8172 new->ncmd
.assign
= copynode(n
->ncmd
.assign
);
8175 new->npipe
.cmdlist
= copynodelist(n
->npipe
.cmdlist
);
8176 new->npipe
.pipe_backgnd
= n
->npipe
.pipe_backgnd
;
8181 new->nredir
.redirect
= copynode(n
->nredir
.redirect
);
8182 new->nredir
.n
= copynode(n
->nredir
.n
);
8189 new->nbinary
.ch2
= copynode(n
->nbinary
.ch2
);
8190 new->nbinary
.ch1
= copynode(n
->nbinary
.ch1
);
8193 new->nif
.elsepart
= copynode(n
->nif
.elsepart
);
8194 new->nif
.ifpart
= copynode(n
->nif
.ifpart
);
8195 new->nif
.test
= copynode(n
->nif
.test
);
8198 new->nfor
.var
= nodeckstrdup(n
->nfor
.var
);
8199 new->nfor
.body
= copynode(n
->nfor
.body
);
8200 new->nfor
.args
= copynode(n
->nfor
.args
);
8203 new->ncase
.cases
= copynode(n
->ncase
.cases
);
8204 new->ncase
.expr
= copynode(n
->ncase
.expr
);
8207 new->nclist
.body
= copynode(n
->nclist
.body
);
8208 new->nclist
.pattern
= copynode(n
->nclist
.pattern
);
8209 new->nclist
.next
= copynode(n
->nclist
.next
);
8213 new->narg
.backquote
= copynodelist(n
->narg
.backquote
);
8214 new->narg
.text
= nodeckstrdup(n
->narg
.text
);
8215 new->narg
.next
= copynode(n
->narg
.next
);
8218 #if ENABLE_ASH_BASH_COMPAT
8225 new->nfile
.fname
= copynode(n
->nfile
.fname
);
8226 new->nfile
.fd
= n
->nfile
.fd
;
8227 new->nfile
.next
= copynode(n
->nfile
.next
);
8231 new->ndup
.vname
= copynode(n
->ndup
.vname
);
8232 new->ndup
.dupfd
= n
->ndup
.dupfd
;
8233 new->ndup
.fd
= n
->ndup
.fd
;
8234 new->ndup
.next
= copynode(n
->ndup
.next
);
8238 new->nhere
.doc
= copynode(n
->nhere
.doc
);
8239 new->nhere
.fd
= n
->nhere
.fd
;
8240 new->nhere
.next
= copynode(n
->nhere
.next
);
8243 new->nnot
.com
= copynode(n
->nnot
.com
);
8246 new->type
= n
->type
;
8251 * Make a copy of a parse tree.
8253 static struct funcnode
*
8254 copyfunc(union node
*n
)
8259 funcblocksize
= offsetof(struct funcnode
, n
);
8262 blocksize
= funcblocksize
;
8263 f
= ckmalloc(blocksize
+ funcstringsize
);
8264 funcblock
= (char *) f
+ offsetof(struct funcnode
, n
);
8265 funcstring
= (char *) f
+ blocksize
;
8272 * Define a shell function.
8275 defun(char *name
, union node
*func
)
8277 struct cmdentry entry
;
8280 entry
.cmdtype
= CMDFUNCTION
;
8281 entry
.u
.func
= copyfunc(func
);
8282 addcmdentry(name
, &entry
);
8286 /* Reasons for skipping commands (see comment on breakcmd routine) */
8287 #define SKIPBREAK (1 << 0)
8288 #define SKIPCONT (1 << 1)
8289 #define SKIPFUNC (1 << 2)
8290 #define SKIPFILE (1 << 3)
8291 #define SKIPEVAL (1 << 4)
8292 static smallint evalskip
; /* set to SKIPxxx if we are skipping commands */
8293 static int skipcount
; /* number of levels to skip */
8294 static int funcnest
; /* depth of function calls */
8295 static int loopnest
; /* current loop nesting level */
8297 /* Forward decl way out to parsing code - dotrap needs it */
8298 static int evalstring(char *s
, int mask
);
8300 /* Called to execute a trap.
8301 * Single callsite - at the end of evaltree().
8302 * If we return non-zero, evaltree raises EXEXIT exception.
8304 * Perhaps we should avoid entering new trap handlers
8305 * while we are executing a trap handler. [is it a TODO?]
8314 savestatus
= exitstatus
;
8318 TRACE(("dotrap entered\n"));
8319 for (sig
= 1, g
= gotsig
; sig
< NSIG
; sig
++, g
++) {
8326 /* non-trapped SIGINT is handled separately by raise_interrupt,
8327 * don't upset it by resetting gotsig[SIGINT-1] */
8328 if (sig
== SIGINT
&& !t
)
8331 TRACE(("sig %d is active, will run handler '%s'\n", sig
, t
));
8335 want_exexit
= evalstring(t
, SKIPEVAL
);
8336 exitstatus
= savestatus
;
8338 TRACE(("dotrap returns %d\n", want_exexit
));
8343 TRACE(("dotrap returns 0\n"));
8347 /* forward declarations - evaluation is fairly recursive business... */
8348 static void evalloop(union node
*, int);
8349 static void evalfor(union node
*, int);
8350 static void evalcase(union node
*, int);
8351 static void evalsubshell(union node
*, int);
8352 static void expredir(union node
*);
8353 static void evalpipe(union node
*, int);
8354 static void evalcommand(union node
*, int);
8355 static int evalbltin(const struct builtincmd
*, int, char **);
8356 static void prehash(union node
*);
8359 * Evaluate a parse tree. The value is left in the global variable
8363 evaltree(union node
*n
, int flags
)
8365 struct jmploc
*volatile savehandler
= exception_handler
;
8366 struct jmploc jmploc
;
8368 void (*evalfn
)(union node
*, int);
8372 SAVE_INT(int_level
);
8375 TRACE(("evaltree(NULL) called\n"));
8378 TRACE(("evaltree(%p: %d, %d) called\n", n
, n
->type
, flags
));
8380 exception_handler
= &jmploc
;
8382 int err
= setjmp(jmploc
.loc
);
8384 /* if it was a signal, check for trap handlers */
8385 if (exception_type
== EXSIG
) {
8386 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8387 exception_type
, err
));
8390 /* continue on the way out */
8391 TRACE(("exception %d in evaltree, propagating err=%d\n",
8392 exception_type
, err
));
8393 exception_handler
= savehandler
;
8394 longjmp(exception_handler
->loc
, err
);
8401 out1fmt("Node type = %d\n", n
->type
);
8406 evaltree(n
->nnot
.com
, EV_TESTED
);
8407 status
= !exitstatus
;
8410 expredir(n
->nredir
.redirect
);
8411 status
= redirectsafe(n
->nredir
.redirect
, REDIR_PUSH
);
8413 evaltree(n
->nredir
.n
, flags
& EV_TESTED
);
8414 status
= exitstatus
;
8416 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8419 evalfn
= evalcommand
;
8421 if (eflag
&& !(flags
& EV_TESTED
))
8433 evalfn
= evalsubshell
;
8446 #error NAND + 1 != NOR
8448 #if NOR + 1 != NSEMI
8449 #error NOR + 1 != NSEMI
8451 unsigned is_or
= n
->type
- NAND
;
8454 (flags
| ((is_or
>> 1) - 1)) & EV_TESTED
8456 if (!exitstatus
== is_or
)
8469 evaltree(n
->nif
.test
, EV_TESTED
);
8472 if (exitstatus
== 0) {
8476 if (n
->nif
.elsepart
) {
8477 n
= n
->nif
.elsepart
;
8482 defun(n
->narg
.text
, n
->narg
.next
);
8486 exitstatus
= status
;
8491 exception_handler
= savehandler
;
8494 /* Order of checks below is important:
8495 * signal handlers trigger before exit caused by "set -e".
8497 if (pending_sig
&& dotrap())
8499 if (checkexit
& exitstatus
)
8500 evalskip
|= SKIPEVAL
;
8502 if (flags
& EV_EXIT
) {
8504 raise_exception(EXEXIT
);
8507 RESTORE_INT(int_level
);
8508 TRACE(("leaving evaltree (no interrupts)\n"));
8511 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8514 void evaltreenr(union node
*, int) __attribute__ ((alias("evaltree"),__noreturn__
));
8517 evalloop(union node
*n
, int flags
)
8527 evaltree(n
->nbinary
.ch1
, EV_TESTED
);
8530 if (evalskip
== SKIPCONT
&& --skipcount
<= 0) {
8534 if (evalskip
== SKIPBREAK
&& --skipcount
<= 0)
8539 if (n
->type
!= NWHILE
)
8543 evaltree(n
->nbinary
.ch2
, flags
);
8544 status
= exitstatus
;
8549 exitstatus
= status
;
8553 evalfor(union node
*n
, int flags
)
8555 struct arglist arglist
;
8558 struct stackmark smark
;
8560 setstackmark(&smark
);
8561 arglist
.list
= NULL
;
8562 arglist
.lastp
= &arglist
.list
;
8563 for (argp
= n
->nfor
.args
; argp
; argp
= argp
->narg
.next
) {
8564 expandarg(argp
, &arglist
, EXP_FULL
| EXP_TILDE
| EXP_RECORD
);
8569 *arglist
.lastp
= NULL
;
8574 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
8575 setvar(n
->nfor
.var
, sp
->text
, 0);
8576 evaltree(n
->nfor
.body
, flags
);
8578 if (evalskip
== SKIPCONT
&& --skipcount
<= 0) {
8582 if (evalskip
== SKIPBREAK
&& --skipcount
<= 0)
8589 popstackmark(&smark
);
8593 evalcase(union node
*n
, int flags
)
8597 struct arglist arglist
;
8598 struct stackmark smark
;
8600 setstackmark(&smark
);
8601 arglist
.list
= NULL
;
8602 arglist
.lastp
= &arglist
.list
;
8603 expandarg(n
->ncase
.expr
, &arglist
, EXP_TILDE
);
8605 for (cp
= n
->ncase
.cases
; cp
&& evalskip
== 0; cp
= cp
->nclist
.next
) {
8606 for (patp
= cp
->nclist
.pattern
; patp
; patp
= patp
->narg
.next
) {
8607 if (casematch(patp
, arglist
.list
->text
)) {
8608 if (evalskip
== 0) {
8609 evaltree(cp
->nclist
.body
, flags
);
8616 popstackmark(&smark
);
8620 * Kick off a subshell to evaluate a tree.
8623 evalsubshell(union node
*n
, int flags
)
8626 int backgnd
= (n
->type
== NBACKGND
);
8629 expredir(n
->nredir
.redirect
);
8630 if (!backgnd
&& (flags
& EV_EXIT
) && !may_have_traps
)
8633 jp
= makejob(/*n,*/ 1);
8634 if (forkshell(jp
, n
, backgnd
) == 0) {
8639 flags
&= ~EV_TESTED
;
8641 redirect(n
->nredir
.redirect
, 0);
8642 evaltreenr(n
->nredir
.n
, flags
);
8647 status
= waitforjob(jp
);
8648 exitstatus
= status
;
8653 * Compute the names of the files in a redirection list.
8655 static void fixredir(union node
*, const char *, int);
8657 expredir(union node
*n
)
8661 for (redir
= n
; redir
; redir
= redir
->nfile
.next
) {
8665 fn
.lastp
= &fn
.list
;
8666 switch (redir
->type
) {
8670 #if ENABLE_ASH_BASH_COMPAT
8675 expandarg(redir
->nfile
.fname
, &fn
, EXP_TILDE
| EXP_REDIR
);
8676 TRACE(("expredir expanded to '%s'\n", fn
.list
->text
));
8677 #if ENABLE_ASH_BASH_COMPAT
8681 // By the design of stack allocator, the loop of this kind:
8682 // while true; do while true; do break; done </dev/null; done
8683 // will look like a memory leak: ash plans to free expfname's
8684 // of "/dev/null" as soon as it finishes running the loop
8685 // (in this case, never).
8686 // This "fix" is wrong:
8687 if (redir
->nfile
.expfname
)
8688 stunalloc(redir
->nfile
.expfname
);
8689 // It results in corrupted state of stacked allocations.
8691 redir
->nfile
.expfname
= fn
.list
->text
;
8694 case NTOFD
: /* >& */
8695 if (redir
->ndup
.vname
) {
8696 expandarg(redir
->ndup
.vname
, &fn
, EXP_FULL
| EXP_TILDE
);
8697 if (fn
.list
== NULL
)
8698 ash_msg_and_raise_error("redir error");
8699 #if ENABLE_ASH_BASH_COMPAT
8700 //FIXME: we used expandarg with different args!
8701 if (!isdigit_str9(fn
.list
->text
)) {
8702 /* >&file, not >&fd */
8703 if (redir
->nfile
.fd
!= 1) /* 123>&file - BAD */
8704 ash_msg_and_raise_error("redir error");
8706 goto store_expfname
;
8709 fixredir(redir
, fn
.list
->text
, 1);
8717 * Evaluate a pipeline. All the processes in the pipeline are children
8718 * of the process creating the pipeline. (This differs from some versions
8719 * of the shell, which make the last process in a pipeline the parent
8723 evalpipe(union node
*n
, int flags
)
8726 struct nodelist
*lp
;
8731 TRACE(("evalpipe(0x%lx) called\n", (long)n
));
8733 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
)
8737 jp
= makejob(/*n,*/ pipelen
);
8739 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
) {
8743 if (pipe(pip
) < 0) {
8745 ash_msg_and_raise_error("pipe call failed");
8748 if (forkshell(jp
, lp
->n
, n
->npipe
.pipe_backgnd
) == 0) {
8761 evaltreenr(lp
->n
, flags
);
8767 /* Don't want to trigger debugging */
8771 if (n
->npipe
.pipe_backgnd
== 0) {
8772 exitstatus
= waitforjob(jp
);
8773 TRACE(("evalpipe: job done exit status %d\n", exitstatus
));
8779 * Controls whether the shell is interactive or not.
8782 setinteractive(int on
)
8784 static smallint is_interactive
;
8786 if (++on
== is_interactive
)
8788 is_interactive
= on
;
8792 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8793 if (is_interactive
> 1) {
8794 /* Looks like they want an interactive shell */
8795 static smallint did_banner
;
8798 /* note: ash and hush share this string */
8799 out1fmt("\n\n%s %s\n"
8800 "Enter 'help' for a list of built-in commands."
8803 "built-in shell (ash)"
8817 setinteractive(iflag
);
8819 #if ENABLE_FEATURE_EDITING_VI
8821 line_input_state
->flags
|= VI_MODE
;
8823 line_input_state
->flags
&= ~VI_MODE
;
8825 viflag
= 0; /* forcibly keep the option off */
8829 static struct localvar
*localvars
;
8832 * Called after a function returns.
8833 * Interrupts must be off.
8838 struct localvar
*lvp
;
8841 while ((lvp
= localvars
) != NULL
) {
8842 localvars
= lvp
->next
;
8844 TRACE(("poplocalvar %s\n", vp
? vp
->var_text
: "-"));
8845 if (vp
== NULL
) { /* $- saved */
8846 memcpy(optlist
, lvp
->text
, sizeof(optlist
));
8847 free((char*)lvp
->text
);
8849 } else if ((lvp
->flags
& (VUNSET
|VSTRFIXED
)) == VUNSET
) {
8850 unsetvar(vp
->var_text
);
8853 vp
->var_func(var_end(lvp
->text
));
8854 if ((vp
->flags
& (VTEXTFIXED
|VSTACK
)) == 0)
8855 free((char*)vp
->var_text
);
8856 vp
->flags
= lvp
->flags
;
8857 vp
->var_text
= lvp
->text
;
8864 evalfun(struct funcnode
*func
, int argc
, char **argv
, int flags
)
8866 volatile struct shparam saveparam
;
8867 struct localvar
*volatile savelocalvars
;
8868 struct jmploc
*volatile savehandler
;
8869 struct jmploc jmploc
;
8872 saveparam
= shellparam
;
8873 savelocalvars
= localvars
;
8874 e
= setjmp(jmploc
.loc
);
8879 savehandler
= exception_handler
;
8880 exception_handler
= &jmploc
;
8882 shellparam
.malloced
= 0;
8886 shellparam
.nparam
= argc
- 1;
8887 shellparam
.p
= argv
+ 1;
8888 #if ENABLE_ASH_GETOPTS
8889 shellparam
.optind
= 1;
8890 shellparam
.optoff
= -1;
8892 evaltree(&func
->n
, flags
& EV_TESTED
);
8898 localvars
= savelocalvars
;
8899 freeparam(&shellparam
);
8900 shellparam
= saveparam
;
8901 exception_handler
= savehandler
;
8903 evalskip
&= ~SKIPFUNC
;
8907 #if ENABLE_ASH_CMDCMD
8909 parse_command_args(char **argv
, const char **path
)
8922 if (c
== '-' && !*cp
) {
8929 *path
= bb_default_path
;
8932 /* run 'typecmd' for other options */
8943 * Make a variable a local variable. When a variable is made local, it's
8944 * value and flags are saved in a localvar structure. The saved values
8945 * will be restored when the shell function returns. We handle the name
8946 * "-" as a special case.
8951 struct localvar
*lvp
;
8956 lvp
= ckzalloc(sizeof(struct localvar
));
8957 if (LONE_DASH(name
)) {
8959 p
= ckmalloc(sizeof(optlist
));
8960 lvp
->text
= memcpy(p
, optlist
, sizeof(optlist
));
8965 vpp
= hashvar(name
);
8966 vp
= *findvar(vpp
, name
);
8967 eq
= strchr(name
, '=');
8970 setvareq(name
, VSTRFIXED
);
8972 setvar(name
, NULL
, VSTRFIXED
);
8973 vp
= *vpp
; /* the new variable */
8974 lvp
->flags
= VUNSET
;
8976 lvp
->text
= vp
->var_text
;
8977 lvp
->flags
= vp
->flags
;
8978 vp
->flags
|= VSTRFIXED
|VTEXTFIXED
;
8984 lvp
->next
= localvars
;
8990 * The "local" command.
8992 static int FAST_FUNC
8993 localcmd(int argc UNUSED_PARAM
, char **argv
)
8998 while ((name
= *argv
++) != NULL
) {
9004 static int FAST_FUNC
9005 falsecmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
9010 static int FAST_FUNC
9011 truecmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
9016 static int FAST_FUNC
9017 execcmd(int argc UNUSED_PARAM
, char **argv
)
9020 iflag
= 0; /* exit on error */
9023 shellexec(argv
+ 1, pathval(), 0);
9029 * The return command.
9031 static int FAST_FUNC
9032 returncmd(int argc UNUSED_PARAM
, char **argv
)
9035 * If called outside a function, do what ksh does;
9036 * skip the rest of the file.
9038 evalskip
= funcnest
? SKIPFUNC
: SKIPFILE
;
9039 return argv
[1] ? number(argv
[1]) : exitstatus
;
9042 /* Forward declarations for builtintab[] */
9043 static int breakcmd(int, char **) FAST_FUNC
;
9044 static int dotcmd(int, char **) FAST_FUNC
;
9045 static int evalcmd(int, char **) FAST_FUNC
;
9046 static int exitcmd(int, char **) FAST_FUNC
;
9047 static int exportcmd(int, char **) FAST_FUNC
;
9048 #if ENABLE_ASH_GETOPTS
9049 static int getoptscmd(int, char **) FAST_FUNC
;
9051 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9052 static int helpcmd(int, char **) FAST_FUNC
;
9054 #if ENABLE_SH_MATH_SUPPORT
9055 static int letcmd(int, char **) FAST_FUNC
;
9057 static int readcmd(int, char **) FAST_FUNC
;
9058 static int setcmd(int, char **) FAST_FUNC
;
9059 static int shiftcmd(int, char **) FAST_FUNC
;
9060 static int timescmd(int, char **) FAST_FUNC
;
9061 static int trapcmd(int, char **) FAST_FUNC
;
9062 static int umaskcmd(int, char **) FAST_FUNC
;
9063 static int unsetcmd(int, char **) FAST_FUNC
;
9064 static int ulimitcmd(int, char **) FAST_FUNC
;
9066 #define BUILTIN_NOSPEC "0"
9067 #define BUILTIN_SPECIAL "1"
9068 #define BUILTIN_REGULAR "2"
9069 #define BUILTIN_SPEC_REG "3"
9070 #define BUILTIN_ASSIGN "4"
9071 #define BUILTIN_SPEC_ASSG "5"
9072 #define BUILTIN_REG_ASSG "6"
9073 #define BUILTIN_SPEC_REG_ASSG "7"
9075 /* Stubs for calling non-FAST_FUNC's */
9076 #if ENABLE_ASH_BUILTIN_ECHO
9077 static int FAST_FUNC
echocmd(int argc
, char **argv
) { return echo_main(argc
, argv
); }
9079 #if ENABLE_ASH_BUILTIN_PRINTF
9080 static int FAST_FUNC
printfcmd(int argc
, char **argv
) { return printf_main(argc
, argv
); }
9082 #if ENABLE_ASH_BUILTIN_TEST
9083 static int FAST_FUNC
testcmd(int argc
, char **argv
) { return test_main(argc
, argv
); }
9086 /* Keep these in proper order since it is searched via bsearch() */
9087 static const struct builtincmd builtintab
[] = {
9088 { BUILTIN_SPEC_REG
"." , dotcmd
},
9089 { BUILTIN_SPEC_REG
":" , truecmd
},
9090 #if ENABLE_ASH_BUILTIN_TEST
9091 { BUILTIN_REGULAR
"[" , testcmd
},
9092 #if ENABLE_ASH_BASH_COMPAT
9093 { BUILTIN_REGULAR
"[[" , testcmd
},
9096 #if ENABLE_ASH_ALIAS
9097 { BUILTIN_REG_ASSG
"alias" , aliascmd
},
9100 { BUILTIN_REGULAR
"bg" , fg_bgcmd
},
9102 { BUILTIN_SPEC_REG
"break" , breakcmd
},
9103 { BUILTIN_REGULAR
"cd" , cdcmd
},
9104 { BUILTIN_NOSPEC
"chdir" , cdcmd
},
9105 #if ENABLE_ASH_CMDCMD
9106 { BUILTIN_REGULAR
"command" , commandcmd
},
9108 { BUILTIN_SPEC_REG
"continue", breakcmd
},
9109 #if ENABLE_ASH_BUILTIN_ECHO
9110 { BUILTIN_REGULAR
"echo" , echocmd
},
9112 { BUILTIN_SPEC_REG
"eval" , evalcmd
},
9113 { BUILTIN_SPEC_REG
"exec" , execcmd
},
9114 { BUILTIN_SPEC_REG
"exit" , exitcmd
},
9115 { BUILTIN_SPEC_REG_ASSG
"export" , exportcmd
},
9116 { BUILTIN_REGULAR
"false" , falsecmd
},
9118 { BUILTIN_REGULAR
"fg" , fg_bgcmd
},
9120 #if ENABLE_ASH_GETOPTS
9121 { BUILTIN_REGULAR
"getopts" , getoptscmd
},
9123 { BUILTIN_NOSPEC
"hash" , hashcmd
},
9124 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9125 { BUILTIN_NOSPEC
"help" , helpcmd
},
9128 { BUILTIN_REGULAR
"jobs" , jobscmd
},
9129 { BUILTIN_REGULAR
"kill" , killcmd
},
9131 #if ENABLE_SH_MATH_SUPPORT
9132 { BUILTIN_NOSPEC
"let" , letcmd
},
9134 { BUILTIN_ASSIGN
"local" , localcmd
},
9135 #if ENABLE_ASH_BUILTIN_PRINTF
9136 { BUILTIN_REGULAR
"printf" , printfcmd
},
9138 { BUILTIN_NOSPEC
"pwd" , pwdcmd
},
9139 { BUILTIN_REGULAR
"read" , readcmd
},
9140 { BUILTIN_SPEC_REG_ASSG
"readonly", exportcmd
},
9141 { BUILTIN_SPEC_REG
"return" , returncmd
},
9142 { BUILTIN_SPEC_REG
"set" , setcmd
},
9143 { BUILTIN_SPEC_REG
"shift" , shiftcmd
},
9144 #if ENABLE_ASH_BASH_COMPAT
9145 { BUILTIN_SPEC_REG
"source" , dotcmd
},
9147 #if ENABLE_ASH_BUILTIN_TEST
9148 { BUILTIN_REGULAR
"test" , testcmd
},
9150 { BUILTIN_SPEC_REG
"times" , timescmd
},
9151 { BUILTIN_SPEC_REG
"trap" , trapcmd
},
9152 { BUILTIN_REGULAR
"true" , truecmd
},
9153 { BUILTIN_NOSPEC
"type" , typecmd
},
9154 { BUILTIN_NOSPEC
"ulimit" , ulimitcmd
},
9155 { BUILTIN_REGULAR
"umask" , umaskcmd
},
9156 #if ENABLE_ASH_ALIAS
9157 { BUILTIN_REGULAR
"unalias" , unaliascmd
},
9159 { BUILTIN_SPEC_REG
"unset" , unsetcmd
},
9160 { BUILTIN_REGULAR
"wait" , waitcmd
},
9163 /* Should match the above table! */
9164 #define COMMANDCMD (builtintab + \
9166 1 * ENABLE_ASH_BUILTIN_TEST + \
9167 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9168 1 * ENABLE_ASH_ALIAS + \
9169 1 * ENABLE_ASH_JOB_CONTROL + \
9171 #define EXECCMD (builtintab + \
9173 1 * ENABLE_ASH_BUILTIN_TEST + \
9174 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9175 1 * ENABLE_ASH_ALIAS + \
9176 1 * ENABLE_ASH_JOB_CONTROL + \
9178 1 * ENABLE_ASH_CMDCMD + \
9180 ENABLE_ASH_BUILTIN_ECHO + \
9184 * Search the table of builtin commands.
9186 static struct builtincmd
*
9187 find_builtin(const char *name
)
9189 struct builtincmd
*bp
;
9192 name
, builtintab
, ARRAY_SIZE(builtintab
), sizeof(builtintab
[0]),
9199 * Execute a simple command.
9202 isassignment(const char *p
)
9204 const char *q
= endofname(p
);
9209 static int FAST_FUNC
9210 bltincmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
9212 /* Preserve exitstatus of a previous possible redirection
9213 * as POSIX mandates */
9214 return back_exitstatus
;
9217 evalcommand(union node
*cmd
, int flags
)
9219 static const struct builtincmd null_bltin
= {
9220 "\0\0", bltincmd
/* why three NULs? */
9222 struct stackmark smark
;
9224 struct arglist arglist
;
9225 struct arglist varlist
;
9228 const struct strlist
*sp
;
9229 struct cmdentry cmdentry
;
9236 struct builtincmd
*bcmd
;
9237 smallint cmd_is_exec
;
9238 smallint pseudovarflag
= 0;
9240 /* First expand the arguments. */
9241 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd
, flags
));
9242 setstackmark(&smark
);
9243 back_exitstatus
= 0;
9245 cmdentry
.cmdtype
= CMDBUILTIN
;
9246 cmdentry
.u
.cmd
= &null_bltin
;
9247 varlist
.lastp
= &varlist
.list
;
9248 *varlist
.lastp
= NULL
;
9249 arglist
.lastp
= &arglist
.list
;
9250 *arglist
.lastp
= NULL
;
9253 if (cmd
->ncmd
.args
) {
9254 bcmd
= find_builtin(cmd
->ncmd
.args
->narg
.text
);
9255 pseudovarflag
= bcmd
&& IS_BUILTIN_ASSIGN(bcmd
);
9258 for (argp
= cmd
->ncmd
.args
; argp
; argp
= argp
->narg
.next
) {
9259 struct strlist
**spp
;
9261 spp
= arglist
.lastp
;
9262 if (pseudovarflag
&& isassignment(argp
->narg
.text
))
9263 expandarg(argp
, &arglist
, EXP_VARTILDE
);
9265 expandarg(argp
, &arglist
, EXP_FULL
| EXP_TILDE
);
9267 for (sp
= *spp
; sp
; sp
= sp
->next
)
9271 argv
= nargv
= stalloc(sizeof(char *) * (argc
+ 1));
9272 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
9273 TRACE(("evalcommand arg: %s\n", sp
->text
));
9274 *nargv
++ = sp
->text
;
9279 if (iflag
&& funcnest
== 0 && argc
> 0)
9280 lastarg
= nargv
[-1];
9283 expredir(cmd
->ncmd
.redirect
);
9284 status
= redirectsafe(cmd
->ncmd
.redirect
, REDIR_PUSH
| REDIR_SAVEFD2
);
9286 path
= vpath
.var_text
;
9287 for (argp
= cmd
->ncmd
.assign
; argp
; argp
= argp
->narg
.next
) {
9288 struct strlist
**spp
;
9291 spp
= varlist
.lastp
;
9292 expandarg(argp
, &varlist
, EXP_VARTILDE
);
9295 * Modify the command lookup path, if a PATH= assignment
9299 if (varcmp(p
, path
) == 0)
9303 /* Print the command if xflag is set. */
9306 const char *p
= " %s" + 1;
9308 fdprintf(preverrout_fd
, p
, expandstr(ps4val()));
9310 for (n
= 0; n
< 2; n
++) {
9312 fdprintf(preverrout_fd
, p
, sp
->text
);
9318 safe_write(preverrout_fd
, "\n", 1);
9324 /* Now locate the command. */
9326 int cmd_flag
= DO_ERR
;
9327 #if ENABLE_ASH_CMDCMD
9328 const char *oldpath
= path
+ 5;
9332 find_command(argv
[0], &cmdentry
, cmd_flag
, path
);
9333 if (cmdentry
.cmdtype
== CMDUNKNOWN
) {
9334 flush_stdout_stderr();
9339 /* implement bltin and command here */
9340 if (cmdentry
.cmdtype
!= CMDBUILTIN
)
9343 spclbltin
= IS_BUILTIN_SPECIAL(cmdentry
.u
.cmd
);
9344 if (cmdentry
.u
.cmd
== EXECCMD
)
9346 #if ENABLE_ASH_CMDCMD
9347 if (cmdentry
.u
.cmd
== COMMANDCMD
) {
9349 nargv
= parse_command_args(argv
, &path
);
9352 argc
-= nargv
- argv
;
9354 cmd_flag
|= DO_NOFUNC
;
9362 /* We have a redirection error. */
9364 raise_exception(EXERROR
);
9366 exitstatus
= status
;
9370 /* Execute the command. */
9371 switch (cmdentry
.cmdtype
) {
9374 #if ENABLE_FEATURE_SH_NOFORK
9375 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9376 * around run_nofork_applet() call.
9377 * (2) Should this check also be done in forkshell()?
9378 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9380 /* find_command() encodes applet_no as (-2 - applet_no) */
9381 int applet_no
= (- cmdentry
.u
.index
- 2);
9382 if (applet_no
>= 0 && APPLET_IS_NOFORK(applet_no
)) {
9383 listsetvar(varlist
.list
, VEXPORT
|VSTACK
);
9384 /* run <applet>_main() */
9385 exitstatus
= run_nofork_applet(applet_no
, argv
);
9389 /* Can we avoid forking off? For example, very last command
9390 * in a script or a subshell does not need forking,
9391 * we can just exec it.
9393 if (!(flags
& EV_EXIT
) || may_have_traps
) {
9394 /* No, forking off a child is necessary */
9396 jp
= makejob(/*cmd,*/ 1);
9397 if (forkshell(jp
, cmd
, FORK_FG
) != 0) {
9399 exitstatus
= waitforjob(jp
);
9401 TRACE(("forked child exited with %d\n", exitstatus
));
9406 /* fall through to exec'ing external program */
9408 listsetvar(varlist
.list
, VEXPORT
|VSTACK
);
9409 shellexec(argv
, path
, cmdentry
.u
.index
);
9413 cmdenviron
= varlist
.list
;
9415 struct strlist
*list
= cmdenviron
;
9417 if (spclbltin
> 0 || argc
== 0) {
9419 if (cmd_is_exec
&& argc
> 1)
9422 listsetvar(list
, i
);
9424 /* Tight loop with builtins only:
9425 * "while kill -0 $child; do true; done"
9426 * will never exit even if $child died, unless we do this
9427 * to reap the zombie and make kill detect that it's gone: */
9428 dowait(DOWAIT_NONBLOCK
, NULL
);
9430 if (evalbltin(cmdentry
.u
.cmd
, argc
, argv
)) {
9432 int i
= exception_type
;
9437 exit_status
= 128 + SIGINT
;
9439 exit_status
= 128 + pending_sig
;
9440 exitstatus
= exit_status
;
9441 if (i
== EXINT
|| spclbltin
> 0) {
9443 longjmp(exception_handler
->loc
, 1);
9450 listsetvar(varlist
.list
, 0);
9451 /* See above for the rationale */
9452 dowait(DOWAIT_NONBLOCK
, NULL
);
9453 if (evalfun(cmdentry
.u
.func
, argc
, argv
, flags
))
9460 popredir(/*drop:*/ cmd_is_exec
, /*restore:*/ cmd_is_exec
);
9462 /* dsl: I think this is intended to be used to support
9463 * '_' in 'vi' command mode during line editing...
9464 * However I implemented that within libedit itself.
9466 setvar("_", lastarg
, 0);
9468 popstackmark(&smark
);
9472 evalbltin(const struct builtincmd
*cmd
, int argc
, char **argv
)
9474 char *volatile savecmdname
;
9475 struct jmploc
*volatile savehandler
;
9476 struct jmploc jmploc
;
9479 savecmdname
= commandname
;
9480 i
= setjmp(jmploc
.loc
);
9483 savehandler
= exception_handler
;
9484 exception_handler
= &jmploc
;
9485 commandname
= argv
[0];
9487 optptr
= NULL
; /* initialize nextopt */
9488 exitstatus
= (*cmd
->builtin
)(argc
, argv
);
9489 flush_stdout_stderr();
9491 exitstatus
|= ferror(stdout
);
9493 commandname
= savecmdname
;
9494 exception_handler
= savehandler
;
9500 goodname(const char *p
)
9502 return endofname(p
)[0] == '\0';
9507 * Search for a command. This is called before we fork so that the
9508 * location of the command will be available in the parent as well as
9509 * the child. The check for "goodname" is an overly conservative
9510 * check that the name will not be subject to expansion.
9513 prehash(union node
*n
)
9515 struct cmdentry entry
;
9517 if (n
->type
== NCMD
&& n
->ncmd
.args
&& goodname(n
->ncmd
.args
->narg
.text
))
9518 find_command(n
->ncmd
.args
->narg
.text
, &entry
, 0, pathval());
9522 /* ============ Builtin commands
9524 * Builtin commands whose functions are closely tied to evaluation
9525 * are implemented here.
9529 * Handle break and continue commands. Break, continue, and return are
9530 * all handled by setting the evalskip flag. The evaluation routines
9531 * above all check this flag, and if it is set they start skipping
9532 * commands rather than executing them. The variable skipcount is
9533 * the number of loops to break/continue, or the number of function
9534 * levels to return. (The latter is always 1.) It should probably
9535 * be an error to break out of more loops than exist, but it isn't
9536 * in the standard shell so we don't make it one here.
9538 static int FAST_FUNC
9539 breakcmd(int argc UNUSED_PARAM
, char **argv
)
9541 int n
= argv
[1] ? number(argv
[1]) : 1;
9544 ash_msg_and_raise_error(msg_illnum
, argv
[1]);
9548 evalskip
= (**argv
== 'c') ? SKIPCONT
: SKIPBREAK
;
9555 /* ============ input.c
9557 * This implements the input routines used by the parser.
9561 INPUT_PUSH_FILE
= 1,
9562 INPUT_NOFILE_OK
= 2,
9565 static smallint checkkwd
;
9566 /* values of checkkwd variable */
9567 #define CHKALIAS 0x1
9572 * Push a string back onto the input at this current parsefile level.
9573 * We handle aliases this way.
9575 #if !ENABLE_ASH_ALIAS
9576 #define pushstring(s, ap) pushstring(s)
9579 pushstring(char *s
, struct alias
*ap
)
9586 if (g_parsefile
->strpush
) {
9587 sp
= ckzalloc(sizeof(*sp
));
9588 sp
->prev
= g_parsefile
->strpush
;
9590 sp
= &(g_parsefile
->basestrpush
);
9592 g_parsefile
->strpush
= sp
;
9593 sp
->prev_string
= g_parsefile
->next_to_pgetc
;
9594 sp
->prev_left_in_line
= g_parsefile
->left_in_line
;
9595 #if ENABLE_ASH_ALIAS
9598 ap
->flag
|= ALIASINUSE
;
9602 g_parsefile
->next_to_pgetc
= s
;
9603 g_parsefile
->left_in_line
= len
;
9610 struct strpush
*sp
= g_parsefile
->strpush
;
9613 #if ENABLE_ASH_ALIAS
9615 if (g_parsefile
->next_to_pgetc
[-1] == ' '
9616 || g_parsefile
->next_to_pgetc
[-1] == '\t'
9618 checkkwd
|= CHKALIAS
;
9620 if (sp
->string
!= sp
->ap
->val
) {
9623 sp
->ap
->flag
&= ~ALIASINUSE
;
9624 if (sp
->ap
->flag
& ALIASDEAD
) {
9625 unalias(sp
->ap
->name
);
9629 g_parsefile
->next_to_pgetc
= sp
->prev_string
;
9630 g_parsefile
->left_in_line
= sp
->prev_left_in_line
;
9631 g_parsefile
->strpush
= sp
->prev
;
9632 if (sp
!= &(g_parsefile
->basestrpush
))
9637 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9638 //it peeks whether it is &>, and then pushes back both chars.
9639 //This function needs to save last *next_to_pgetc to buf[0]
9640 //to make two pungetc() reliable. Currently,
9641 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9646 char *buf
= g_parsefile
->buf
;
9648 g_parsefile
->next_to_pgetc
= buf
;
9649 #if ENABLE_FEATURE_EDITING
9651 if (!iflag
|| g_parsefile
->pf_fd
!= STDIN_FILENO
)
9652 nr
= nonblock_immune_read(g_parsefile
->pf_fd
, buf
, IBUFSIZ
- 1, /*loop_on_EINTR:*/ 1);
9655 # if ENABLE_ASH_IDLE_TIMEOUT
9657 const char *tmout_var
= lookupvar("TMOUT");
9659 timeout
= atoi(tmout_var
) * 1000;
9665 # if ENABLE_FEATURE_TAB_COMPLETION
9666 line_input_state
->path_lookup
= pathval();
9668 /* Unicode support should be activated even if LANG is set
9669 * _during_ shell execution, not only if it was set when
9670 * shell was started. Therefore, re-check LANG every time:
9672 reinit_unicode(lookupvar("LANG"));
9673 nr
= read_line_input(line_input_state
, cmdedit_prompt
, buf
, IBUFSIZ
, timeout
);
9675 /* Ctrl+C pressed */
9686 /* Ctrl+D pressed */
9689 # if ENABLE_ASH_IDLE_TIMEOUT
9690 else if (errno
== EAGAIN
&& timeout
> 0) {
9691 printf("\007timed out waiting for input: auto-logout\n");
9698 nr
= nonblock_immune_read(g_parsefile
->pf_fd
, buf
, IBUFSIZ
- 1, /*loop_on_EINTR:*/ 1);
9701 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9703 if (parsefile
->fd
== 0 && errno
== EWOULDBLOCK
) {
9704 int flags
= fcntl(0, F_GETFL
);
9705 if (flags
>= 0 && (flags
& O_NONBLOCK
)) {
9706 flags
&= ~O_NONBLOCK
;
9707 if (fcntl(0, F_SETFL
, flags
) >= 0) {
9708 out2str("sh: turning off NDELAY mode\n");
9719 * Refill the input buffer and return the next input character:
9721 * 1) If a string was pushed back on the input, pop it;
9722 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9723 * or we are reading from a string so we can't refill the buffer,
9725 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9726 * 4) Process input up to the next newline, deleting nul characters.
9728 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9729 #define pgetc_debug(...) ((void)0)
9736 while (g_parsefile
->strpush
) {
9737 #if ENABLE_ASH_ALIAS
9738 if (g_parsefile
->left_in_line
== -1
9739 && g_parsefile
->strpush
->ap
9740 && g_parsefile
->next_to_pgetc
[-1] != ' '
9741 && g_parsefile
->next_to_pgetc
[-1] != '\t'
9743 pgetc_debug("preadbuffer PEOA");
9748 /* try "pgetc" now: */
9749 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9750 g_parsefile
->left_in_line
,
9751 g_parsefile
->next_to_pgetc
,
9752 g_parsefile
->next_to_pgetc
);
9753 if (--g_parsefile
->left_in_line
>= 0)
9754 return (unsigned char)(*g_parsefile
->next_to_pgetc
++);
9756 /* on both branches above g_parsefile->left_in_line < 0.
9757 * "pgetc" needs refilling.
9760 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9761 * pungetc() may increment it a few times.
9762 * Assuming it won't increment it to less than -90.
9764 if (g_parsefile
->left_in_line
< -90 || g_parsefile
->buf
== NULL
) {
9765 pgetc_debug("preadbuffer PEOF1");
9766 /* even in failure keep left_in_line and next_to_pgetc
9767 * in lock step, for correct multi-layer pungetc.
9768 * left_in_line was decremented before preadbuffer(),
9769 * must inc next_to_pgetc: */
9770 g_parsefile
->next_to_pgetc
++;
9774 more
= g_parsefile
->left_in_buffer
;
9776 flush_stdout_stderr();
9780 /* don't try reading again */
9781 g_parsefile
->left_in_line
= -99;
9782 pgetc_debug("preadbuffer PEOF2");
9783 g_parsefile
->next_to_pgetc
++;
9788 /* Find out where's the end of line.
9789 * Set g_parsefile->left_in_line
9790 * and g_parsefile->left_in_buffer acordingly.
9791 * NUL chars are deleted.
9793 q
= g_parsefile
->next_to_pgetc
;
9801 memmove(q
, q
+ 1, more
);
9805 g_parsefile
->left_in_line
= q
- g_parsefile
->next_to_pgetc
- 1;
9811 g_parsefile
->left_in_line
= q
- g_parsefile
->next_to_pgetc
- 1;
9812 if (g_parsefile
->left_in_line
< 0)
9817 g_parsefile
->left_in_buffer
= more
;
9822 out2str(g_parsefile
->next_to_pgetc
);
9826 pgetc_debug("preadbuffer at %d:%p'%s'",
9827 g_parsefile
->left_in_line
,
9828 g_parsefile
->next_to_pgetc
,
9829 g_parsefile
->next_to_pgetc
);
9830 return (unsigned char)*g_parsefile
->next_to_pgetc
++;
9833 #define pgetc_as_macro() \
9834 (--g_parsefile->left_in_line >= 0 \
9835 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9842 pgetc_debug("pgetc_fast at %d:%p'%s'",
9843 g_parsefile
->left_in_line
,
9844 g_parsefile
->next_to_pgetc
,
9845 g_parsefile
->next_to_pgetc
);
9846 return pgetc_as_macro();
9849 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9850 # define pgetc_fast() pgetc()
9852 # define pgetc_fast() pgetc_as_macro()
9855 #if ENABLE_ASH_ALIAS
9857 pgetc_without_PEOA(void)
9861 pgetc_debug("pgetc_fast at %d:%p'%s'",
9862 g_parsefile
->left_in_line
,
9863 g_parsefile
->next_to_pgetc
,
9864 g_parsefile
->next_to_pgetc
);
9866 } while (c
== PEOA
);
9870 # define pgetc_without_PEOA() pgetc()
9874 * Read a line from the script.
9877 pfgets(char *line
, int len
)
9883 while (--nleft
> 0) {
9884 c
= pgetc_without_PEOA();
9899 * Undo the last call to pgetc. Only one character may be pushed back.
9900 * PEOF may be pushed back.
9905 g_parsefile
->left_in_line
++;
9906 g_parsefile
->next_to_pgetc
--;
9907 pgetc_debug("pushed back to %d:%p'%s'",
9908 g_parsefile
->left_in_line
,
9909 g_parsefile
->next_to_pgetc
,
9910 g_parsefile
->next_to_pgetc
);
9914 * To handle the "." command, a stack of input files is used. Pushfile
9915 * adds a new entry to the stack and popfile restores the previous level.
9920 struct parsefile
*pf
;
9922 pf
= ckzalloc(sizeof(*pf
));
9923 pf
->prev
= g_parsefile
;
9925 /*pf->strpush = NULL; - ckzalloc did it */
9926 /*pf->basestrpush.prev = NULL;*/
9933 struct parsefile
*pf
= g_parsefile
;
9941 g_parsefile
= pf
->prev
;
9947 * Return to top level.
9952 while (g_parsefile
!= &basepf
)
9957 * Close the file(s) that the shell is reading commands from. Called
9958 * after a fork is done.
9964 if (g_parsefile
->pf_fd
> 0) {
9965 close(g_parsefile
->pf_fd
);
9966 g_parsefile
->pf_fd
= 0;
9971 * Like setinputfile, but takes an open file descriptor. Call this with
9975 setinputfd(int fd
, int push
)
9977 close_on_exec_on(fd
);
9980 g_parsefile
->buf
= NULL
;
9982 g_parsefile
->pf_fd
= fd
;
9983 if (g_parsefile
->buf
== NULL
)
9984 g_parsefile
->buf
= ckmalloc(IBUFSIZ
);
9985 g_parsefile
->left_in_buffer
= 0;
9986 g_parsefile
->left_in_line
= 0;
9987 g_parsefile
->linno
= 1;
9991 * Set the input to take input from a file. If push is set, push the
9992 * old input onto the stack first.
9995 setinputfile(const char *fname
, int flags
)
10001 fd
= open(fname
, O_RDONLY
);
10003 if (flags
& INPUT_NOFILE_OK
)
10005 ash_msg_and_raise_error("can't open '%s'", fname
);
10008 fd2
= copyfd(fd
, 10);
10011 ash_msg_and_raise_error("out of file descriptors");
10014 setinputfd(fd
, flags
& INPUT_PUSH_FILE
);
10021 * Like setinputfile, but takes input from a string.
10024 setinputstring(char *string
)
10028 g_parsefile
->next_to_pgetc
= string
;
10029 g_parsefile
->left_in_line
= strlen(string
);
10030 g_parsefile
->buf
= NULL
;
10031 g_parsefile
->linno
= 1;
10036 /* ============ mail.c
10038 * Routines to check for mail.
10041 #if ENABLE_ASH_MAIL
10043 #define MAXMBOXES 10
10045 /* times of mailboxes */
10046 static time_t mailtime
[MAXMBOXES
];
10047 /* Set if MAIL or MAILPATH is changed. */
10048 static smallint mail_var_path_changed
;
10051 * Print appropriate message(s) if mail has arrived.
10052 * If mail_var_path_changed is set,
10053 * then the value of MAIL has mail_var_path_changed,
10054 * so we just update the values.
10063 struct stackmark smark
;
10066 setstackmark(&smark
);
10067 mpath
= mpathset() ? mpathval() : mailval();
10068 for (mtp
= mailtime
; mtp
< mailtime
+ MAXMBOXES
; mtp
++) {
10069 p
= path_advance(&mpath
, nullstr
);
10074 for (q
= p
; *q
; q
++)
10080 q
[-1] = '\0'; /* delete trailing '/' */
10081 if (stat(p
, &statb
) < 0) {
10085 if (!mail_var_path_changed
&& statb
.st_mtime
!= *mtp
) {
10088 pathopt
? pathopt
: "you have mail"
10091 *mtp
= statb
.st_mtime
;
10093 mail_var_path_changed
= 0;
10094 popstackmark(&smark
);
10097 static void FAST_FUNC
10098 changemail(const char *val UNUSED_PARAM
)
10100 mail_var_path_changed
= 1;
10103 #endif /* ASH_MAIL */
10106 /* ============ ??? */
10109 * Set the shell parameters.
10112 setparam(char **argv
)
10118 for (nparam
= 0; argv
[nparam
]; nparam
++)
10120 ap
= newparam
= ckmalloc((nparam
+ 1) * sizeof(*ap
));
10122 *ap
++ = ckstrdup(*argv
++);
10125 freeparam(&shellparam
);
10126 shellparam
.malloced
= 1;
10127 shellparam
.nparam
= nparam
;
10128 shellparam
.p
= newparam
;
10129 #if ENABLE_ASH_GETOPTS
10130 shellparam
.optind
= 1;
10131 shellparam
.optoff
= -1;
10136 * Process shell options. The global variable argptr contains a pointer
10137 * to the argument list; we advance it past the options.
10139 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10140 * For a non-interactive shell, an error condition encountered
10141 * by a special built-in ... shall cause the shell to write a diagnostic message
10142 * to standard error and exit as shown in the following table:
10143 * Error Special Built-In
10145 * Utility syntax error (option or operand error) Shall exit
10147 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10148 * we see that bash does not do that (set "finishes" with error code 1 instead,
10149 * and shell continues), and people rely on this behavior!
10151 * set -o barfoo 2>/dev/null
10154 * Oh well. Let's mimic that.
10157 plus_minus_o(char *name
, int val
)
10162 for (i
= 0; i
< NOPTS
; i
++) {
10163 if (strcmp(name
, optnames(i
)) == 0) {
10168 ash_msg("illegal option %co %s", val
? '-' : '+', name
);
10171 for (i
= 0; i
< NOPTS
; i
++) {
10173 out1fmt("%-16s%s\n", optnames(i
), optlist
[i
] ? "on" : "off");
10175 out1fmt("set %co %s\n", optlist
[i
] ? '-' : '+', optnames(i
));
10181 setoption(int flag
, int val
)
10185 for (i
= 0; i
< NOPTS
; i
++) {
10186 if (optletters(i
) == flag
) {
10191 ash_msg_and_raise_error("illegal option %c%c", val
? '-' : '+', flag
);
10195 options(int cmdline
)
10203 while ((p
= *argptr
) != NULL
) {
10205 if (c
!= '-' && c
!= '+')
10208 val
= 0; /* val = 0 if c == '+' */
10211 if (p
[0] == '\0' || LONE_DASH(p
)) {
10213 /* "-" means turn off -x and -v */
10216 /* "--" means reset params */
10217 else if (*argptr
== NULL
)
10220 break; /* "-" or "--" terminates options */
10223 /* first char was + or - */
10224 while ((c
= *p
++) != '\0') {
10225 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10226 if (c
== 'c' && cmdline
) {
10227 minusc
= p
; /* command is after shell args */
10228 } else if (c
== 'o') {
10229 if (plus_minus_o(*argptr
, val
)) {
10230 /* it already printed err message */
10231 return 1; /* error */
10235 } else if (cmdline
&& (c
== 'l')) { /* -l or +l == --login */
10237 /* bash does not accept +-login, we also won't */
10238 } else if (cmdline
&& val
&& (c
== '-')) { /* long options */
10239 if (strcmp(p
, "login") == 0)
10251 * The shift builtin command.
10253 static int FAST_FUNC
10254 shiftcmd(int argc UNUSED_PARAM
, char **argv
)
10261 n
= number(argv
[1]);
10262 if (n
> shellparam
.nparam
)
10263 n
= 0; /* bash compat, was = shellparam.nparam; */
10265 shellparam
.nparam
-= n
;
10266 for (ap1
= shellparam
.p
; --n
>= 0; ap1
++) {
10267 if (shellparam
.malloced
)
10270 ap2
= shellparam
.p
;
10271 while ((*ap2
++ = *ap1
++) != NULL
)
10273 #if ENABLE_ASH_GETOPTS
10274 shellparam
.optind
= 1;
10275 shellparam
.optoff
= -1;
10282 * POSIX requires that 'set' (but not export or readonly) output the
10283 * variables in lexicographic order - by the locale's collating order (sigh).
10284 * Maybe we could keep them in an ordered balanced binary tree
10285 * instead of hashed lists.
10286 * For now just roll 'em through qsort for printing...
10289 showvars(const char *sep_prefix
, int on
, int off
)
10292 char **ep
, **epend
;
10294 ep
= listvars(on
, off
, &epend
);
10295 qsort(ep
, epend
- ep
, sizeof(char *), vpcmp
);
10297 sep
= *sep_prefix
? " " : sep_prefix
;
10299 for (; ep
< epend
; ep
++) {
10303 p
= strchrnul(*ep
, '=');
10306 q
= single_quote(++p
);
10307 out1fmt("%s%s%.*s%s\n", sep_prefix
, sep
, (int)(p
- *ep
), *ep
, q
);
10313 * The set command builtin.
10315 static int FAST_FUNC
10316 setcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
10321 return showvars(nullstr
, 0, VUNSET
);
10324 retval
= options(/*cmdline:*/ 0);
10325 if (retval
== 0) { /* if no parse error... */
10327 if (*argptr
!= NULL
) {
10335 #if ENABLE_ASH_RANDOM_SUPPORT
10336 static void FAST_FUNC
10337 change_random(const char *value
)
10341 if (value
== NULL
) {
10342 /* "get", generate */
10343 t
= next_random(&random_gen
);
10344 /* set without recursion */
10345 setvar(vrandom
.var_text
, utoa(t
), VNOFUNC
);
10346 vrandom
.flags
&= ~VNOFUNC
;
10349 t
= strtoul(value
, NULL
, 10);
10350 INIT_RANDOM_T(&random_gen
, (t
? t
: 1), t
);
10355 #if ENABLE_ASH_GETOPTS
10357 getopts(char *optstr
, char *optvar
, char **optfirst
, int *param_optind
, int *optoff
)
10366 if (*param_optind
< 1)
10368 optnext
= optfirst
+ *param_optind
- 1;
10370 if (*param_optind
<= 1 || *optoff
< 0 || (int)strlen(optnext
[-1]) < *optoff
)
10373 p
= optnext
[-1] + *optoff
;
10374 if (p
== NULL
|| *p
== '\0') {
10375 /* Current word is done, advance */
10377 if (p
== NULL
|| *p
!= '-' || *++p
== '\0') {
10384 if (LONE_DASH(p
)) /* check for "--" */
10389 for (q
= optstr
; *q
!= c
;) {
10391 if (optstr
[0] == ':') {
10394 err
|= setvarsafe("OPTARG", s
, 0);
10396 fprintf(stderr
, "Illegal option -%c\n", c
);
10397 unsetvar("OPTARG");
10407 if (*p
== '\0' && (p
= *optnext
) == NULL
) {
10408 if (optstr
[0] == ':') {
10411 err
|= setvarsafe("OPTARG", s
, 0);
10414 fprintf(stderr
, "No arg for -%c option\n", c
);
10415 unsetvar("OPTARG");
10423 err
|= setvarsafe("OPTARG", p
, 0);
10426 err
|= setvarsafe("OPTARG", nullstr
, 0);
10428 *optoff
= p
? p
- *(optnext
- 1) : -1;
10429 *param_optind
= optnext
- optfirst
+ 1;
10430 fmtstr(s
, sizeof(s
), "%d", *param_optind
);
10431 err
|= setvarsafe("OPTIND", s
, VNOFUNC
);
10434 err
|= setvarsafe(optvar
, s
, 0);
10438 flush_stdout_stderr();
10439 raise_exception(EXERROR
);
10445 * The getopts builtin. Shellparam.optnext points to the next argument
10446 * to be processed. Shellparam.optptr points to the next character to
10447 * be processed in the current argument. If shellparam.optnext is NULL,
10448 * then it's the first time getopts has been called.
10450 static int FAST_FUNC
10451 getoptscmd(int argc
, char **argv
)
10456 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10458 optbase
= shellparam
.p
;
10459 if (shellparam
.optind
> shellparam
.nparam
+ 1) {
10460 shellparam
.optind
= 1;
10461 shellparam
.optoff
= -1;
10464 optbase
= &argv
[3];
10465 if (shellparam
.optind
> argc
- 2) {
10466 shellparam
.optind
= 1;
10467 shellparam
.optoff
= -1;
10471 return getopts(argv
[1], argv
[2], optbase
, &shellparam
.optind
,
10472 &shellparam
.optoff
);
10474 #endif /* ASH_GETOPTS */
10477 /* ============ Shell parser */
10480 struct heredoc
*next
; /* next here document in list */
10481 union node
*here
; /* redirection node */
10482 char *eofmark
; /* string indicating end of input */
10483 smallint striptabs
; /* if set, strip leading tabs */
10486 static smallint tokpushback
; /* last token pushed back */
10487 static smallint parsebackquote
; /* nonzero if we are inside backquotes */
10488 static smallint quoteflag
; /* set if (part of) last token was quoted */
10489 static token_id_t lasttoken
; /* last token read (integer id Txxx) */
10490 static struct heredoc
*heredoclist
; /* list of here documents to read */
10491 static char *wordtext
; /* text of last word returned by readtoken */
10492 static struct nodelist
*backquotelist
;
10493 static union node
*redirnode
;
10494 static struct heredoc
*heredoc
;
10496 static const char *
10497 tokname(char *buf
, int tok
)
10500 return tokname_array
[tok
] + 1;
10501 sprintf(buf
, "\"%s\"", tokname_array
[tok
] + 1);
10505 /* raise_error_unexpected_syntax:
10506 * Called when an unexpected token is read during the parse. The argument
10507 * is the token that is expected, or -1 if more than one type of token can
10508 * occur at this point.
10510 static void raise_error_unexpected_syntax(int) NORETURN
;
10512 raise_error_unexpected_syntax(int token
)
10518 l
= sprintf(msg
, "unexpected %s", tokname(buf
, lasttoken
));
10520 sprintf(msg
+ l
, " (expecting %s)", tokname(buf
, token
));
10521 raise_error_syntax(msg
);
10525 #define EOFMARKLEN 79
10527 /* parsing is heavily cross-recursive, need these forward decls */
10528 static union node
*andor(void);
10529 static union node
*pipeline(void);
10530 static union node
*parse_command(void);
10531 static void parseheredoc(void);
10532 static char peektoken(void);
10533 static int readtoken(void);
10535 static union node
*
10538 union node
*n1
, *n2
, *n3
;
10541 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10542 if (nlflag
== 2 && peektoken())
10548 if (tok
== TBACKGND
) {
10549 if (n2
->type
== NPIPE
) {
10550 n2
->npipe
.pipe_backgnd
= 1;
10552 if (n2
->type
!= NREDIR
) {
10553 n3
= stzalloc(sizeof(struct nredir
));
10555 /*n3->nredir.redirect = NULL; - stzalloc did it */
10558 n2
->type
= NBACKGND
;
10564 n3
= stzalloc(sizeof(struct nbinary
));
10566 n3
->nbinary
.ch1
= n1
;
10567 n3
->nbinary
.ch2
= n2
;
10583 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10591 pungetc(); /* push back EOF on input */
10595 raise_error_unexpected_syntax(-1);
10602 static union node
*
10605 union node
*n1
, *n2
, *n3
;
10613 } else if (t
== TOR
) {
10619 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10621 n3
= stzalloc(sizeof(struct nbinary
));
10623 n3
->nbinary
.ch1
= n1
;
10624 n3
->nbinary
.ch2
= n2
;
10629 static union node
*
10632 union node
*n1
, *n2
, *pipenode
;
10633 struct nodelist
*lp
, *prev
;
10637 TRACE(("pipeline: entered\n"));
10638 if (readtoken() == TNOT
) {
10640 checkkwd
= CHKKWD
| CHKALIAS
;
10643 n1
= parse_command();
10644 if (readtoken() == TPIPE
) {
10645 pipenode
= stzalloc(sizeof(struct npipe
));
10646 pipenode
->type
= NPIPE
;
10647 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10648 lp
= stzalloc(sizeof(struct nodelist
));
10649 pipenode
->npipe
.cmdlist
= lp
;
10653 lp
= stzalloc(sizeof(struct nodelist
));
10654 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10655 lp
->n
= parse_command();
10657 } while (readtoken() == TPIPE
);
10663 n2
= stzalloc(sizeof(struct nnot
));
10671 static union node
*
10676 n
= stzalloc(sizeof(struct narg
));
10678 /*n->narg.next = NULL; - stzalloc did it */
10679 n
->narg
.text
= wordtext
;
10680 n
->narg
.backquote
= backquotelist
;
10685 fixredir(union node
*n
, const char *text
, int err
)
10689 TRACE(("Fix redir %s %d\n", text
, err
));
10691 n
->ndup
.vname
= NULL
;
10693 fd
= bb_strtou(text
, NULL
, 10);
10694 if (!errno
&& fd
>= 0)
10695 n
->ndup
.dupfd
= fd
;
10696 else if (LONE_DASH(text
))
10697 n
->ndup
.dupfd
= -1;
10700 raise_error_syntax("bad fd number");
10701 n
->ndup
.vname
= makename();
10706 * Returns true if the text contains nothing to expand (no dollar signs
10710 noexpand(const char *text
)
10714 while ((c
= *text
++) != '\0') {
10715 if (c
== CTLQUOTEMARK
)
10719 else if (SIT(c
, BASESYNTAX
) == CCTL
)
10728 union node
*n
= redirnode
;
10730 if (readtoken() != TWORD
)
10731 raise_error_unexpected_syntax(-1);
10732 if (n
->type
== NHERE
) {
10733 struct heredoc
*here
= heredoc
;
10737 if (quoteflag
== 0)
10739 TRACE(("Here document %d\n", n
->type
));
10740 if (!noexpand(wordtext
) || (i
= strlen(wordtext
)) == 0 || i
> EOFMARKLEN
)
10741 raise_error_syntax("illegal eof marker for << redirection");
10742 rmescapes(wordtext
, 0);
10743 here
->eofmark
= wordtext
;
10745 if (heredoclist
== NULL
)
10746 heredoclist
= here
;
10748 for (p
= heredoclist
; p
->next
; p
= p
->next
)
10752 } else if (n
->type
== NTOFD
|| n
->type
== NFROMFD
) {
10753 fixredir(n
, wordtext
, 0);
10755 n
->nfile
.fname
= makename();
10759 static union node
*
10762 union node
*args
, **app
;
10763 union node
*n
= NULL
;
10764 union node
*vars
, **vpp
;
10765 union node
**rpp
, *redir
;
10767 #if ENABLE_ASH_BASH_COMPAT
10768 smallint double_brackets_flag
= 0;
10778 savecheckkwd
= CHKALIAS
;
10781 checkkwd
= savecheckkwd
;
10784 #if ENABLE_ASH_BASH_COMPAT
10785 case TAND
: /* "&&" */
10786 case TOR
: /* "||" */
10787 if (!double_brackets_flag
) {
10791 wordtext
= (char *) (t
== TAND
? "-a" : "-o");
10794 n
= stzalloc(sizeof(struct narg
));
10796 /*n->narg.next = NULL; - stzalloc did it */
10797 n
->narg
.text
= wordtext
;
10798 #if ENABLE_ASH_BASH_COMPAT
10799 if (strcmp("[[", wordtext
) == 0)
10800 double_brackets_flag
= 1;
10801 else if (strcmp("]]", wordtext
) == 0)
10802 double_brackets_flag
= 0;
10804 n
->narg
.backquote
= backquotelist
;
10805 if (savecheckkwd
&& isassignment(wordtext
)) {
10807 vpp
= &n
->narg
.next
;
10810 app
= &n
->narg
.next
;
10815 *rpp
= n
= redirnode
;
10816 rpp
= &n
->nfile
.next
;
10817 parsefname(); /* read name of redirection file */
10820 if (args
&& app
== &args
->narg
.next
10823 struct builtincmd
*bcmd
;
10826 /* We have a function */
10827 if (readtoken() != TRP
)
10828 raise_error_unexpected_syntax(TRP
);
10829 name
= n
->narg
.text
;
10830 if (!goodname(name
)
10831 || ((bcmd
= find_builtin(name
)) && IS_BUILTIN_SPECIAL(bcmd
))
10833 raise_error_syntax("bad function name");
10836 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10837 n
->narg
.next
= parse_command();
10850 n
= stzalloc(sizeof(struct ncmd
));
10852 n
->ncmd
.args
= args
;
10853 n
->ncmd
.assign
= vars
;
10854 n
->ncmd
.redirect
= redir
;
10858 static union node
*
10859 parse_command(void)
10861 union node
*n1
, *n2
;
10862 union node
*ap
, **app
;
10863 union node
*cp
, **cpp
;
10864 union node
*redir
, **rpp
;
10871 switch (readtoken()) {
10873 raise_error_unexpected_syntax(-1);
10876 n1
= stzalloc(sizeof(struct nif
));
10878 n1
->nif
.test
= list(0);
10879 if (readtoken() != TTHEN
)
10880 raise_error_unexpected_syntax(TTHEN
);
10881 n1
->nif
.ifpart
= list(0);
10883 while (readtoken() == TELIF
) {
10884 n2
->nif
.elsepart
= stzalloc(sizeof(struct nif
));
10885 n2
= n2
->nif
.elsepart
;
10887 n2
->nif
.test
= list(0);
10888 if (readtoken() != TTHEN
)
10889 raise_error_unexpected_syntax(TTHEN
);
10890 n2
->nif
.ifpart
= list(0);
10892 if (lasttoken
== TELSE
)
10893 n2
->nif
.elsepart
= list(0);
10895 n2
->nif
.elsepart
= NULL
;
10903 n1
= stzalloc(sizeof(struct nbinary
));
10904 n1
->type
= (lasttoken
== TWHILE
) ? NWHILE
: NUNTIL
;
10905 n1
->nbinary
.ch1
= list(0);
10908 TRACE(("expecting DO got '%s' %s\n", tokname_array
[got
] + 1,
10909 got
== TWORD
? wordtext
: ""));
10910 raise_error_unexpected_syntax(TDO
);
10912 n1
->nbinary
.ch2
= list(0);
10917 if (readtoken() != TWORD
|| quoteflag
|| !goodname(wordtext
))
10918 raise_error_syntax("bad for loop variable");
10919 n1
= stzalloc(sizeof(struct nfor
));
10921 n1
->nfor
.var
= wordtext
;
10922 checkkwd
= CHKKWD
| CHKALIAS
;
10923 if (readtoken() == TIN
) {
10925 while (readtoken() == TWORD
) {
10926 n2
= stzalloc(sizeof(struct narg
));
10928 /*n2->narg.next = NULL; - stzalloc did it */
10929 n2
->narg
.text
= wordtext
;
10930 n2
->narg
.backquote
= backquotelist
;
10932 app
= &n2
->narg
.next
;
10935 n1
->nfor
.args
= ap
;
10936 if (lasttoken
!= TNL
&& lasttoken
!= TSEMI
)
10937 raise_error_unexpected_syntax(-1);
10939 n2
= stzalloc(sizeof(struct narg
));
10941 /*n2->narg.next = NULL; - stzalloc did it */
10942 n2
->narg
.text
= (char *)dolatstr
;
10943 /*n2->narg.backquote = NULL;*/
10944 n1
->nfor
.args
= n2
;
10946 * Newline or semicolon here is optional (but note
10947 * that the original Bourne shell only allowed NL).
10949 if (lasttoken
!= TNL
&& lasttoken
!= TSEMI
)
10952 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10953 if (readtoken() != TDO
)
10954 raise_error_unexpected_syntax(TDO
);
10955 n1
->nfor
.body
= list(0);
10959 n1
= stzalloc(sizeof(struct ncase
));
10961 if (readtoken() != TWORD
)
10962 raise_error_unexpected_syntax(TWORD
);
10963 n1
->ncase
.expr
= n2
= stzalloc(sizeof(struct narg
));
10965 /*n2->narg.next = NULL; - stzalloc did it */
10966 n2
->narg
.text
= wordtext
;
10967 n2
->narg
.backquote
= backquotelist
;
10969 checkkwd
= CHKKWD
| CHKALIAS
;
10970 } while (readtoken() == TNL
);
10971 if (lasttoken
!= TIN
)
10972 raise_error_unexpected_syntax(TIN
);
10973 cpp
= &n1
->ncase
.cases
;
10975 checkkwd
= CHKNL
| CHKKWD
;
10977 while (t
!= TESAC
) {
10978 if (lasttoken
== TLP
)
10980 *cpp
= cp
= stzalloc(sizeof(struct nclist
));
10982 app
= &cp
->nclist
.pattern
;
10984 *app
= ap
= stzalloc(sizeof(struct narg
));
10986 /*ap->narg.next = NULL; - stzalloc did it */
10987 ap
->narg
.text
= wordtext
;
10988 ap
->narg
.backquote
= backquotelist
;
10989 if (readtoken() != TPIPE
)
10991 app
= &ap
->narg
.next
;
10994 //ap->narg.next = NULL;
10995 if (lasttoken
!= TRP
)
10996 raise_error_unexpected_syntax(TRP
);
10997 cp
->nclist
.body
= list(2);
10999 cpp
= &cp
->nclist
.next
;
11001 checkkwd
= CHKNL
| CHKKWD
;
11005 raise_error_unexpected_syntax(TENDCASE
);
11012 n1
= stzalloc(sizeof(struct nredir
));
11013 n1
->type
= NSUBSHELL
;
11014 n1
->nredir
.n
= list(0);
11015 /*n1->nredir.redirect = NULL; - stzalloc did it */
11025 return simplecmd();
11028 if (readtoken() != t
)
11029 raise_error_unexpected_syntax(t
);
11032 /* Now check for redirection which may follow command */
11033 checkkwd
= CHKKWD
| CHKALIAS
;
11035 while (readtoken() == TREDIR
) {
11036 *rpp
= n2
= redirnode
;
11037 rpp
= &n2
->nfile
.next
;
11043 if (n1
->type
!= NSUBSHELL
) {
11044 n2
= stzalloc(sizeof(struct nredir
));
11049 n1
->nredir
.redirect
= redir
;
11054 #if ENABLE_ASH_BASH_COMPAT
11055 static int decode_dollar_squote(void)
11057 static const char C_escapes
[] ALIGN1
= "nrbtfav""x\\01234567";
11063 p
= strchr(C_escapes
, c
);
11068 if ((unsigned char)(c
- '0') <= 7) { /* \ooo */
11072 } while ((unsigned char)(c
- '0') <= 7 && --cnt
);
11074 } else if (c
== 'x') { /* \xHH */
11078 } while (isxdigit(c
) && --cnt
);
11080 if (cnt
== 3) { /* \x but next char is "bad" */
11084 } else { /* simple seq like \\ or \t */
11089 c
= bb_process_escape_sequence((void*)&p
);
11090 } else { /* unrecognized "\z": print both chars unless ' or " */
11091 if (c
!= '\'' && c
!= '"') {
11093 c
|= 0x100; /* "please encode \, then me" */
11101 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11102 * is not NULL, read a here document. In the latter case, eofmark is the
11103 * word which marks the end of the document and striptabs is true if
11104 * leading tabs should be stripped from the document. The argument c
11105 * is the first character of the input token or document.
11107 * Because C does not have internal subroutines, I have simulated them
11108 * using goto's to implement the subroutine linkage. The following macros
11109 * will run code that appears at the end of readtoken1.
11111 #define CHECKEND() {goto checkend; checkend_return:;}
11112 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11113 #define PARSESUB() {goto parsesub; parsesub_return:;}
11114 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11115 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11116 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11118 readtoken1(int c
, int syntax
, char *eofmark
, int striptabs
)
11120 /* NB: syntax parameter fits into smallint */
11121 /* c parameter is an unsigned char or PEOF or PEOA */
11124 char line
[EOFMARKLEN
+ 1];
11125 struct nodelist
*bqlist
;
11129 smallint prevsyntax
; /* syntax before arithmetic */
11130 #if ENABLE_ASH_EXPAND_PRMT
11131 smallint pssyntax
; /* we are expanding a prompt string */
11133 int varnest
; /* levels of variables expansion */
11134 int arinest
; /* levels of arithmetic expansion */
11135 int parenlevel
; /* levels of parens in arithmetic */
11136 int dqvarnest
; /* levels of variables expansion within double quotes */
11138 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote
= 0;)
11141 /* Avoid longjmp clobbering */
11147 (void) &parenlevel
;
11150 (void) &prevsyntax
;
11153 startlinno
= g_parsefile
->linno
;
11157 #if ENABLE_ASH_EXPAND_PRMT
11158 pssyntax
= (syntax
== PSSYNTAX
);
11162 dblquote
= (syntax
== DQSYNTAX
);
11168 STARTSTACKSTR(out
);
11170 /* For each line, until end of word */
11171 CHECKEND(); /* set c to PEOF if at end of here document */
11172 for (;;) { /* until end of line or end of word */
11173 CHECKSTRSPACE(4, out
); /* permit 4 calls to USTPUTC */
11174 switch (SIT(c
, syntax
)) {
11175 case CNL
: /* '\n' */
11176 if (syntax
== BASESYNTAX
)
11177 goto endword
; /* exit outer loop */
11179 g_parsefile
->linno
++;
11180 setprompt_if(doprompt
, 2);
11182 goto loop
; /* continue outer loop */
11187 if (eofmark
== NULL
|| dblquote
)
11188 USTPUTC(CTLESC
, out
);
11189 #if ENABLE_ASH_BASH_COMPAT
11190 if (c
== '\\' && bash_dollar_squote
) {
11191 c
= decode_dollar_squote();
11193 USTPUTC('\\', out
);
11194 c
= (unsigned char)c
;
11200 case CBACK
: /* backslash */
11201 c
= pgetc_without_PEOA();
11203 USTPUTC(CTLESC
, out
);
11204 USTPUTC('\\', out
);
11206 } else if (c
== '\n') {
11207 setprompt_if(doprompt
, 2);
11209 #if ENABLE_ASH_EXPAND_PRMT
11210 if (c
== '$' && pssyntax
) {
11211 USTPUTC(CTLESC
, out
);
11212 USTPUTC('\\', out
);
11215 /* Backslash is retained if we are in "str" and next char isn't special */
11220 && (c
!= '"' || eofmark
!= NULL
)
11222 USTPUTC(CTLESC
, out
);
11223 USTPUTC('\\', out
);
11225 if (SIT(c
, SQSYNTAX
) == CCTL
)
11226 USTPUTC(CTLESC
, out
);
11234 if (eofmark
== NULL
) {
11235 USTPUTC(CTLQUOTEMARK
, out
);
11243 IF_ASH_BASH_COMPAT(bash_dollar_squote
= 0;)
11244 if (eofmark
!= NULL
&& arinest
== 0
11249 if (dqvarnest
== 0) {
11250 syntax
= BASESYNTAX
;
11257 case CVAR
: /* '$' */
11258 PARSESUB(); /* parse substitution */
11260 case CENDVAR
: /* '}' */
11263 if (dqvarnest
> 0) {
11270 #if ENABLE_SH_MATH_SUPPORT
11271 case CLP
: /* '(' in arithmetic */
11275 case CRP
: /* ')' in arithmetic */
11276 if (parenlevel
> 0) {
11279 if (pgetc() == ')') {
11280 if (--arinest
== 0) {
11281 syntax
= prevsyntax
;
11282 dblquote
= (syntax
== DQSYNTAX
);
11287 * unbalanced parens
11288 * (don't 2nd guess - no error)
11296 case CBQUOTE
: /* '`' */
11300 goto endword
; /* exit outer loop */
11304 if (varnest
== 0) {
11305 #if ENABLE_ASH_BASH_COMPAT
11307 if (pgetc() == '>')
11308 c
= 0x100 + '>'; /* flag &> */
11312 goto endword
; /* exit outer loop */
11314 IF_ASH_ALIAS(if (c
!= PEOA
))
11321 #if ENABLE_SH_MATH_SUPPORT
11322 if (syntax
== ARISYNTAX
)
11323 raise_error_syntax("missing '))'");
11325 if (syntax
!= BASESYNTAX
&& !parsebackquote
&& eofmark
== NULL
)
11326 raise_error_syntax("unterminated quoted string");
11327 if (varnest
!= 0) {
11328 startlinno
= g_parsefile
->linno
;
11330 raise_error_syntax("missing '}'");
11332 USTPUTC('\0', out
);
11333 len
= out
- (char *)stackblock();
11334 out
= stackblock();
11335 if (eofmark
== NULL
) {
11336 if ((c
== '>' || c
== '<' IF_ASH_BASH_COMPAT( || c
== 0x100 + '>'))
11339 if (isdigit_str9(out
)) {
11340 PARSEREDIR(); /* passed as params: out, c */
11341 lasttoken
= TREDIR
;
11344 /* else: non-number X seen, interpret it
11345 * as "NNNX>file" = "NNNX >file" */
11349 quoteflag
= quotef
;
11350 backquotelist
= bqlist
;
11351 grabstackblock(len
);
11355 /* end of readtoken routine */
11358 * Check to see whether we are at the end of the here document. When this
11359 * is called, c is set to the first character of the next input line. If
11360 * we are at the end of the here document, this routine sets the c to PEOF.
11364 #if ENABLE_ASH_ALIAS
11366 c
= pgetc_without_PEOA();
11369 while (c
== '\t') {
11370 c
= pgetc_without_PEOA();
11373 if (c
== *eofmark
) {
11374 if (pfgets(line
, sizeof(line
)) != NULL
) {
11378 for (q
= eofmark
+ 1; *q
&& *p
== *q
; p
++, q
++)
11380 if (*p
== '\n' && *q
== '\0') {
11382 g_parsefile
->linno
++;
11383 needprompt
= doprompt
;
11385 pushstring(line
, NULL
);
11390 goto checkend_return
;
11394 * Parse a redirection operator. The variable "out" points to a string
11395 * specifying the fd to be redirected. The variable "c" contains the
11396 * first character of the redirection operator.
11399 /* out is already checked to be a valid number or "" */
11400 int fd
= (*out
== '\0' ? -1 : atoi(out
));
11403 np
= stzalloc(sizeof(struct nfile
));
11408 np
->type
= NAPPEND
;
11410 np
->type
= NCLOBBER
;
11413 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11419 #if ENABLE_ASH_BASH_COMPAT
11420 else if (c
== 0x100 + '>') { /* this flags &> redirection */
11422 pgetc(); /* this is '>', no need to check */
11426 else { /* c == '<' */
11427 /*np->nfile.fd = 0; - stzalloc did it */
11431 if (sizeof(struct nfile
) != sizeof(struct nhere
)) {
11432 np
= stzalloc(sizeof(struct nhere
));
11433 /*np->nfile.fd = 0; - stzalloc did it */
11436 heredoc
= stzalloc(sizeof(struct heredoc
));
11437 heredoc
->here
= np
;
11440 heredoc
->striptabs
= 1;
11442 /*heredoc->striptabs = 0; - stzalloc did it */
11448 np
->type
= NFROMFD
;
11452 np
->type
= NFROMTO
;
11464 goto parseredir_return
;
11468 * Parse a substitution. At this point, we have read the dollar sign
11469 * and nothing else.
11472 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11473 * (assuming ascii char codes, as the original implementation did) */
11474 #define is_special(c) \
11475 (((unsigned)(c) - 33 < 32) \
11476 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11478 unsigned char subtype
;
11483 if (c
> 255 /* PEOA or PEOF */
11484 || (c
!= '(' && c
!= '{' && !is_name(c
) && !is_special(c
))
11486 #if ENABLE_ASH_BASH_COMPAT
11488 bash_dollar_squote
= 1;
11493 } else if (c
== '(') {
11494 /* $(command) or $((arith)) */
11495 if (pgetc() == '(') {
11496 #if ENABLE_SH_MATH_SUPPORT
11499 raise_error_syntax("you disabled math support for $((arith)) syntax");
11506 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11507 USTPUTC(CTLVAR
, out
);
11508 typeloc
= out
- (char *)stackblock();
11509 USTPUTC(VSNORMAL
, out
);
11510 subtype
= VSNORMAL
;
11516 c
= '#'; /* ${#} - same as $# */
11518 subtype
= VSLENGTH
; /* ${#VAR} */
11523 if (c
<= 255 /* not PEOA or PEOF */ && is_name(c
)) {
11524 /* $[{[#]]NAME[}] */
11528 } while (c
<= 255 /* not PEOA or PEOF */ && is_in_name(c
));
11529 } else if (isdigit(c
)) {
11530 /* $[{[#]]NUM[}] */
11534 } while (isdigit(c
));
11535 } else if (is_special(c
)) {
11536 /* $[{[#]]<specialchar>[}] */
11541 raise_error_syntax("bad substitution");
11543 if (c
!= '}' && subtype
== VSLENGTH
) {
11544 /* ${#VAR didn't end with } */
11550 if (subtype
== 0) {
11551 /* ${VAR...} but not $VAR or ${#VAR} */
11552 /* c == first char after VAR */
11556 #if ENABLE_ASH_BASH_COMPAT
11557 if (c
== ':' || c
== '$' || isdigit(c
)) {
11558 //TODO: support more general format ${v:EXPR:EXPR},
11559 // where EXPR follows $(()) rules
11560 subtype
= VSSUBSTR
;
11562 break; /* "goto do_pungetc" is bigger (!) */
11568 static const char types
[] ALIGN1
= "}-+?=";
11569 const char *p
= strchr(types
, c
);
11572 subtype
= p
- types
+ VSNORMAL
;
11578 subtype
= (c
== '#' ? VSTRIMLEFT
: VSTRIMRIGHT
);
11585 #if ENABLE_ASH_BASH_COMPAT
11587 /* ${v/[/]pattern/repl} */
11588 //TODO: encode pattern and repl separately.
11589 // Currently ${v/$var_with_slash/repl} is horribly broken
11590 subtype
= VSREPLACE
;
11594 subtype
++; /* VSREPLACEALL */
11602 if (dblquote
|| arinest
)
11604 ((unsigned char *)stackblock())[typeloc
] = subtype
| flags
;
11605 if (subtype
!= VSNORMAL
) {
11607 if (dblquote
|| arinest
) {
11612 goto parsesub_return
;
11616 * Called to parse command substitutions. Newstyle is set if the command
11617 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11618 * list of commands (passed by reference), and savelen is the number of
11619 * characters on the top of the stack which must be preserved.
11622 struct nodelist
**nlpp
;
11625 char *volatile str
;
11626 struct jmploc jmploc
;
11627 struct jmploc
*volatile savehandler
;
11629 smallint saveprompt
= 0;
11632 (void) &saveprompt
;
11634 savepbq
= parsebackquote
;
11635 if (setjmp(jmploc
.loc
)) {
11637 parsebackquote
= 0;
11638 exception_handler
= savehandler
;
11639 longjmp(exception_handler
->loc
, 1);
11643 savelen
= out
- (char *)stackblock();
11645 str
= ckmalloc(savelen
);
11646 memcpy(str
, stackblock(), savelen
);
11648 savehandler
= exception_handler
;
11649 exception_handler
= &jmploc
;
11652 /* We must read until the closing backquote, giving special
11653 * treatment to some slashes, and then push the string and
11654 * reread it as input, interpreting it normally.
11660 STARTSTACKSTR(pout
);
11664 setprompt_if(needprompt
, 2);
11673 g_parsefile
->linno
++;
11674 setprompt_if(doprompt
, 2);
11676 * If eating a newline, avoid putting
11677 * the newline into the new character
11678 * stream (via the STPUTC after the
11683 if (pc
!= '\\' && pc
!= '`' && pc
!= '$'
11684 && (!dblquote
|| pc
!= '"')
11686 STPUTC('\\', pout
);
11688 if (pc
<= 255 /* not PEOA or PEOF */) {
11694 IF_ASH_ALIAS(case PEOA
:)
11695 startlinno
= g_parsefile
->linno
;
11696 raise_error_syntax("EOF in backquote substitution");
11699 g_parsefile
->linno
++;
11700 needprompt
= doprompt
;
11709 STPUTC('\0', pout
);
11710 psavelen
= pout
- (char *)stackblock();
11711 if (psavelen
> 0) {
11712 pstr
= grabstackstr(pout
);
11713 setinputstring(pstr
);
11718 nlpp
= &(*nlpp
)->next
;
11719 *nlpp
= stzalloc(sizeof(**nlpp
));
11720 /* (*nlpp)->next = NULL; - stzalloc did it */
11721 parsebackquote
= oldstyle
;
11724 saveprompt
= doprompt
;
11731 doprompt
= saveprompt
;
11732 else if (readtoken() != TRP
)
11733 raise_error_unexpected_syntax(TRP
);
11738 * Start reading from old file again, ignoring any pushed back
11739 * tokens left from the backquote parsing
11744 while (stackblocksize() <= savelen
)
11746 STARTSTACKSTR(out
);
11748 memcpy(out
, str
, savelen
);
11749 STADJUST(savelen
, out
);
11755 parsebackquote
= savepbq
;
11756 exception_handler
= savehandler
;
11757 if (arinest
|| dblquote
)
11758 USTPUTC(CTLBACKQ
| CTLQUOTE
, out
);
11760 USTPUTC(CTLBACKQ
, out
);
11762 goto parsebackq_oldreturn
;
11763 goto parsebackq_newreturn
;
11766 #if ENABLE_SH_MATH_SUPPORT
11768 * Parse an arithmetic expansion (indicate start of one and set state)
11771 if (++arinest
== 1) {
11772 prevsyntax
= syntax
;
11773 syntax
= ARISYNTAX
;
11774 USTPUTC(CTLARI
, out
);
11781 * we collapse embedded arithmetic expansion to
11782 * parenthesis, which should be equivalent
11786 goto parsearith_return
;
11790 } /* end of readtoken */
11793 * Read the next input token.
11794 * If the token is a word, we set backquotelist to the list of cmds in
11795 * backquotes. We set quoteflag to true if any part of the word was
11797 * If the token is TREDIR, then we set redirnode to a structure containing
11799 * In all cases, the variable startlinno is set to the number of the line
11800 * on which the token starts.
11802 * [Change comment: here documents and internal procedures]
11803 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11804 * word parsing code into a separate routine. In this case, readtoken
11805 * doesn't need to have any internal procedures, but parseword does.
11806 * We could also make parseoperator in essence the main routine, and
11807 * have parseword (readtoken1?) handle both words and redirection.]
11809 #define NEW_xxreadtoken
11810 #ifdef NEW_xxreadtoken
11811 /* singles must be first! */
11812 static const char xxreadtoken_chars
[7] ALIGN1
= {
11813 '\n', '(', ')', /* singles */
11814 '&', '|', ';', /* doubles */
11818 #define xxreadtoken_singles 3
11819 #define xxreadtoken_doubles 3
11821 static const char xxreadtoken_tokens
[] ALIGN1
= {
11822 TNL
, TLP
, TRP
, /* only single occurrence allowed */
11823 TBACKGND
, TPIPE
, TSEMI
, /* if single occurrence */
11824 TEOF
, /* corresponds to trailing nul */
11825 TAND
, TOR
, TENDCASE
/* if double occurrence */
11837 setprompt_if(needprompt
, 2);
11838 startlinno
= g_parsefile
->linno
;
11839 for (;;) { /* until token or start of word found */
11841 if (c
== ' ' || c
== '\t' IF_ASH_ALIAS( || c
== PEOA
))
11845 while ((c
= pgetc()) != '\n' && c
!= PEOF
)
11848 } else if (c
== '\\') {
11849 if (pgetc() != '\n') {
11851 break; /* return readtoken1(...) */
11853 startlinno
= ++g_parsefile
->linno
;
11854 setprompt_if(doprompt
, 2);
11858 p
= xxreadtoken_chars
+ sizeof(xxreadtoken_chars
) - 1;
11861 g_parsefile
->linno
++;
11862 needprompt
= doprompt
;
11865 p
= strchr(xxreadtoken_chars
, c
);
11867 break; /* return readtoken1(...) */
11869 if ((int)(p
- xxreadtoken_chars
) >= xxreadtoken_singles
) {
11871 if (cc
== c
) { /* double occurrence? */
11872 p
+= xxreadtoken_doubles
+ 1;
11875 #if ENABLE_ASH_BASH_COMPAT
11876 if (c
== '&' && cc
== '>') /* &> */
11877 break; /* return readtoken1(...) */
11882 lasttoken
= xxreadtoken_tokens
[p
- xxreadtoken_chars
];
11887 return readtoken1(c
, BASESYNTAX
, (char *) NULL
, 0);
11889 #else /* old xxreadtoken */
11890 #define RETURN(token) return lasttoken = token
11900 setprompt_if(needprompt
, 2);
11901 startlinno
= g_parsefile
->linno
;
11902 for (;;) { /* until token or start of word found */
11905 case ' ': case '\t':
11906 IF_ASH_ALIAS(case PEOA
:)
11909 while ((c
= pgetc()) != '\n' && c
!= PEOF
)
11914 if (pgetc() == '\n') {
11915 startlinno
= ++g_parsefile
->linno
;
11916 setprompt_if(doprompt
, 2);
11922 g_parsefile
->linno
++;
11923 needprompt
= doprompt
;
11928 if (pgetc() == '&')
11933 if (pgetc() == '|')
11938 if (pgetc() == ';')
11951 return readtoken1(c
, BASESYNTAX
, (char *)NULL
, 0);
11954 #endif /* old xxreadtoken */
11961 smallint alreadyseen
= tokpushback
;
11964 #if ENABLE_ASH_ALIAS
11973 if (checkkwd
& CHKNL
) {
11980 if (t
!= TWORD
|| quoteflag
) {
11985 * check for keywords
11987 if (checkkwd
& CHKKWD
) {
11988 const char *const *pp
;
11990 pp
= findkwd(wordtext
);
11992 lasttoken
= t
= pp
- tokname_array
;
11993 TRACE(("keyword '%s' recognized\n", tokname_array
[t
] + 1));
11998 if (checkkwd
& CHKALIAS
) {
11999 #if ENABLE_ASH_ALIAS
12001 ap
= lookupalias(wordtext
, 1);
12004 pushstring(ap
->val
, ap
);
12014 TRACE(("token '%s' %s\n", tokname_array
[t
] + 1, t
== TWORD
? wordtext
: ""));
12016 TRACE(("reread token '%s' %s\n", tokname_array
[t
] + 1, t
== TWORD
? wordtext
: ""));
12028 return tokname_array
[t
][0];
12032 * Read and parse a command. Returns NODE_EOF on end of file.
12033 * (NULL is a valid parse tree indicating a blank line.)
12035 static union node
*
12036 parsecmd(int interact
)
12041 doprompt
= interact
;
12042 setprompt_if(doprompt
, doprompt
);
12054 * Input any here documents.
12059 struct heredoc
*here
;
12062 here
= heredoclist
;
12063 heredoclist
= NULL
;
12066 setprompt_if(needprompt
, 2);
12067 readtoken1(pgetc(), here
->here
->type
== NHERE
? SQSYNTAX
: DQSYNTAX
,
12068 here
->eofmark
, here
->striptabs
);
12069 n
= stzalloc(sizeof(struct narg
));
12070 n
->narg
.type
= NARG
;
12071 /*n->narg.next = NULL; - stzalloc did it */
12072 n
->narg
.text
= wordtext
;
12073 n
->narg
.backquote
= backquotelist
;
12074 here
->here
->nhere
.doc
= n
;
12081 * called by editline -- any expansions to the prompt should be added here.
12083 #if ENABLE_ASH_EXPAND_PRMT
12084 static const char *
12085 expandstr(const char *ps
)
12089 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12090 * and token processing _can_ alter it (delete NULs etc). */
12091 setinputstring((char *)ps
);
12092 readtoken1(pgetc(), PSSYNTAX
, nullstr
, 0);
12095 n
.narg
.type
= NARG
;
12096 n
.narg
.next
= NULL
;
12097 n
.narg
.text
= wordtext
;
12098 n
.narg
.backquote
= backquotelist
;
12100 expandarg(&n
, NULL
, 0);
12101 return stackblock();
12106 * Execute a command or commands contained in a string.
12109 evalstring(char *s
, int mask
)
12112 struct stackmark smark
;
12116 setstackmark(&smark
);
12119 while ((n
= parsecmd(0)) != NODE_EOF
) {
12121 popstackmark(&smark
);
12134 * The eval command.
12136 static int FAST_FUNC
12137 evalcmd(int argc UNUSED_PARAM
, char **argv
)
12146 STARTSTACKSTR(concat
);
12148 concat
= stack_putstr(p
, concat
);
12152 STPUTC(' ', concat
);
12154 STPUTC('\0', concat
);
12155 p
= grabstackstr(concat
);
12157 evalstring(p
, ~SKIPEVAL
);
12163 * Read and execute commands.
12164 * "Top" is nonzero for the top level command loop;
12165 * it turns on prompting if the shell is interactive.
12171 struct stackmark smark
;
12175 TRACE(("cmdloop(%d) called\n", top
));
12179 setstackmark(&smark
);
12182 showjobs(stderr
, SHOW_CHANGED
);
12185 if (iflag
&& top
) {
12189 n
= parsecmd(inter
);
12191 if (DEBUG
> 2 && debug
&& (n
!= NODE_EOF
))
12194 if (n
== NODE_EOF
) {
12195 if (!top
|| numeof
>= 50)
12197 if (!stoppedjobs()) {
12200 out2str("\nUse \"exit\" to leave shell.\n");
12203 } else if (nflag
== 0) {
12204 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12209 popstackmark(&smark
);
12214 return skip
& SKIPEVAL
;
12221 * Take commands from a file. To be compatible we should do a path
12222 * search for the file, which is necessary to find sub-commands.
12225 find_dot_file(char *name
)
12228 const char *path
= pathval();
12231 /* don't try this for absolute or relative paths */
12232 if (strchr(name
, '/'))
12235 /* IIRC standards do not say whether . is to be searched.
12236 * And it is even smaller this way, making it unconditional for now:
12238 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12243 while ((fullname
= path_advance(&path
, name
)) != NULL
) {
12245 if ((stat(fullname
, &statb
) == 0) && S_ISREG(statb
.st_mode
)) {
12247 * Don't bother freeing here, since it will
12248 * be freed by the caller.
12252 if (fullname
!= name
)
12253 stunalloc(fullname
);
12256 /* not found in the PATH */
12257 ash_msg_and_raise_error("%s: not found", name
);
12261 static int FAST_FUNC
12262 dotcmd(int argc
, char **argv
)
12265 struct strlist
*sp
;
12266 volatile struct shparam saveparam
;
12268 for (sp
= cmdenviron
; sp
; sp
= sp
->next
)
12269 setvareq(ckstrdup(sp
->text
), VSTRFIXED
| VTEXTFIXED
);
12272 /* bash says: "bash: .: filename argument required" */
12273 return 2; /* bash compat */
12276 /* "false; . empty_file; echo $?" should print 0, not 1: */
12279 fullname
= find_dot_file(argv
[1]);
12283 if (argc
) { /* argc > 0, argv[0] != NULL */
12284 saveparam
= shellparam
;
12285 shellparam
.malloced
= 0;
12286 shellparam
.nparam
= argc
;
12287 shellparam
.p
= argv
;
12290 setinputfile(fullname
, INPUT_PUSH_FILE
);
12291 commandname
= fullname
;
12296 freeparam(&shellparam
);
12297 shellparam
= saveparam
;
12303 static int FAST_FUNC
12304 exitcmd(int argc UNUSED_PARAM
, char **argv
)
12309 exitstatus
= number(argv
[1]);
12310 raise_exception(EXEXIT
);
12315 * Read a file containing shell functions.
12318 readcmdfile(char *name
)
12320 setinputfile(name
, INPUT_PUSH_FILE
);
12326 /* ============ find_command inplementation */
12329 * Resolve a command name. If you change this routine, you may have to
12330 * change the shellexec routine as well.
12333 find_command(char *name
, struct cmdentry
*entry
, int act
, const char *path
)
12335 struct tblentry
*cmdp
;
12342 struct builtincmd
*bcmd
;
12344 /* If name contains a slash, don't use PATH or hash table */
12345 if (strchr(name
, '/') != NULL
) {
12346 entry
->u
.index
= -1;
12347 if (act
& DO_ABS
) {
12348 while (stat(name
, &statb
) < 0) {
12350 if (errno
== EINTR
)
12353 entry
->cmdtype
= CMDUNKNOWN
;
12357 entry
->cmdtype
= CMDNORMAL
;
12361 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12363 updatetbl
= (path
== pathval());
12366 if (strstr(path
, "%builtin") != NULL
)
12367 act
|= DO_ALTBLTIN
;
12370 /* If name is in the table, check answer will be ok */
12371 cmdp
= cmdlookup(name
, 0);
12372 if (cmdp
!= NULL
) {
12375 switch (cmdp
->cmdtype
) {
12393 } else if (cmdp
->rehash
== 0)
12394 /* if not invalidated by cd, we're done */
12398 /* If %builtin not in path, check for builtin next */
12399 bcmd
= find_builtin(name
);
12401 if (IS_BUILTIN_REGULAR(bcmd
))
12402 goto builtin_success
;
12403 if (act
& DO_ALTPATH
) {
12404 if (!(act
& DO_ALTBLTIN
))
12405 goto builtin_success
;
12406 } else if (builtinloc
<= 0) {
12407 goto builtin_success
;
12411 #if ENABLE_FEATURE_SH_STANDALONE
12413 int applet_no
= find_applet_by_name(name
);
12414 if (applet_no
>= 0) {
12415 entry
->cmdtype
= CMDNORMAL
;
12416 entry
->u
.index
= -2 - applet_no
;
12422 /* We have to search path. */
12423 prev
= -1; /* where to start */
12424 if (cmdp
&& cmdp
->rehash
) { /* doing a rehash */
12425 if (cmdp
->cmdtype
== CMDBUILTIN
)
12428 prev
= cmdp
->param
.index
;
12434 while ((fullname
= path_advance(&path
, name
)) != NULL
) {
12435 stunalloc(fullname
);
12436 /* NB: code below will still use fullname
12437 * despite it being "unallocated" */
12440 if (prefix(pathopt
, "builtin")) {
12442 goto builtin_success
;
12445 if ((act
& DO_NOFUNC
)
12446 || !prefix(pathopt
, "func")
12447 ) { /* ignore unimplemented options */
12451 /* if rehash, don't redo absolute path names */
12452 if (fullname
[0] == '/' && idx
<= prev
) {
12455 TRACE(("searchexec \"%s\": no change\n", name
));
12458 while (stat(fullname
, &statb
) < 0) {
12460 if (errno
== EINTR
)
12463 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
12467 e
= EACCES
; /* if we fail, this will be the error */
12468 if (!S_ISREG(statb
.st_mode
))
12470 if (pathopt
) { /* this is a %func directory */
12471 stalloc(strlen(fullname
) + 1);
12472 /* NB: stalloc will return space pointed by fullname
12473 * (because we don't have any intervening allocations
12474 * between stunalloc above and this stalloc) */
12475 readcmdfile(fullname
);
12476 cmdp
= cmdlookup(name
, 0);
12477 if (cmdp
== NULL
|| cmdp
->cmdtype
!= CMDFUNCTION
)
12478 ash_msg_and_raise_error("%s not defined in %s", name
, fullname
);
12479 stunalloc(fullname
);
12482 TRACE(("searchexec \"%s\" returns \"%s\"\n", name
, fullname
));
12484 entry
->cmdtype
= CMDNORMAL
;
12485 entry
->u
.index
= idx
;
12489 cmdp
= cmdlookup(name
, 1);
12490 cmdp
->cmdtype
= CMDNORMAL
;
12491 cmdp
->param
.index
= idx
;
12496 /* We failed. If there was an entry for this command, delete it */
12497 if (cmdp
&& updatetbl
)
12498 delete_cmd_entry();
12500 ash_msg("%s: %s", name
, errmsg(e
, "not found"));
12501 entry
->cmdtype
= CMDUNKNOWN
;
12506 entry
->cmdtype
= CMDBUILTIN
;
12507 entry
->u
.cmd
= bcmd
;
12511 cmdp
= cmdlookup(name
, 1);
12512 cmdp
->cmdtype
= CMDBUILTIN
;
12513 cmdp
->param
.cmd
= bcmd
;
12517 entry
->cmdtype
= cmdp
->cmdtype
;
12518 entry
->u
= cmdp
->param
;
12522 /* ============ trap.c */
12525 * The trap builtin.
12527 static int FAST_FUNC
12528 trapcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12532 int signo
, exitcode
;
12537 for (signo
= 0; signo
< NSIG
; signo
++) {
12538 char *tr
= trap_ptr
[signo
];
12540 /* note: bash adds "SIG", but only if invoked
12541 * as "bash". If called as "sh", or if set -o posix,
12542 * then it prints short signal names.
12543 * We are printing short names: */
12544 out1fmt("trap -- %s %s\n",
12546 get_signame(signo
));
12547 /* trap_ptr != trap only if we are in special-cased `trap` code.
12548 * In this case, we will exit very soon, no need to free(). */
12549 /* if (trap_ptr != trap && tp[0]) */
12554 if (trap_ptr != trap) {
12567 signo
= get_signum(*ap
);
12569 /* Mimic bash message exactly */
12570 ash_msg("%s: invalid signal specification", *ap
);
12576 if (LONE_DASH(action
))
12579 action
= ckstrdup(action
);
12583 may_have_traps
= 1;
12584 trap
[signo
] = action
;
12595 /* ============ Builtins */
12597 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12599 * Lists available builtins
12601 static int FAST_FUNC
12602 helpcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12608 "Built-in commands:\n"
12609 "------------------\n");
12610 for (col
= 0, i
= 0; i
< ARRAY_SIZE(builtintab
); i
++) {
12611 col
+= out1fmt("%c%s", ((col
== 0) ? '\t' : ' '),
12612 builtintab
[i
].name
+ 1);
12618 #if ENABLE_FEATURE_SH_STANDALONE
12620 const char *a
= applet_names
;
12622 col
+= out1fmt("%c%s", ((col
== 0) ? '\t' : ' '), a
);
12627 a
+= strlen(a
) + 1;
12632 return EXIT_SUCCESS
;
12634 #endif /* FEATURE_SH_EXTRA_QUIET */
12637 * The export and readonly commands.
12639 static int FAST_FUNC
12640 exportcmd(int argc UNUSED_PARAM
, char **argv
)
12650 /* "readonly" in bash accepts, but ignores -n.
12651 * We do the same: it saves a conditional in nextopt's param.
12654 while ((opt
= nextopt("np")) != '\0') {
12656 flag_off
= VEXPORT
;
12659 if (argv
[0][0] == 'r') {
12661 flag_off
= 0; /* readonly ignores -n */
12663 flag_off
= ~flag_off
;
12665 /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
12671 p
= strchr(name
, '=');
12675 vp
= *findvar(hashvar(name
), name
);
12677 vp
->flags
= ((vp
->flags
| flag
) & flag_off
);
12681 setvar(name
, p
, (flag
& flag_off
));
12682 } while ((name
= *++aptr
) != NULL
);
12687 /* No arguments. Show the list of exported or readonly vars.
12690 showvars(argv
[0], flag
, 0);
12695 * Delete a function if it exists.
12698 unsetfunc(const char *name
)
12700 struct tblentry
*cmdp
;
12702 cmdp
= cmdlookup(name
, 0);
12703 if (cmdp
!= NULL
&& cmdp
->cmdtype
== CMDFUNCTION
)
12704 delete_cmd_entry();
12708 * The unset builtin command. We unset the function before we unset the
12709 * variable to allow a function to be unset when there is a readonly variable
12710 * with the same name.
12712 static int FAST_FUNC
12713 unsetcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12720 while ((i
= nextopt("vf")) != 0) {
12724 for (ap
= argptr
; *ap
; ap
++) {
12737 static const unsigned char timescmd_str
[] ALIGN1
= {
12738 ' ', offsetof(struct tms
, tms_utime
),
12739 '\n', offsetof(struct tms
, tms_stime
),
12740 ' ', offsetof(struct tms
, tms_cutime
),
12741 '\n', offsetof(struct tms
, tms_cstime
),
12744 static int FAST_FUNC
12745 timescmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12747 unsigned long clk_tck
, s
, t
;
12748 const unsigned char *p
;
12751 clk_tck
= sysconf(_SC_CLK_TCK
);
12756 t
= *(clock_t *)(((char *) &buf
) + p
[1]);
12759 out1fmt("%lum%lu.%03lus%c",
12761 (t
* 1000) / clk_tck
,
12769 #if ENABLE_SH_MATH_SUPPORT
12771 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12772 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12774 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12776 static int FAST_FUNC
12777 letcmd(int argc UNUSED_PARAM
, char **argv
)
12783 ash_msg_and_raise_error("expression expected");
12785 i
= ash_arith(*argv
);
12793 * The read builtin. Options:
12794 * -r Do not interpret '\' specially
12795 * -s Turn off echo (tty only)
12796 * -n NCHARS Read NCHARS max
12797 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12798 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12799 * -u FD Read from given FD instead of fd 0
12800 * This uses unbuffered input, which may be avoidable in some cases.
12801 * TODO: bash also has:
12802 * -a ARRAY Read into array[0],[1],etc
12803 * -d DELIM End on DELIM char, not newline
12804 * -e Use line editing (tty only)
12806 static int FAST_FUNC
12807 readcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12809 char *opt_n
= NULL
;
12810 char *opt_p
= NULL
;
12811 char *opt_t
= NULL
;
12812 char *opt_u
= NULL
;
12813 int read_flags
= 0;
12817 while ((i
= nextopt("p:u:rt:n:s")) != '\0') {
12826 read_flags
|= BUILTIN_READ_SILENT
;
12832 read_flags
|= BUILTIN_READ_RAW
;
12842 /* "read -s" needs to save/restore termios, can't allow ^C
12843 * to jump out of it.
12846 r
= shell_builtin_read(setvar2
,
12848 bltinlookup("IFS"), /* can be NULL */
12857 if ((uintptr_t)r
> 1)
12858 ash_msg_and_raise_error(r
);
12860 return (uintptr_t)r
;
12863 static int FAST_FUNC
12864 umaskcmd(int argc UNUSED_PARAM
, char **argv
)
12866 static const char permuser
[3] ALIGN1
= "ugo";
12867 static const char permmode
[3] ALIGN1
= "rwx";
12868 static const short permmask
[] ALIGN2
= {
12869 S_IRUSR
, S_IWUSR
, S_IXUSR
,
12870 S_IRGRP
, S_IWGRP
, S_IXGRP
,
12871 S_IROTH
, S_IWOTH
, S_IXOTH
12874 /* TODO: use bb_parse_mode() instead */
12879 int symbolic_mode
= 0;
12881 while (nextopt("S") != '\0') {
12892 if (symbolic_mode
) {
12896 for (i
= 0; i
< 3; i
++) {
12899 *p
++ = permuser
[i
];
12901 for (j
= 0; j
< 3; j
++) {
12902 if ((mask
& permmask
[3 * i
+ j
]) == 0) {
12903 *p
++ = permmode
[j
];
12911 out1fmt("%.4o\n", mask
);
12914 if (isdigit((unsigned char) *ap
)) {
12917 if (*ap
>= '8' || *ap
< '0')
12918 ash_msg_and_raise_error(msg_illnum
, argv
[1]);
12919 mask
= (mask
<< 3) + (*ap
- '0');
12920 } while (*++ap
!= '\0');
12923 mask
= ~mask
& 0777;
12924 if (!bb_parse_mode(ap
, &mask
)) {
12925 ash_msg_and_raise_error("illegal mode: %s", ap
);
12927 umask(~mask
& 0777);
12933 static int FAST_FUNC
12934 ulimitcmd(int argc UNUSED_PARAM
, char **argv
)
12936 return shell_builtin_ulimit(argv
);
12939 /* ============ main() and helpers */
12942 * Called to exit the shell.
12951 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12952 save_history(line_input_state
);
12955 status
= exitstatus
;
12956 TRACE(("pid %d, exitshell(%d)\n", getpid(), status
));
12957 if (setjmp(loc
.loc
)) {
12958 if (exception_type
== EXEXIT
)
12959 /* dash bug: it just does _exit(exitstatus) here
12960 * but we have to do setjobctl(0) first!
12961 * (bug is still not fixed in dash-0.5.3 - if you run dash
12962 * under Midnight Commander, on exit from dash MC is backgrounded) */
12963 status
= exitstatus
;
12966 exception_handler
= &loc
;
12973 flush_stdout_stderr();
12983 /* from input.c: */
12984 /* we will never free this */
12985 basepf
.next_to_pgetc
= basepf
.buf
= ckmalloc(IBUFSIZ
);
12988 signal(SIGCHLD
, SIG_DFL
);
12989 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12990 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12992 signal(SIGHUP
, SIG_DFL
);
12998 struct stat st1
, st2
;
13001 for (envp
= environ
; envp
&& *envp
; envp
++) {
13002 if (strchr(*envp
, '=')) {
13003 setvareq(*envp
, VEXPORT
|VTEXTFIXED
);
13007 setvar("PPID", utoa(getppid()), 0);
13009 p
= lookupvar("PWD");
13011 if (*p
!= '/' || stat(p
, &st1
) || stat(".", &st2
)
13012 || st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
13022 //usage:#define ash_trivial_usage
13023 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13024 //usage:#define ash_full_usage "\n\n"
13025 //usage: "Unix shell interpreter"
13027 //usage:#if ENABLE_FEATURE_SH_IS_ASH
13028 //usage:# define sh_trivial_usage ash_trivial_usage
13029 //usage:# define sh_full_usage ash_full_usage
13031 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
13032 //usage:# define bash_trivial_usage ash_trivial_usage
13033 //usage:# define bash_full_usage ash_full_usage
13037 * Process the shell command line arguments.
13040 procargs(char **argv
)
13043 const char *xminusc
;
13048 /* if (xargv[0]) - mmm, this is always true! */
13050 for (i
= 0; i
< NOPTS
; i
++)
13053 if (options(/*cmdline:*/ 1)) {
13054 /* it already printed err message */
13055 raise_exception(EXERROR
);
13059 if (*xargv
== NULL
) {
13061 ash_msg_and_raise_error(bb_msg_requires_arg
, "-c");
13064 if (iflag
== 2 && sflag
== 1 && isatty(0) && isatty(1))
13068 for (i
= 0; i
< NOPTS
; i
++)
13069 if (optlist
[i
] == 2)
13074 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13079 } else if (!sflag
) {
13080 setinputfile(*xargv
, 0);
13083 commandname
= arg0
;
13086 shellparam
.p
= xargv
;
13087 #if ENABLE_ASH_GETOPTS
13088 shellparam
.optind
= 1;
13089 shellparam
.optoff
= -1;
13091 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13093 shellparam
.nparam
++;
13100 * Read /etc/profile or .profile.
13103 read_profile(const char *name
)
13107 if (setinputfile(name
, INPUT_PUSH_FILE
| INPUT_NOFILE_OK
) < 0)
13116 * This routine is called when an error or an interrupt occurs in an
13117 * interactive shell and control is returned to the main command loop.
13125 /* from input.c: */
13126 g_parsefile
->left_in_buffer
= 0;
13127 g_parsefile
->left_in_line
= 0; /* clear input buffer */
13129 /* from parser.c: */
13132 /* from redir.c: */
13133 clearredir(/*drop:*/ 0);
13137 static short profile_buf
[16384];
13138 extern int etext();
13142 * Main routine. We initialize things, parse the arguments, execute
13143 * profiles if we're a login shell, and then call cmdloop to execute
13144 * commands. The setjmp call sets up the location to jump to when an
13145 * exception occurs. When an exception occurs the variable "state"
13146 * is used to figure out how far we had gotten.
13148 int ash_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
13149 int ash_main(int argc UNUSED_PARAM
, char **argv
)
13151 const char *shinit
;
13152 volatile smallint state
;
13153 struct jmploc jmploc
;
13154 struct stackmark smark
;
13156 /* Initialize global data */
13160 #if ENABLE_ASH_ALIAS
13166 monitor(4, etext
, profile_buf
, sizeof(profile_buf
), 50);
13169 #if ENABLE_FEATURE_EDITING
13170 line_input_state
= new_line_input_t(FOR_SHELL
| WITH_PATH_LOOKUP
);
13173 if (setjmp(jmploc
.loc
)) {
13179 e
= exception_type
;
13183 if (e
== EXEXIT
|| s
== 0 || iflag
== 0 || shlvl
) {
13187 outcslow('\n', stderr
);
13190 popstackmark(&smark
);
13191 FORCE_INT_ON
; /* enable interrupts */
13200 exception_handler
= &jmploc
;
13203 TRACE(("Shell args: "));
13204 trace_puts_args(argv
);
13206 rootpid
= getpid();
13209 setstackmark(&smark
);
13212 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13214 const char *hp
= lookupvar("HISTFILE");
13216 hp
= lookupvar("HOME");
13218 char *defhp
= concat_path_file(hp
, ".ash_history");
13219 setvar("HISTFILE", defhp
, 0);
13225 if (argv
[0] && argv
[0][0] == '-')
13229 read_profile("/etc/profile");
13232 read_profile(".profile");
13238 getuid() == geteuid() && getgid() == getegid() &&
13242 shinit
= lookupvar("ENV");
13243 if (shinit
!= NULL
&& *shinit
!= '\0') {
13244 read_profile(shinit
);
13250 /* evalstring pushes parsefile stack.
13251 * Ensure we don't falsely claim that 0 (stdin)
13252 * is one of stacked source fds.
13253 * Testcase: ash -c 'exec 1>&0' must not complain. */
13254 // if (!sflag) g_parsefile->pf_fd = -1;
13255 // ^^ not necessary since now we special-case fd 0
13256 // in is_hidden_fd() to not be considered "hidden fd"
13257 evalstring(minusc
, 0);
13260 if (sflag
|| minusc
== NULL
) {
13261 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13263 const char *hp
= lookupvar("HISTFILE");
13265 line_input_state
->hist_file
= hp
;
13266 # if ENABLE_FEATURE_SH_HISTFILESIZE
13267 hp
= lookupvar("HISTFILESIZE");
13268 line_input_state
->max_history
= size_from_HISTFILESIZE(hp
);
13272 state4
: /* XXX ??? - why isn't this before the "if" statement */
13280 extern void _mcleanup(void);
13284 TRACE(("End of main reached\n"));
13291 * Copyright (c) 1989, 1991, 1993, 1994
13292 * The Regents of the University of California. All rights reserved.
13294 * This code is derived from software contributed to Berkeley by
13295 * Kenneth Almquist.
13297 * Redistribution and use in source and binary forms, with or without
13298 * modification, are permitted provided that the following conditions
13300 * 1. Redistributions of source code must retain the above copyright
13301 * notice, this list of conditions and the following disclaimer.
13302 * 2. Redistributions in binary form must reproduce the above copyright
13303 * notice, this list of conditions and the following disclaimer in the
13304 * documentation and/or other materials provided with the distribution.
13305 * 3. Neither the name of the University nor the names of its contributors
13306 * may be used to endorse or promote products derived from this software
13307 * without specific prior written permission.
13309 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13310 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13311 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13312 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13313 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13314 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13315 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13316 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13317 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13318 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF