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, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
30 /* Tweak debug output verbosity here */
37 #define JOBS ENABLE_ASH_JOB_CONTROL
42 #include <sys/times.h>
44 #include "busybox.h" /* for applet_names */
47 #include "shell_common.h"
48 #if ENABLE_SH_MATH_SUPPORT
51 #if ENABLE_ASH_RANDOM_SUPPORT
54 # define CLEAR_RANDOM_T(rnd) ((void)0)
57 #include "NUM_APPLETS.h"
59 /* STANDALONE does not make sense, and won't compile */
60 # undef CONFIG_FEATURE_SH_STANDALONE
61 # undef ENABLE_FEATURE_SH_STANDALONE
62 # undef IF_FEATURE_SH_STANDALONE
63 # undef IF_NOT_FEATURE_SH_STANDALONE
64 # define ENABLE_FEATURE_SH_STANDALONE 0
65 # define IF_FEATURE_SH_STANDALONE(...)
66 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
70 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
74 # error "Do not even bother, ash will not run on NOMMU machine"
80 //config: depends on !NOMMU
82 //config: Tha 'ash' shell adds about 60k in the default configuration and is
83 //config: the most complete and most pedantically correct shell included with
84 //config: busybox. This shell is actually a derivative of the Debian 'dash'
85 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
86 //config: (written by Kenneth Almquist) from NetBSD.
88 //config:config ASH_BASH_COMPAT
89 //config: bool "bash-compatible extensions"
91 //config: depends on ASH
93 //config: Enable bash-compatible extensions.
95 //config:config ASH_IDLE_TIMEOUT
96 //config: bool "Idle timeout variable"
98 //config: depends on ASH
100 //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
102 //config:config ASH_JOB_CONTROL
103 //config: bool "Job control"
105 //config: depends on ASH
107 //config: Enable job control in the ash shell.
109 //config:config ASH_ALIAS
110 //config: bool "Alias support"
112 //config: depends on ASH
114 //config: Enable alias support in the ash shell.
116 //config:config ASH_GETOPTS
117 //config: bool "Builtin getopt to parse positional parameters"
119 //config: depends on ASH
121 //config: Enable support for getopts builtin in ash.
123 //config:config ASH_BUILTIN_ECHO
124 //config: bool "Builtin version of 'echo'"
126 //config: depends on ASH
128 //config: Enable support for echo builtin in ash.
130 //config:config ASH_BUILTIN_PRINTF
131 //config: bool "Builtin version of 'printf'"
133 //config: depends on ASH
135 //config: Enable support for printf builtin in ash.
137 //config:config ASH_BUILTIN_TEST
138 //config: bool "Builtin version of 'test'"
140 //config: depends on ASH
142 //config: Enable support for test builtin in ash.
144 //config:config ASH_CMDCMD
145 //config: bool "'command' command to override shell builtins"
147 //config: depends on ASH
149 //config: Enable support for the ash 'command' builtin, which allows
150 //config: you to run the specified command with the specified arguments,
151 //config: even when there is an ash builtin command with the same name.
153 //config:config ASH_MAIL
154 //config: bool "Check for new mail on interactive shells"
156 //config: depends on ASH
158 //config: Enable "check for new mail" function in the ash shell.
160 //config:config ASH_OPTIMIZE_FOR_SIZE
161 //config: bool "Optimize for size instead of speed"
163 //config: depends on ASH
165 //config: Compile ash for reduced size at the price of speed.
167 //config:config ASH_RANDOM_SUPPORT
168 //config: bool "Pseudorandom generator and $RANDOM variable"
170 //config: depends on ASH
172 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
173 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
174 //config: You can reset the generator by using a specified start value.
175 //config: After "unset RANDOM" the generator will switch off and this
176 //config: variable will no longer have special treatment.
178 //config:config ASH_EXPAND_PRMT
179 //config: bool "Expand prompt string"
181 //config: depends on ASH
183 //config: "PS#" may contain volatile content, such as backquote commands.
184 //config: This option recreates the prompt string from the environment
185 //config: variable each time it is displayed.
188 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
189 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
190 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
192 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
193 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
196 /* ============ Hash table sizes. Configurable. */
200 #define CMDTABLESIZE 31 /* should be prime */
203 /* ============ Shell options */
205 static const char *const optletters_optnames
[] = {
220 #if ENABLE_ASH_BASH_COMPAT
229 #define optletters(n) optletters_optnames[n][0]
230 #define optnames(n) (optletters_optnames[n] + 1)
232 enum { NOPTS
= ARRAY_SIZE(optletters_optnames
) };
235 /* ============ Misc data */
237 #define msg_illnum "Illegal number: %s"
240 * We enclose jmp_buf in a structure so that we can declare pointers to
241 * jump locations. The global variable handler contains the location to
242 * jump to when an exception occurs, and the global variable exception_type
243 * contains a code identifying the exception. To implement nested
244 * exception handlers, the user should save the value of handler on entry
245 * to an inner scope, set handler to point to a jmploc structure for the
246 * inner scope, and restore handler on exit from the scope.
252 struct globals_misc
{
253 /* pid of main shell */
255 /* shell level: 0 for the main shell, 1 for its children, and so on */
257 #define rootshell (!shlvl)
258 char *minusc
; /* argument to -c option */
260 char *curdir
; // = nullstr; /* current working directory */
261 char *physdir
; // = nullstr; /* physical working directory */
263 char *arg0
; /* value of $0 */
265 struct jmploc
*exception_handler
;
267 volatile int suppress_int
; /* counter */
268 volatile /*sig_atomic_t*/ smallint pending_int
; /* 1 = got SIGINT */
269 /* last pending signal */
270 volatile /*sig_atomic_t*/ smallint pending_sig
;
271 smallint exception_type
; /* kind of exception (0..5) */
273 #define EXINT 0 /* SIGINT received */
274 #define EXERROR 1 /* a generic error */
275 #define EXSHELLPROC 2 /* execute a shell procedure */
276 #define EXEXEC 3 /* command execution failed */
277 #define EXEXIT 4 /* exit the shell */
278 #define EXSIG 5 /* trapped signal in wait(1) */
281 char nullstr
[1]; /* zero length string */
284 #define eflag optlist[0]
285 #define fflag optlist[1]
286 #define Iflag optlist[2]
287 #define iflag optlist[3]
288 #define mflag optlist[4]
289 #define nflag optlist[5]
290 #define sflag optlist[6]
291 #define xflag optlist[7]
292 #define vflag optlist[8]
293 #define Cflag optlist[9]
294 #define aflag optlist[10]
295 #define bflag optlist[11]
296 #define uflag optlist[12]
297 #define viflag optlist[13]
298 #if ENABLE_ASH_BASH_COMPAT
299 # define pipefail optlist[14]
304 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
305 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
308 /* trap handler commands */
310 * Sigmode records the current value of the signal handlers for the various
311 * modes. A value of zero means that the current handler is not known.
312 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
314 char sigmode
[NSIG
- 1];
315 #define S_DFL 1 /* default signal handling (SIG_DFL) */
316 #define S_CATCH 2 /* signal is caught */
317 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
318 #define S_HARD_IGN 4 /* signal is ignored permenantly */
320 /* indicates specified signal received */
321 uint8_t gotsig
[NSIG
- 1]; /* offset by 1: "signal" 0 is meaningless */
322 uint8_t may_have_traps
; /* 0: definitely no traps are set, 1: some traps may be set */
324 char **trap_ptr
; /* used only by "trap hack" */
326 /* Rarely referenced stuff */
327 #if ENABLE_ASH_RANDOM_SUPPORT
330 pid_t backgndpid
; /* pid of last background process */
331 smallint job_warning
; /* user was warned about stopped jobs (can be 2, 1 or 0). */
333 extern struct globals_misc
*const ash_ptr_to_globals_misc
;
334 #define G_misc (*ash_ptr_to_globals_misc)
335 #define rootpid (G_misc.rootpid )
336 #define shlvl (G_misc.shlvl )
337 #define minusc (G_misc.minusc )
338 #define curdir (G_misc.curdir )
339 #define physdir (G_misc.physdir )
340 #define arg0 (G_misc.arg0 )
341 #define exception_handler (G_misc.exception_handler)
342 #define exception_type (G_misc.exception_type )
343 #define suppress_int (G_misc.suppress_int )
344 #define pending_int (G_misc.pending_int )
345 #define pending_sig (G_misc.pending_sig )
346 #define isloginsh (G_misc.isloginsh )
347 #define nullstr (G_misc.nullstr )
348 #define optlist (G_misc.optlist )
349 #define sigmode (G_misc.sigmode )
350 #define gotsig (G_misc.gotsig )
351 #define may_have_traps (G_misc.may_have_traps )
352 #define trap (G_misc.trap )
353 #define trap_ptr (G_misc.trap_ptr )
354 #define random_gen (G_misc.random_gen )
355 #define backgndpid (G_misc.backgndpid )
356 #define job_warning (G_misc.job_warning)
357 #define INIT_G_misc() do { \
358 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
366 /* ============ DEBUG */
368 static void trace_printf(const char *fmt
, ...);
369 static void trace_vprintf(const char *fmt
, va_list va
);
370 # define TRACE(param) trace_printf param
371 # define TRACEV(param) trace_vprintf param
372 # define close(fd) do { \
374 if (close(dfd) < 0) \
375 bb_error_msg("bug on %d: closing %d(0x%x)", \
376 __LINE__, dfd, dfd); \
379 # define TRACE(param)
380 # define TRACEV(param)
384 /* ============ Utility functions */
385 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
387 static int isdigit_str9(const char *str
)
389 int maxlen
= 9 + 1; /* max 9 digits: 999999999 */
390 while (--maxlen
&& isdigit(*str
))
392 return (*str
== '\0');
395 static const char *var_end(const char *var
)
404 /* ============ Interrupts / exceptions */
406 static void exitshell(void) NORETURN
;
409 * These macros allow the user to suspend the handling of interrupt signals
410 * over a period of time. This is similar to SIGHOLD or to sigblock, but
411 * much more efficient and portable. (But hacking the kernel is so much
412 * more fun than worrying about efficiency and portability. :-))
414 #define INT_OFF do { \
420 * Called to raise an exception. Since C doesn't include exceptions, we
421 * just do a longjmp to the exception handler. The type of exception is
422 * stored in the global variable "exception_type".
424 static void raise_exception(int) NORETURN
;
426 raise_exception(int e
)
429 if (exception_handler
== NULL
)
434 longjmp(exception_handler
->loc
, 1);
437 #define raise_exception(e) do { \
438 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
439 raise_exception(e); \
444 * Called from trap.c when a SIGINT is received. (If the user specifies
445 * that SIGINT is to be trapped or ignored using the trap builtin, then
446 * this routine is not called.) Suppressint is nonzero when interrupts
447 * are held using the INT_OFF macro. (The test for iflag is just
448 * defensive programming.)
450 static void raise_interrupt(void) NORETURN
;
452 raise_interrupt(void)
457 /* Signal is not automatically unmasked after it is raised,
458 * do it ourself - unmask all signals */
459 sigprocmask_allsigs(SIG_UNBLOCK
);
460 /* pending_sig = 0; - now done in signal_handler() */
463 if (gotsig
[SIGINT
- 1] && !trap
[SIGINT
]) {
464 if (!(rootshell
&& iflag
)) {
465 /* Kill ourself with SIGINT */
466 signal(SIGINT
, SIG_DFL
);
471 raise_exception(ex_type
);
475 #define raise_interrupt() do { \
476 TRACE(("raising interrupt on line %d\n", __LINE__)); \
481 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
485 if (--suppress_int
== 0 && pending_int
) {
489 #define INT_ON int_on()
490 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
498 #define FORCE_INT_ON force_int_on()
500 #define SAVE_INT(v) ((v) = suppress_int)
502 #define RESTORE_INT(v) do { \
504 suppress_int = (v); \
505 if (suppress_int == 0 && pending_int) \
510 /* ============ Stdout/stderr output */
513 outstr(const char *p
, FILE *file
)
521 flush_stdout_stderr(void)
529 outcslow(int c
, FILE *dest
)
537 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__
,1,2)));
539 out1fmt(const char *fmt
, ...)
546 r
= vprintf(fmt
, ap
);
552 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__
,3,4)));
554 fmtstr(char *outbuf
, size_t length
, const char *fmt
, ...)
561 ret
= vsnprintf(outbuf
, length
, fmt
, ap
);
568 out1str(const char *p
)
574 out2str(const char *p
)
577 flush_stdout_stderr();
581 /* ============ Parser structures */
583 /* control characters in argument strings */
584 #define CTL_FIRST CTLESC
585 #define CTLESC ((unsigned char)'\201') /* escape next character */
586 #define CTLVAR ((unsigned char)'\202') /* variable defn */
587 #define CTLENDVAR ((unsigned char)'\203')
588 #define CTLBACKQ ((unsigned char)'\204')
589 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
590 /* CTLBACKQ | CTLQUOTE == '\205' */
591 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
592 #define CTLENDARI ((unsigned char)'\207')
593 #define CTLQUOTEMARK ((unsigned char)'\210')
594 #define CTL_LAST CTLQUOTEMARK
596 /* variable substitution byte (follows CTLVAR) */
597 #define VSTYPE 0x0f /* type of variable substitution */
598 #define VSNUL 0x10 /* colon--treat the empty string as unset */
599 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
601 /* values of VSTYPE field */
602 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
603 #define VSMINUS 0x2 /* ${var-text} */
604 #define VSPLUS 0x3 /* ${var+text} */
605 #define VSQUESTION 0x4 /* ${var?message} */
606 #define VSASSIGN 0x5 /* ${var=text} */
607 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
608 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
609 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
610 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
611 #define VSLENGTH 0xa /* ${#var} */
612 #if ENABLE_ASH_BASH_COMPAT
613 #define VSSUBSTR 0xc /* ${var:position:length} */
614 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
615 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
618 static const char dolatstr
[] ALIGN1
= {
619 CTLVAR
, VSNORMAL
|VSQUOTE
, '@', '=', '\0'
639 #if ENABLE_ASH_BASH_COMPAT
656 smallint type
; /* Nxxxx */
659 union node
*redirect
;
664 smallint pipe_backgnd
;
665 struct nodelist
*cmdlist
;
671 union node
*redirect
;
684 union node
*elsepart
;
711 struct nodelist
*backquote
;
714 /* nfile and ndup layout must match!
715 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
716 * that it is actually NTO2 (>&file), and change its type.
733 char *_unused_expfname
;
752 struct nredir nredir
;
753 struct nbinary nbinary
;
757 struct nclist nclist
;
766 * NODE_EOF is returned by parsecmd when it encounters an end of file.
767 * It must be distinct from NULL.
769 #define NODE_EOF ((union node *) -1L)
772 struct nodelist
*next
;
785 freefunc(struct funcnode
*f
)
787 if (f
&& --f
->count
< 0)
792 /* ============ Debugging output */
796 static FILE *tracefile
;
799 trace_printf(const char *fmt
, ...)
806 fprintf(tracefile
, "%u ", (int) time(NULL
));
808 fprintf(tracefile
, "[%u] ", (int) getpid());
810 fprintf(tracefile
, "pending s:%d i:%d(supp:%d) ", pending_sig
, pending_int
, suppress_int
);
812 vfprintf(tracefile
, fmt
, va
);
817 trace_vprintf(const char *fmt
, va_list va
)
822 fprintf(tracefile
, "%u ", (int) time(NULL
));
824 fprintf(tracefile
, "[%u] ", (int) getpid());
826 fprintf(tracefile
, "pending s:%d i:%d(supp:%d) ", pending_sig
, pending_int
, suppress_int
);
827 vfprintf(tracefile
, fmt
, va
);
831 trace_puts(const char *s
)
839 trace_puts_quoted(char *s
)
846 putc('"', tracefile
);
847 for (p
= s
; *p
; p
++) {
848 switch ((unsigned char)*p
) {
849 case '\n': c
= 'n'; goto backslash
;
850 case '\t': c
= 't'; goto backslash
;
851 case '\r': c
= 'r'; goto backslash
;
852 case '\"': c
= '\"'; goto backslash
;
853 case '\\': c
= '\\'; goto backslash
;
854 case CTLESC
: c
= 'e'; goto backslash
;
855 case CTLVAR
: c
= 'v'; goto backslash
;
856 case CTLVAR
+CTLQUOTE
: c
= 'V'; goto backslash
;
857 case CTLBACKQ
: c
= 'q'; goto backslash
;
858 case CTLBACKQ
+CTLQUOTE
: c
= 'Q'; goto backslash
;
860 putc('\\', tracefile
);
864 if (*p
>= ' ' && *p
<= '~')
867 putc('\\', tracefile
);
868 putc((*p
>> 6) & 03, tracefile
);
869 putc((*p
>> 3) & 07, tracefile
);
870 putc(*p
& 07, tracefile
);
875 putc('"', tracefile
);
879 trace_puts_args(char **ap
)
886 trace_puts_quoted(*ap
);
888 putc('\n', tracefile
);
891 putc(' ', tracefile
);
906 /* leave open because libedit might be using it */
909 strcpy(s
, "./trace");
911 if (!freopen(s
, "a", tracefile
)) {
912 fprintf(stderr
, "Can't re-open %s\n", s
);
917 tracefile
= fopen(s
, "a");
918 if (tracefile
== NULL
) {
919 fprintf(stderr
, "Can't open %s\n", s
);
925 flags
= fcntl(fileno(tracefile
), F_GETFL
);
927 fcntl(fileno(tracefile
), F_SETFL
, flags
| O_APPEND
);
929 setlinebuf(tracefile
);
930 fputs("\nTracing started.\n", tracefile
);
934 indent(int amount
, char *pfx
, FILE *fp
)
938 for (i
= 0; i
< amount
; i
++) {
939 if (pfx
&& i
== amount
- 1)
945 /* little circular references here... */
946 static void shtree(union node
*n
, int ind
, char *pfx
, FILE *fp
);
949 sharg(union node
*arg
, FILE *fp
)
952 struct nodelist
*bqlist
;
953 unsigned char subtype
;
955 if (arg
->type
!= NARG
) {
956 out1fmt("<node type %d>\n", arg
->type
);
959 bqlist
= arg
->narg
.backquote
;
960 for (p
= arg
->narg
.text
; *p
; p
++) {
961 switch ((unsigned char)*p
) {
970 if (subtype
== VSLENGTH
)
981 switch (subtype
& VSTYPE
) {
1007 case VSTRIMRIGHTMAX
:
1014 out1fmt("<subtype %d>", subtype
);
1021 case CTLBACKQ
|CTLQUOTE
:
1024 shtree(bqlist
->n
, -1, NULL
, fp
);
1035 shcmd(union node
*cmd
, FILE *fp
)
1043 for (np
= cmd
->ncmd
.args
; np
; np
= np
->narg
.next
) {
1049 for (np
= cmd
->ncmd
.redirect
; np
; np
= np
->nfile
.next
) {
1053 switch (np
->nfile
.type
) {
1054 case NTO
: s
= ">>"+1; dftfd
= 1; break;
1055 case NCLOBBER
: s
= ">|"; dftfd
= 1; break;
1056 case NAPPEND
: s
= ">>"; dftfd
= 1; break;
1057 #if ENABLE_ASH_BASH_COMPAT
1060 case NTOFD
: s
= ">&"; dftfd
= 1; break;
1061 case NFROM
: s
= "<"; break;
1062 case NFROMFD
: s
= "<&"; break;
1063 case NFROMTO
: s
= "<>"; break;
1064 default: s
= "*error*"; break;
1066 if (np
->nfile
.fd
!= dftfd
)
1067 fprintf(fp
, "%d", np
->nfile
.fd
);
1069 if (np
->nfile
.type
== NTOFD
|| np
->nfile
.type
== NFROMFD
) {
1070 fprintf(fp
, "%d", np
->ndup
.dupfd
);
1072 sharg(np
->nfile
.fname
, fp
);
1079 shtree(union node
*n
, int ind
, char *pfx
, FILE *fp
)
1081 struct nodelist
*lp
;
1087 indent(ind
, pfx
, fp
);
1089 if (n
== NODE_EOF
) {
1104 shtree(n
->nbinary
.ch1
, ind
, NULL
, fp
);
1107 shtree(n
->nbinary
.ch2
, ind
, NULL
, fp
);
1115 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
) {
1116 shtree(lp
->n
, 0, NULL
, fp
);
1120 if (n
->npipe
.pipe_backgnd
)
1126 fprintf(fp
, "<node type %d>", n
->type
);
1134 showtree(union node
*n
)
1136 trace_puts("showtree called\n");
1137 shtree(n
, 1, NULL
, stderr
);
1143 /* ============ Parser data */
1146 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1149 struct strlist
*next
;
1156 struct strpush
*prev
; /* preceding string on stack */
1158 int prev_left_in_line
;
1159 #if ENABLE_ASH_ALIAS
1160 struct alias
*ap
; /* if push was associated with an alias */
1162 char *string
; /* remember the string since it may change */
1166 struct parsefile
*prev
; /* preceding file on stack */
1167 int linno
; /* current line */
1168 int pf_fd
; /* file descriptor (or -1 if string) */
1169 int left_in_line
; /* number of chars left in this line */
1170 int left_in_buffer
; /* number of chars left in this buffer past the line */
1171 char *next_to_pgetc
; /* next char in buffer */
1172 char *buf
; /* input buffer */
1173 struct strpush
*strpush
; /* for pushing strings at this level */
1174 struct strpush basestrpush
; /* so pushing one is fast */
1177 static struct parsefile basepf
; /* top level input file */
1178 static struct parsefile
*g_parsefile
= &basepf
; /* current input file */
1179 static int startlinno
; /* line # where last token started */
1180 static char *commandname
; /* currently executing command */
1181 static struct strlist
*cmdenviron
; /* environment for builtin command */
1182 static uint8_t exitstatus
; /* exit status of last command */
1185 /* ============ Message printing */
1188 ash_vmsg(const char *msg
, va_list ap
)
1190 fprintf(stderr
, "%s: ", arg0
);
1192 if (strcmp(arg0
, commandname
))
1193 fprintf(stderr
, "%s: ", commandname
);
1194 if (!iflag
|| g_parsefile
->pf_fd
> 0)
1195 fprintf(stderr
, "line %d: ", startlinno
);
1197 vfprintf(stderr
, msg
, ap
);
1198 outcslow('\n', stderr
);
1202 * Exverror is called to raise the error exception. If the second argument
1203 * is not NULL then error prints an error message using printf style
1204 * formatting. It then raises the error exception.
1206 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN
;
1208 ash_vmsg_and_raise(int cond
, const char *msg
, va_list ap
)
1212 TRACE(("ash_vmsg_and_raise(%d, \"", cond
));
1214 TRACE(("\") pid=%d\n", getpid()));
1216 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond
, getpid()));
1221 flush_stdout_stderr();
1222 raise_exception(cond
);
1226 static void ash_msg_and_raise_error(const char *, ...) NORETURN
;
1228 ash_msg_and_raise_error(const char *msg
, ...)
1233 ash_vmsg_and_raise(EXERROR
, msg
, ap
);
1238 static void raise_error_syntax(const char *) NORETURN
;
1240 raise_error_syntax(const char *msg
)
1242 ash_msg_and_raise_error("syntax error: %s", msg
);
1246 static void ash_msg_and_raise(int, const char *, ...) NORETURN
;
1248 ash_msg_and_raise(int cond
, const char *msg
, ...)
1253 ash_vmsg_and_raise(cond
, msg
, ap
);
1259 * error/warning routines for external builtins
1262 ash_msg(const char *fmt
, ...)
1272 * Return a string describing an error. The returned string may be a
1273 * pointer to a static buffer that will be overwritten on the next call.
1274 * Action describes the operation that got the error.
1277 errmsg(int e
, const char *em
)
1279 if (e
== ENOENT
|| e
== ENOTDIR
) {
1286 /* ============ Memory allocation */
1289 /* I consider these wrappers nearly useless:
1290 * ok, they return you to nearest exception handler, but
1291 * how much memory do you leak in the process, making
1292 * memory starvation worse?
1295 ckrealloc(void * p
, size_t nbytes
)
1297 p
= realloc(p
, nbytes
);
1299 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1304 ckmalloc(size_t nbytes
)
1306 return ckrealloc(NULL
, nbytes
);
1310 ckzalloc(size_t nbytes
)
1312 return memset(ckmalloc(nbytes
), 0, nbytes
);
1316 ckstrdup(const char *s
)
1318 char *p
= strdup(s
);
1320 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1324 /* Using bbox equivalents. They exit if out of memory */
1325 # define ckrealloc xrealloc
1326 # define ckmalloc xmalloc
1327 # define ckzalloc xzalloc
1328 # define ckstrdup xstrdup
1332 * It appears that grabstackstr() will barf with such alignments
1333 * because stalloc() will return a string allocated in a new stackblock.
1335 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1337 /* Most machines require the value returned from malloc to be aligned
1338 * in some way. The following macro will get this right
1339 * on many machines. */
1340 SHELL_SIZE
= sizeof(union { int i
; char *cp
; double d
; }) - 1,
1341 /* Minimum size of a block */
1342 MINSIZE
= SHELL_ALIGN(504),
1345 struct stack_block
{
1346 struct stack_block
*prev
;
1347 char space
[MINSIZE
];
1351 struct stack_block
*stackp
;
1354 struct stackmark
*marknext
;
1358 struct globals_memstack
{
1359 struct stack_block
*g_stackp
; // = &stackbase;
1360 struct stackmark
*markp
;
1361 char *g_stacknxt
; // = stackbase.space;
1362 char *sstrend
; // = stackbase.space + MINSIZE;
1363 size_t g_stacknleft
; // = MINSIZE;
1364 int herefd
; // = -1;
1365 struct stack_block stackbase
;
1367 extern struct globals_memstack
*const ash_ptr_to_globals_memstack
;
1368 #define G_memstack (*ash_ptr_to_globals_memstack)
1369 #define g_stackp (G_memstack.g_stackp )
1370 #define markp (G_memstack.markp )
1371 #define g_stacknxt (G_memstack.g_stacknxt )
1372 #define sstrend (G_memstack.sstrend )
1373 #define g_stacknleft (G_memstack.g_stacknleft)
1374 #define herefd (G_memstack.herefd )
1375 #define stackbase (G_memstack.stackbase )
1376 #define INIT_G_memstack() do { \
1377 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1379 g_stackp = &stackbase; \
1380 g_stacknxt = stackbase.space; \
1381 g_stacknleft = MINSIZE; \
1382 sstrend = stackbase.space + MINSIZE; \
1387 #define stackblock() ((void *)g_stacknxt)
1388 #define stackblocksize() g_stacknleft
1391 * Parse trees for commands are allocated in lifo order, so we use a stack
1392 * to make this more efficient, and also to avoid all sorts of exception
1393 * handling code to handle interrupts in the middle of a parse.
1395 * The size 504 was chosen because the Ultrix malloc handles that size
1399 stalloc(size_t nbytes
)
1404 aligned
= SHELL_ALIGN(nbytes
);
1405 if (aligned
> g_stacknleft
) {
1408 struct stack_block
*sp
;
1410 blocksize
= aligned
;
1411 if (blocksize
< MINSIZE
)
1412 blocksize
= MINSIZE
;
1413 len
= sizeof(struct stack_block
) - MINSIZE
+ blocksize
;
1414 if (len
< blocksize
)
1415 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1418 sp
->prev
= g_stackp
;
1419 g_stacknxt
= sp
->space
;
1420 g_stacknleft
= blocksize
;
1421 sstrend
= g_stacknxt
+ blocksize
;
1426 g_stacknxt
+= aligned
;
1427 g_stacknleft
-= aligned
;
1432 stzalloc(size_t nbytes
)
1434 return memset(stalloc(nbytes
), 0, nbytes
);
1441 if (!p
|| (g_stacknxt
< (char *)p
) || ((char *)p
< g_stackp
->space
)) {
1442 write(STDERR_FILENO
, "stunalloc\n", 10);
1446 g_stacknleft
+= g_stacknxt
- (char *)p
;
1451 * Like strdup but works with the ash stack.
1454 ststrdup(const char *p
)
1456 size_t len
= strlen(p
) + 1;
1457 return memcpy(stalloc(len
), p
, len
);
1461 setstackmark(struct stackmark
*mark
)
1463 mark
->stackp
= g_stackp
;
1464 mark
->stacknxt
= g_stacknxt
;
1465 mark
->stacknleft
= g_stacknleft
;
1466 mark
->marknext
= markp
;
1471 popstackmark(struct stackmark
*mark
)
1473 struct stack_block
*sp
;
1479 markp
= mark
->marknext
;
1480 while (g_stackp
!= mark
->stackp
) {
1482 g_stackp
= sp
->prev
;
1485 g_stacknxt
= mark
->stacknxt
;
1486 g_stacknleft
= mark
->stacknleft
;
1487 sstrend
= mark
->stacknxt
+ mark
->stacknleft
;
1492 * When the parser reads in a string, it wants to stick the string on the
1493 * stack and only adjust the stack pointer when it knows how big the
1494 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1495 * of space on top of the stack and stackblocklen returns the length of
1496 * this block. Growstackblock will grow this space by at least one byte,
1497 * possibly moving it (like realloc). Grabstackblock actually allocates the
1498 * part of the block that has been used.
1501 growstackblock(void)
1505 newlen
= g_stacknleft
* 2;
1506 if (newlen
< g_stacknleft
)
1507 ash_msg_and_raise_error(bb_msg_memory_exhausted
);
1511 if (g_stacknxt
== g_stackp
->space
&& g_stackp
!= &stackbase
) {
1512 struct stack_block
*oldstackp
;
1513 struct stackmark
*xmark
;
1514 struct stack_block
*sp
;
1515 struct stack_block
*prevstackp
;
1519 oldstackp
= g_stackp
;
1521 prevstackp
= sp
->prev
;
1522 grosslen
= newlen
+ sizeof(struct stack_block
) - MINSIZE
;
1523 sp
= ckrealloc(sp
, grosslen
);
1524 sp
->prev
= prevstackp
;
1526 g_stacknxt
= sp
->space
;
1527 g_stacknleft
= newlen
;
1528 sstrend
= sp
->space
+ newlen
;
1531 * Stack marks pointing to the start of the old block
1532 * must be relocated to point to the new block
1535 while (xmark
!= NULL
&& xmark
->stackp
== oldstackp
) {
1536 xmark
->stackp
= g_stackp
;
1537 xmark
->stacknxt
= g_stacknxt
;
1538 xmark
->stacknleft
= g_stacknleft
;
1539 xmark
= xmark
->marknext
;
1543 char *oldspace
= g_stacknxt
;
1544 size_t oldlen
= g_stacknleft
;
1545 char *p
= stalloc(newlen
);
1547 /* free the space we just allocated */
1548 g_stacknxt
= memcpy(p
, oldspace
, oldlen
);
1549 g_stacknleft
+= newlen
;
1554 grabstackblock(size_t len
)
1556 len
= SHELL_ALIGN(len
);
1558 g_stacknleft
-= len
;
1562 * The following routines are somewhat easier to use than the above.
1563 * The user declares a variable of type STACKSTR, which may be declared
1564 * to be a register. The macro STARTSTACKSTR initializes things. Then
1565 * the user uses the macro STPUTC to add characters to the string. In
1566 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1567 * grown as necessary. When the user is done, she can just leave the
1568 * string there and refer to it using stackblock(). Or she can allocate
1569 * the space for it using grabstackstr(). If it is necessary to allow
1570 * someone else to use the stack temporarily and then continue to grow
1571 * the string, the user should use grabstack to allocate the space, and
1572 * then call ungrabstr(p) to return to the previous mode of operation.
1574 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1575 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1576 * is space for at least one character.
1581 size_t len
= stackblocksize();
1582 if (herefd
>= 0 && len
>= 1024) {
1583 full_write(herefd
, stackblock(), len
);
1584 return stackblock();
1587 return (char *)stackblock() + len
;
1591 * Called from CHECKSTRSPACE.
1594 makestrspace(size_t newlen
, char *p
)
1596 size_t len
= p
- g_stacknxt
;
1597 size_t size
= stackblocksize();
1602 size
= stackblocksize();
1604 if (nleft
>= newlen
)
1608 return (char *)stackblock() + len
;
1612 stack_nputstr(const char *s
, size_t n
, char *p
)
1614 p
= makestrspace(n
, p
);
1615 p
= (char *)memcpy(p
, s
, n
) + n
;
1620 stack_putstr(const char *s
, char *p
)
1622 return stack_nputstr(s
, strlen(s
), p
);
1626 _STPUTC(int c
, char *p
)
1634 #define STARTSTACKSTR(p) ((p) = stackblock())
1635 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1636 #define CHECKSTRSPACE(n, p) do { \
1639 size_t m = sstrend - q; \
1641 (p) = makestrspace(l, q); \
1643 #define USTPUTC(c, p) (*(p)++ = (c))
1644 #define STACKSTRNUL(p) do { \
1645 if ((p) == sstrend) \
1646 (p) = growstackstr(); \
1649 #define STUNPUTC(p) (--(p))
1650 #define STTOPC(p) ((p)[-1])
1651 #define STADJUST(amount, p) ((p) += (amount))
1653 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1654 #define ungrabstackstr(s, p) stunalloc(s)
1655 #define stackstrend() ((void *)sstrend)
1658 /* ============ String helpers */
1661 * prefix -- see if pfx is a prefix of string.
1664 prefix(const char *string
, const char *pfx
)
1667 if (*pfx
++ != *string
++)
1670 return (char *) string
;
1674 * Check for a valid number. This should be elsewhere.
1677 is_number(const char *p
)
1682 } while (*++p
!= '\0');
1687 * Convert a string of digits to an integer, printing an error message on
1691 number(const char *s
)
1694 ash_msg_and_raise_error(msg_illnum
, s
);
1699 * Produce a possibly single quoted string suitable as input to the shell.
1700 * The return string is allocated on the stack.
1703 single_quote(const char *s
)
1713 len
= strchrnul(s
, '\'') - s
;
1715 q
= p
= makestrspace(len
+ 3, p
);
1718 q
= (char *)memcpy(q
, s
, len
) + len
;
1727 do len
++; while (*++s
== '\'');
1729 q
= p
= makestrspace(len
+ 3, p
);
1732 q
= (char *)memcpy(q
, s
- len
, len
) + len
;
1740 return stackblock();
1744 /* ============ nextopt */
1746 static char **argptr
; /* argument list for builtin commands */
1747 static char *optionarg
; /* set by nextopt (like getopt) */
1748 static char *optptr
; /* used by nextopt */
1751 * XXX - should get rid of. Have all builtins use getopt(3).
1752 * The library getopt must have the BSD extension static variable
1753 * "optreset", otherwise it can't be used within the shell safely.
1755 * Standard option processing (a la getopt) for builtin routines.
1756 * The only argument that is passed to nextopt is the option string;
1757 * the other arguments are unnecessary. It returns the character,
1758 * or '\0' on end of input.
1761 nextopt(const char *optstring
)
1768 if (p
== NULL
|| *p
== '\0') {
1769 /* We ate entire "-param", take next one */
1775 if (*++p
== '\0') /* just "-" ? */
1778 if (LONE_DASH(p
)) /* "--" ? */
1780 /* p => next "-param" */
1782 /* p => some option char in the middle of a "-param" */
1784 for (q
= optstring
; *q
!= c
;) {
1786 ash_msg_and_raise_error("illegal option -%c", c
);
1794 ash_msg_and_raise_error("no arg for -%c option", c
);
1804 /* ============ Shell variables */
1807 * The parsefile structure pointed to by the global variable parsefile
1808 * contains information about the current file being read.
1811 int nparam
; /* # of positional parameters (without $0) */
1812 #if ENABLE_ASH_GETOPTS
1813 int optind
; /* next parameter to be processed by getopts */
1814 int optoff
; /* used by getopts */
1816 unsigned char malloced
; /* if parameter list dynamically allocated */
1817 char **p
; /* parameter list */
1821 * Free the list of positional parameters.
1824 freeparam(volatile struct shparam
*param
)
1826 if (param
->malloced
) {
1828 ap
= ap1
= param
->p
;
1835 #if ENABLE_ASH_GETOPTS
1836 static void FAST_FUNC
getoptsreset(const char *value
);
1840 struct var
*next
; /* next entry in hash list */
1841 int flags
; /* flags are defined above */
1842 const char *var_text
; /* name=value */
1843 void (*var_func
)(const char *) FAST_FUNC
; /* function to be called when */
1844 /* the variable gets set/unset */
1848 struct localvar
*next
; /* next local variable in list */
1849 struct var
*vp
; /* the variable that was made local */
1850 int flags
; /* saved flags */
1851 const char *text
; /* saved text */
1855 #define VEXPORT 0x01 /* variable is exported */
1856 #define VREADONLY 0x02 /* variable cannot be modified */
1857 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1858 #define VTEXTFIXED 0x08 /* text is statically allocated */
1859 #define VSTACK 0x10 /* text is allocated on the stack */
1860 #define VUNSET 0x20 /* the variable is not set */
1861 #define VNOFUNC 0x40 /* don't call the callback function */
1862 #define VNOSET 0x80 /* do not set variable - just readonly test */
1863 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1864 #if ENABLE_ASH_RANDOM_SUPPORT
1865 # define VDYNAMIC 0x200 /* dynamic variable */
1871 /* Need to be before varinit_data[] */
1872 #if ENABLE_LOCALE_SUPPORT
1873 static void FAST_FUNC
1874 change_lc_all(const char *value
)
1876 if (value
&& *value
!= '\0')
1877 setlocale(LC_ALL
, value
);
1879 static void FAST_FUNC
1880 change_lc_ctype(const char *value
)
1882 if (value
&& *value
!= '\0')
1883 setlocale(LC_CTYPE
, value
);
1887 static void chkmail(void);
1888 static void changemail(const char *var_value
) FAST_FUNC
;
1890 # define chkmail() ((void)0)
1892 static void changepath(const char *) FAST_FUNC
;
1893 #if ENABLE_ASH_RANDOM_SUPPORT
1894 static void change_random(const char *) FAST_FUNC
;
1897 static const struct {
1899 const char *var_text
;
1900 void (*var_func
)(const char *) FAST_FUNC
;
1901 } varinit_data
[] = {
1902 { VSTRFIXED
|VTEXTFIXED
, defifsvar
, NULL
},
1904 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "MAIL" , changemail
},
1905 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "MAILPATH" , changemail
},
1907 { VSTRFIXED
|VTEXTFIXED
, bb_PATH_root_path
, changepath
},
1908 { VSTRFIXED
|VTEXTFIXED
, "PS1=$ " , NULL
},
1909 { VSTRFIXED
|VTEXTFIXED
, "PS2=> " , NULL
},
1910 { VSTRFIXED
|VTEXTFIXED
, "PS4=+ " , NULL
},
1911 #if ENABLE_ASH_GETOPTS
1912 { VSTRFIXED
|VTEXTFIXED
, "OPTIND=1" , getoptsreset
},
1914 #if ENABLE_ASH_RANDOM_SUPPORT
1915 { VSTRFIXED
|VTEXTFIXED
|VUNSET
|VDYNAMIC
, "RANDOM", change_random
},
1917 #if ENABLE_LOCALE_SUPPORT
1918 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "LC_ALL" , change_lc_all
},
1919 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "LC_CTYPE" , change_lc_ctype
},
1921 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1922 { VSTRFIXED
|VTEXTFIXED
|VUNSET
, "HISTFILE" , NULL
},
1928 struct globals_var
{
1929 struct shparam shellparam
; /* $@ current positional parameters */
1930 struct redirtab
*redirlist
;
1932 int preverrout_fd
; /* save fd2 before print debug if xflag is set. */
1933 struct var
*vartab
[VTABSIZE
];
1934 struct var varinit
[ARRAY_SIZE(varinit_data
)];
1936 extern struct globals_var
*const ash_ptr_to_globals_var
;
1937 #define G_var (*ash_ptr_to_globals_var)
1938 #define shellparam (G_var.shellparam )
1939 //#define redirlist (G_var.redirlist )
1940 #define g_nullredirs (G_var.g_nullredirs )
1941 #define preverrout_fd (G_var.preverrout_fd)
1942 #define vartab (G_var.vartab )
1943 #define varinit (G_var.varinit )
1944 #define INIT_G_var() do { \
1946 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1948 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1949 varinit[i].flags = varinit_data[i].flags; \
1950 varinit[i].var_text = varinit_data[i].var_text; \
1951 varinit[i].var_func = varinit_data[i].var_func; \
1955 #define vifs varinit[0]
1957 # define vmail (&vifs)[1]
1958 # define vmpath (&vmail)[1]
1959 # define vpath (&vmpath)[1]
1961 # define vpath (&vifs)[1]
1963 #define vps1 (&vpath)[1]
1964 #define vps2 (&vps1)[1]
1965 #define vps4 (&vps2)[1]
1966 #if ENABLE_ASH_GETOPTS
1967 # define voptind (&vps4)[1]
1968 # if ENABLE_ASH_RANDOM_SUPPORT
1969 # define vrandom (&voptind)[1]
1972 # if ENABLE_ASH_RANDOM_SUPPORT
1973 # define vrandom (&vps4)[1]
1978 * The following macros access the values of the above variables.
1979 * They have to skip over the name. They return the null string
1980 * for unset variables.
1982 #define ifsval() (vifs.var_text + 4)
1983 #define ifsset() ((vifs.flags & VUNSET) == 0)
1985 # define mailval() (vmail.var_text + 5)
1986 # define mpathval() (vmpath.var_text + 9)
1987 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1989 #define pathval() (vpath.var_text + 5)
1990 #define ps1val() (vps1.var_text + 4)
1991 #define ps2val() (vps2.var_text + 4)
1992 #define ps4val() (vps4.var_text + 4)
1993 #if ENABLE_ASH_GETOPTS
1994 # define optindval() (voptind.var_text + 7)
1997 #if ENABLE_ASH_GETOPTS
1998 static void FAST_FUNC
1999 getoptsreset(const char *value
)
2001 shellparam
.optind
= number(value
);
2002 shellparam
.optoff
= -1;
2006 /* math.h has these, otherwise define our private copies */
2007 #if !ENABLE_SH_MATH_SUPPORT
2008 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
2009 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
2011 * Return the pointer to the first char which is not part of a legal variable name
2012 * (a letter or underscore followed by letters, underscores, and digits).
2015 endofname(const char *name
)
2017 if (!is_name(*name
))
2020 if (!is_in_name(*name
))
2028 * Compares two strings up to the first = or '\0'. The first
2029 * string must be terminated by '='; the second may be terminated by
2030 * either '=' or '\0'.
2033 varcmp(const char *p
, const char *q
)
2037 while ((c
= *p
) == (d
= *q
)) {
2052 * Find the appropriate entry in the hash table from the name.
2054 static struct var
**
2055 hashvar(const char *p
)
2059 hashval
= ((unsigned char) *p
) << 4;
2060 while (*p
&& *p
!= '=')
2061 hashval
+= (unsigned char) *p
++;
2062 return &vartab
[hashval
% VTABSIZE
];
2066 vpcmp(const void *a
, const void *b
)
2068 return varcmp(*(const char **)a
, *(const char **)b
);
2072 * This routine initializes the builtin variables.
2082 * PS1 depends on uid
2084 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2085 vps1
.var_text
= "PS1=\\w \\$ ";
2088 vps1
.var_text
= "PS1=# ";
2091 end
= vp
+ ARRAY_SIZE(varinit
);
2093 vpp
= hashvar(vp
->var_text
);
2096 } while (++vp
< end
);
2099 static struct var
**
2100 findvar(struct var
**vpp
, const char *name
)
2102 for (; *vpp
; vpp
= &(*vpp
)->next
) {
2103 if (varcmp((*vpp
)->var_text
, name
) == 0) {
2111 * Find the value of a variable. Returns NULL if not set.
2113 static const char* FAST_FUNC
2114 lookupvar(const char *name
)
2118 v
= *findvar(hashvar(name
), name
);
2120 #if ENABLE_ASH_RANDOM_SUPPORT
2122 * Dynamic variables are implemented roughly the same way they are
2123 * in bash. Namely, they're "special" so long as they aren't unset.
2124 * As soon as they're unset, they're no longer dynamic, and dynamic
2125 * lookup will no longer happen at that point. -- PFM.
2127 if (v
->flags
& VDYNAMIC
)
2130 if (!(v
->flags
& VUNSET
))
2131 return var_end(v
->var_text
);
2137 * Search the environment of a builtin command.
2140 bltinlookup(const char *name
)
2144 for (sp
= cmdenviron
; sp
; sp
= sp
->next
) {
2145 if (varcmp(sp
->text
, name
) == 0)
2146 return var_end(sp
->text
);
2148 return lookupvar(name
);
2152 * Same as setvar except that the variable and value are passed in
2153 * the first argument as name=value. Since the first argument will
2154 * be actually stored in the table, it should not be a string that
2156 * Called with interrupts off.
2159 setvareq(char *s
, int flags
)
2161 struct var
*vp
, **vpp
;
2164 flags
|= (VEXPORT
& (((unsigned) (1 - aflag
)) - 1));
2165 vp
= *findvar(vpp
, s
);
2167 if ((vp
->flags
& (VREADONLY
|VDYNAMIC
)) == VREADONLY
) {
2170 if (flags
& VNOSAVE
)
2173 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n
, '=') - n
, n
);
2179 if (vp
->var_func
&& !(flags
& VNOFUNC
))
2180 vp
->var_func(var_end(s
));
2182 if (!(vp
->flags
& (VTEXTFIXED
|VSTACK
)))
2183 free((char*)vp
->var_text
);
2185 flags
|= vp
->flags
& ~(VTEXTFIXED
|VSTACK
|VNOSAVE
|VUNSET
);
2187 /* variable s is not found */
2190 vp
= ckzalloc(sizeof(*vp
));
2192 /*vp->func = NULL; - ckzalloc did it */
2195 if (!(flags
& (VTEXTFIXED
|VSTACK
|VNOSAVE
)))
2202 * Set the value of a variable. The flags argument is ored with the
2203 * flags of the variable. If val is NULL, the variable is unset.
2206 setvar(const char *name
, const char *val
, int flags
)
2214 q
= endofname(name
);
2215 p
= strchrnul(q
, '=');
2217 if (!namelen
|| p
!= q
)
2218 ash_msg_and_raise_error("%.*s: bad variable name", namelen
, name
);
2223 vallen
= strlen(val
);
2227 nameeq
= ckmalloc(namelen
+ vallen
+ 2);
2228 p
= memcpy(nameeq
, name
, namelen
) + namelen
;
2231 p
= memcpy(p
, val
, vallen
) + vallen
;
2234 setvareq(nameeq
, flags
| VNOSAVE
);
2238 static void FAST_FUNC
2239 setvar2(const char *name
, const char *val
)
2241 setvar(name
, val
, 0);
2244 #if ENABLE_ASH_GETOPTS
2246 * Safe version of setvar, returns 1 on success 0 on failure.
2249 setvarsafe(const char *name
, const char *val
, int flags
)
2252 volatile int saveint
;
2253 struct jmploc
*volatile savehandler
= exception_handler
;
2254 struct jmploc jmploc
;
2257 if (setjmp(jmploc
.loc
))
2260 exception_handler
= &jmploc
;
2261 setvar(name
, val
, flags
);
2264 exception_handler
= savehandler
;
2265 RESTORE_INT(saveint
);
2271 * Unset the specified variable.
2274 unsetvar(const char *s
)
2280 vpp
= findvar(hashvar(s
), s
);
2284 int flags
= vp
->flags
;
2287 if (flags
& VREADONLY
)
2289 #if ENABLE_ASH_RANDOM_SUPPORT
2290 vp
->flags
&= ~VDYNAMIC
;
2294 if ((flags
& VSTRFIXED
) == 0) {
2296 if ((flags
& (VTEXTFIXED
|VSTACK
)) == 0)
2297 free((char*)vp
->var_text
);
2303 vp
->flags
&= ~VEXPORT
;
2313 * Process a linked list of variable assignments.
2316 listsetvar(struct strlist
*list_set_var
, int flags
)
2318 struct strlist
*lp
= list_set_var
;
2324 setvareq(lp
->text
, flags
);
2331 * Generate a list of variables satisfying the given conditions.
2334 listvars(int on
, int off
, char ***end
)
2345 for (vp
= *vpp
; vp
; vp
= vp
->next
) {
2346 if ((vp
->flags
& mask
) == on
) {
2347 if (ep
== stackstrend())
2348 ep
= growstackstr();
2349 *ep
++ = (char*)vp
->var_text
;
2352 } while (++vpp
< vartab
+ VTABSIZE
);
2353 if (ep
== stackstrend())
2354 ep
= growstackstr();
2358 return grabstackstr(ep
);
2362 /* ============ Path search helper
2364 * The variable path (passed by reference) should be set to the start
2365 * of the path before the first call; path_advance will update
2366 * this value as it proceeds. Successive calls to path_advance will return
2367 * the possible path expansions in sequence. If an option (indicated by
2368 * a percent sign) appears in the path entry then the global variable
2369 * pathopt will be set to point to it; otherwise pathopt will be set to
2372 static const char *pathopt
; /* set by path_advance */
2375 path_advance(const char **path
, const char *name
)
2385 for (p
= start
; *p
&& *p
!= ':' && *p
!= '%'; p
++)
2387 len
= p
- start
+ strlen(name
) + 2; /* "2" is for '/' and '\0' */
2388 while (stackblocksize() < len
)
2392 memcpy(q
, start
, p
- start
);
2400 while (*p
&& *p
!= ':')
2407 return stalloc(len
);
2411 /* ============ Prompt */
2413 static smallint doprompt
; /* if set, prompt the user */
2414 static smallint needprompt
; /* true if interactive and at start of line */
2416 #if ENABLE_FEATURE_EDITING
2417 static line_input_t
*line_input_state
;
2418 static const char *cmdedit_prompt
;
2420 putprompt(const char *s
)
2422 if (ENABLE_ASH_EXPAND_PRMT
) {
2423 free((char*)cmdedit_prompt
);
2424 cmdedit_prompt
= ckstrdup(s
);
2431 putprompt(const char *s
)
2437 #if ENABLE_ASH_EXPAND_PRMT
2438 /* expandstr() needs parsing machinery, so it is far away ahead... */
2439 static const char *expandstr(const char *ps
);
2441 #define expandstr(s) s
2445 setprompt_if(smallint do_set
, int whichprompt
)
2448 IF_ASH_EXPAND_PRMT(struct stackmark smark
;)
2455 switch (whichprompt
) {
2465 #if ENABLE_ASH_EXPAND_PRMT
2466 setstackmark(&smark
);
2467 stalloc(stackblocksize());
2469 putprompt(expandstr(prompt
));
2470 #if ENABLE_ASH_EXPAND_PRMT
2471 popstackmark(&smark
);
2476 /* ============ The cd and pwd commands */
2478 #define CD_PHYSICAL 1
2488 while ((i
= nextopt("LP")) != '\0') {
2490 flags
^= CD_PHYSICAL
;
2499 * Update curdir (the name of the current directory) in response to a
2503 updatepwd(const char *dir
)
2510 cdcomppath
= ststrdup(dir
);
2513 if (curdir
== nullstr
)
2515 new = stack_putstr(curdir
, new);
2517 new = makestrspace(strlen(dir
) + 2, new);
2518 lim
= (char *)stackblock() + 1;
2522 if (new > lim
&& *lim
== '/')
2527 if (dir
[1] == '/' && dir
[2] != '/') {
2533 p
= strtok(cdcomppath
, "/");
2537 if (p
[1] == '.' && p
[2] == '\0') {
2549 new = stack_putstr(p
, new);
2557 return stackblock();
2561 * Find out what the current directory is. If we already know the current
2562 * directory, this routine returns immediately.
2567 char *dir
= getcwd(NULL
, 0); /* huh, using glibc extension? */
2568 return dir
? dir
: nullstr
;
2572 setpwd(const char *val
, int setold
)
2576 oldcur
= dir
= curdir
;
2579 setvar("OLDPWD", oldcur
, VEXPORT
);
2582 if (physdir
!= nullstr
) {
2583 if (physdir
!= oldcur
)
2587 if (oldcur
== val
|| !val
) {
2593 dir
= ckstrdup(val
);
2594 if (oldcur
!= dir
&& oldcur
!= nullstr
) {
2599 setvar("PWD", dir
, VEXPORT
);
2602 static void hashcd(void);
2605 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2606 * know that the current directory has changed.
2609 docd(const char *dest
, int flags
)
2611 const char *dir
= NULL
;
2614 TRACE(("docd(\"%s\", %d) called\n", dest
, flags
));
2617 if (!(flags
& CD_PHYSICAL
)) {
2618 dir
= updatepwd(dest
);
2632 static int FAST_FUNC
2633 cdcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
2645 dest
= bltinlookup("HOME");
2646 else if (LONE_DASH(dest
)) {
2647 dest
= bltinlookup("OLDPWD");
2669 path
= bltinlookup("CDPATH");
2678 p
= path_advance(&path
, dest
);
2679 if (stat(p
, &statb
) >= 0 && S_ISDIR(statb
.st_mode
)) {
2683 if (!docd(p
, flags
))
2688 ash_msg_and_raise_error("can't cd to %s", dest
);
2691 if (flags
& CD_PRINT
)
2692 out1fmt("%s\n", curdir
);
2696 static int FAST_FUNC
2697 pwdcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
2700 const char *dir
= curdir
;
2704 if (physdir
== nullstr
)
2708 out1fmt("%s\n", dir
);
2713 /* ============ ... */
2716 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2718 /* Syntax classes */
2719 #define CWORD 0 /* character is nothing special */
2720 #define CNL 1 /* newline character */
2721 #define CBACK 2 /* a backslash character */
2722 #define CSQUOTE 3 /* single quote */
2723 #define CDQUOTE 4 /* double quote */
2724 #define CENDQUOTE 5 /* a terminating quote */
2725 #define CBQUOTE 6 /* backwards single quote */
2726 #define CVAR 7 /* a dollar sign */
2727 #define CENDVAR 8 /* a '}' character */
2728 #define CLP 9 /* a left paren in arithmetic */
2729 #define CRP 10 /* a right paren in arithmetic */
2730 #define CENDFILE 11 /* end of file */
2731 #define CCTL 12 /* like CWORD, except it must be escaped */
2732 #define CSPCL 13 /* these terminate a word */
2733 #define CIGN 14 /* character should be ignored */
2736 #if ENABLE_ASH_ALIAS
2740 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2742 #if ENABLE_SH_MATH_SUPPORT
2743 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2745 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2747 static const uint16_t S_I_T
[] = {
2748 #if ENABLE_ASH_ALIAS
2749 SIT_ITEM(CSPCL
, CIGN
, CIGN
, CIGN
), /* 0, PEOA */
2751 SIT_ITEM(CSPCL
, CWORD
, CWORD
, CWORD
), /* 1, ' ' */
2752 SIT_ITEM(CNL
, CNL
, CNL
, CNL
), /* 2, \n */
2753 SIT_ITEM(CWORD
, CCTL
, CCTL
, CWORD
), /* 3, !*-/:=?[]~ */
2754 SIT_ITEM(CDQUOTE
, CENDQUOTE
, CWORD
, CWORD
), /* 4, '"' */
2755 SIT_ITEM(CVAR
, CVAR
, CWORD
, CVAR
), /* 5, $ */
2756 SIT_ITEM(CSQUOTE
, CWORD
, CENDQUOTE
, CWORD
), /* 6, "'" */
2757 SIT_ITEM(CSPCL
, CWORD
, CWORD
, CLP
), /* 7, ( */
2758 SIT_ITEM(CSPCL
, CWORD
, CWORD
, CRP
), /* 8, ) */
2759 SIT_ITEM(CBACK
, CBACK
, CCTL
, CBACK
), /* 9, \ */
2760 SIT_ITEM(CBQUOTE
, CBQUOTE
, CWORD
, CBQUOTE
), /* 10, ` */
2761 SIT_ITEM(CENDVAR
, CENDVAR
, CWORD
, CENDVAR
), /* 11, } */
2762 #if !USE_SIT_FUNCTION
2763 SIT_ITEM(CENDFILE
, CENDFILE
, CENDFILE
, CENDFILE
),/* 12, PEOF */
2764 SIT_ITEM(CWORD
, CWORD
, CWORD
, CWORD
), /* 13, 0-9A-Za-z */
2765 SIT_ITEM(CCTL
, CCTL
, CCTL
, CCTL
) /* 14, CTLESC ... */
2769 /* Constants below must match table above */
2771 #if ENABLE_ASH_ALIAS
2772 CSPCL_CIGN_CIGN_CIGN
, /* 0 */
2774 CSPCL_CWORD_CWORD_CWORD
, /* 1 */
2775 CNL_CNL_CNL_CNL
, /* 2 */
2776 CWORD_CCTL_CCTL_CWORD
, /* 3 */
2777 CDQUOTE_CENDQUOTE_CWORD_CWORD
, /* 4 */
2778 CVAR_CVAR_CWORD_CVAR
, /* 5 */
2779 CSQUOTE_CWORD_CENDQUOTE_CWORD
, /* 6 */
2780 CSPCL_CWORD_CWORD_CLP
, /* 7 */
2781 CSPCL_CWORD_CWORD_CRP
, /* 8 */
2782 CBACK_CBACK_CCTL_CBACK
, /* 9 */
2783 CBQUOTE_CBQUOTE_CWORD_CBQUOTE
, /* 10 */
2784 CENDVAR_CENDVAR_CWORD_CENDVAR
, /* 11 */
2785 CENDFILE_CENDFILE_CENDFILE_CENDFILE
, /* 12 */
2786 CWORD_CWORD_CWORD_CWORD
, /* 13 */
2787 CCTL_CCTL_CCTL_CCTL
, /* 14 */
2790 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2791 * caller must ensure proper cast on it if c is *char_ptr!
2793 /* Values for syntax param */
2794 #define BASESYNTAX 0 /* not in quotes */
2795 #define DQSYNTAX 1 /* in double quotes */
2796 #define SQSYNTAX 2 /* in single quotes */
2797 #define ARISYNTAX 3 /* in arithmetic */
2798 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2800 #if USE_SIT_FUNCTION
2803 SIT(int c
, int syntax
)
2805 static const char spec_symbls
[] ALIGN1
= "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2806 # if ENABLE_ASH_ALIAS
2807 static const uint8_t syntax_index_table
[] ALIGN1
= {
2808 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2809 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2810 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2814 static const uint8_t syntax_index_table
[] ALIGN1
= {
2815 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2816 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2817 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2826 # if ENABLE_ASH_ALIAS
2832 /* Cast is purely for paranoia here,
2833 * just in case someone passed signed char to us */
2834 if ((unsigned char)c
>= CTL_FIRST
2835 && (unsigned char)c
<= CTL_LAST
2839 s
= strchrnul(spec_symbls
, c
);
2842 indx
= syntax_index_table
[s
- spec_symbls
];
2844 return (S_I_T
[indx
] >> (syntax
*4)) & 0xf;
2847 #else /* !USE_SIT_FUNCTION */
2849 static const uint8_t syntax_index_table
[] = {
2850 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2851 /* 0 */ CWORD_CWORD_CWORD_CWORD
,
2852 /* 1 */ CWORD_CWORD_CWORD_CWORD
,
2853 /* 2 */ CWORD_CWORD_CWORD_CWORD
,
2854 /* 3 */ CWORD_CWORD_CWORD_CWORD
,
2855 /* 4 */ CWORD_CWORD_CWORD_CWORD
,
2856 /* 5 */ CWORD_CWORD_CWORD_CWORD
,
2857 /* 6 */ CWORD_CWORD_CWORD_CWORD
,
2858 /* 7 */ CWORD_CWORD_CWORD_CWORD
,
2859 /* 8 */ CWORD_CWORD_CWORD_CWORD
,
2860 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD
,
2861 /* 10 "\n" */ CNL_CNL_CNL_CNL
,
2862 /* 11 */ CWORD_CWORD_CWORD_CWORD
,
2863 /* 12 */ CWORD_CWORD_CWORD_CWORD
,
2864 /* 13 */ CWORD_CWORD_CWORD_CWORD
,
2865 /* 14 */ CWORD_CWORD_CWORD_CWORD
,
2866 /* 15 */ CWORD_CWORD_CWORD_CWORD
,
2867 /* 16 */ CWORD_CWORD_CWORD_CWORD
,
2868 /* 17 */ CWORD_CWORD_CWORD_CWORD
,
2869 /* 18 */ CWORD_CWORD_CWORD_CWORD
,
2870 /* 19 */ CWORD_CWORD_CWORD_CWORD
,
2871 /* 20 */ CWORD_CWORD_CWORD_CWORD
,
2872 /* 21 */ CWORD_CWORD_CWORD_CWORD
,
2873 /* 22 */ CWORD_CWORD_CWORD_CWORD
,
2874 /* 23 */ CWORD_CWORD_CWORD_CWORD
,
2875 /* 24 */ CWORD_CWORD_CWORD_CWORD
,
2876 /* 25 */ CWORD_CWORD_CWORD_CWORD
,
2877 /* 26 */ CWORD_CWORD_CWORD_CWORD
,
2878 /* 27 */ CWORD_CWORD_CWORD_CWORD
,
2879 /* 28 */ CWORD_CWORD_CWORD_CWORD
,
2880 /* 29 */ CWORD_CWORD_CWORD_CWORD
,
2881 /* 30 */ CWORD_CWORD_CWORD_CWORD
,
2882 /* 31 */ CWORD_CWORD_CWORD_CWORD
,
2883 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD
,
2884 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD
,
2885 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD
,
2886 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD
,
2887 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR
,
2888 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD
,
2889 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD
,
2890 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD
,
2891 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP
,
2892 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP
,
2893 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD
,
2894 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD
,
2895 /* 44 "," */ CWORD_CWORD_CWORD_CWORD
,
2896 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD
,
2897 /* 46 "." */ CWORD_CWORD_CWORD_CWORD
,
2898 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD
,
2899 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD
,
2900 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD
,
2901 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD
,
2902 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD
,
2903 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD
,
2904 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD
,
2905 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD
,
2906 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD
,
2907 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD
,
2908 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD
,
2909 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD
,
2910 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD
,
2911 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD
,
2912 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD
,
2913 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD
,
2914 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD
,
2915 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD
,
2916 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD
,
2917 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD
,
2918 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD
,
2919 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD
,
2920 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD
,
2921 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD
,
2922 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD
,
2923 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD
,
2924 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD
,
2925 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD
,
2926 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD
,
2927 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD
,
2928 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD
,
2929 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD
,
2930 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD
,
2931 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD
,
2932 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD
,
2933 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD
,
2934 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD
,
2935 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD
,
2936 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD
,
2937 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD
,
2938 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD
,
2939 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD
,
2940 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD
,
2941 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD
,
2942 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD
,
2943 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK
,
2944 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD
,
2945 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD
,
2946 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD
,
2947 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE
,
2948 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD
,
2949 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD
,
2950 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD
,
2951 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD
,
2952 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD
,
2953 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD
,
2954 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD
,
2955 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD
,
2956 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD
,
2957 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD
,
2958 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD
,
2959 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD
,
2960 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD
,
2961 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD
,
2962 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD
,
2963 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD
,
2964 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD
,
2965 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD
,
2966 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD
,
2967 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD
,
2968 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD
,
2969 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD
,
2970 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD
,
2971 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD
,
2972 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD
,
2973 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD
,
2974 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD
,
2975 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD
,
2976 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR
,
2977 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD
,
2978 /* 127 del */ CWORD_CWORD_CWORD_CWORD
,
2979 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD
,
2980 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL
,
2981 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL
,
2982 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL
,
2983 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL
,
2984 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL
,
2985 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL
,
2986 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL
,
2987 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL
,
2988 /* 137 */ CWORD_CWORD_CWORD_CWORD
,
2989 /* 138 */ CWORD_CWORD_CWORD_CWORD
,
2990 /* 139 */ CWORD_CWORD_CWORD_CWORD
,
2991 /* 140 */ CWORD_CWORD_CWORD_CWORD
,
2992 /* 141 */ CWORD_CWORD_CWORD_CWORD
,
2993 /* 142 */ CWORD_CWORD_CWORD_CWORD
,
2994 /* 143 */ CWORD_CWORD_CWORD_CWORD
,
2995 /* 144 */ CWORD_CWORD_CWORD_CWORD
,
2996 /* 145 */ CWORD_CWORD_CWORD_CWORD
,
2997 /* 146 */ CWORD_CWORD_CWORD_CWORD
,
2998 /* 147 */ CWORD_CWORD_CWORD_CWORD
,
2999 /* 148 */ CWORD_CWORD_CWORD_CWORD
,
3000 /* 149 */ CWORD_CWORD_CWORD_CWORD
,
3001 /* 150 */ CWORD_CWORD_CWORD_CWORD
,
3002 /* 151 */ CWORD_CWORD_CWORD_CWORD
,
3003 /* 152 */ CWORD_CWORD_CWORD_CWORD
,
3004 /* 153 */ CWORD_CWORD_CWORD_CWORD
,
3005 /* 154 */ CWORD_CWORD_CWORD_CWORD
,
3006 /* 155 */ CWORD_CWORD_CWORD_CWORD
,
3007 /* 156 */ CWORD_CWORD_CWORD_CWORD
,
3008 /* 157 */ CWORD_CWORD_CWORD_CWORD
,
3009 /* 158 */ CWORD_CWORD_CWORD_CWORD
,
3010 /* 159 */ CWORD_CWORD_CWORD_CWORD
,
3011 /* 160 */ CWORD_CWORD_CWORD_CWORD
,
3012 /* 161 */ CWORD_CWORD_CWORD_CWORD
,
3013 /* 162 */ CWORD_CWORD_CWORD_CWORD
,
3014 /* 163 */ CWORD_CWORD_CWORD_CWORD
,
3015 /* 164 */ CWORD_CWORD_CWORD_CWORD
,
3016 /* 165 */ CWORD_CWORD_CWORD_CWORD
,
3017 /* 166 */ CWORD_CWORD_CWORD_CWORD
,
3018 /* 167 */ CWORD_CWORD_CWORD_CWORD
,
3019 /* 168 */ CWORD_CWORD_CWORD_CWORD
,
3020 /* 169 */ CWORD_CWORD_CWORD_CWORD
,
3021 /* 170 */ CWORD_CWORD_CWORD_CWORD
,
3022 /* 171 */ CWORD_CWORD_CWORD_CWORD
,
3023 /* 172 */ CWORD_CWORD_CWORD_CWORD
,
3024 /* 173 */ CWORD_CWORD_CWORD_CWORD
,
3025 /* 174 */ CWORD_CWORD_CWORD_CWORD
,
3026 /* 175 */ CWORD_CWORD_CWORD_CWORD
,
3027 /* 176 */ CWORD_CWORD_CWORD_CWORD
,
3028 /* 177 */ CWORD_CWORD_CWORD_CWORD
,
3029 /* 178 */ CWORD_CWORD_CWORD_CWORD
,
3030 /* 179 */ CWORD_CWORD_CWORD_CWORD
,
3031 /* 180 */ CWORD_CWORD_CWORD_CWORD
,
3032 /* 181 */ CWORD_CWORD_CWORD_CWORD
,
3033 /* 182 */ CWORD_CWORD_CWORD_CWORD
,
3034 /* 183 */ CWORD_CWORD_CWORD_CWORD
,
3035 /* 184 */ CWORD_CWORD_CWORD_CWORD
,
3036 /* 185 */ CWORD_CWORD_CWORD_CWORD
,
3037 /* 186 */ CWORD_CWORD_CWORD_CWORD
,
3038 /* 187 */ CWORD_CWORD_CWORD_CWORD
,
3039 /* 188 */ CWORD_CWORD_CWORD_CWORD
,
3040 /* 189 */ CWORD_CWORD_CWORD_CWORD
,
3041 /* 190 */ CWORD_CWORD_CWORD_CWORD
,
3042 /* 191 */ CWORD_CWORD_CWORD_CWORD
,
3043 /* 192 */ CWORD_CWORD_CWORD_CWORD
,
3044 /* 193 */ CWORD_CWORD_CWORD_CWORD
,
3045 /* 194 */ CWORD_CWORD_CWORD_CWORD
,
3046 /* 195 */ CWORD_CWORD_CWORD_CWORD
,
3047 /* 196 */ CWORD_CWORD_CWORD_CWORD
,
3048 /* 197 */ CWORD_CWORD_CWORD_CWORD
,
3049 /* 198 */ CWORD_CWORD_CWORD_CWORD
,
3050 /* 199 */ CWORD_CWORD_CWORD_CWORD
,
3051 /* 200 */ CWORD_CWORD_CWORD_CWORD
,
3052 /* 201 */ CWORD_CWORD_CWORD_CWORD
,
3053 /* 202 */ CWORD_CWORD_CWORD_CWORD
,
3054 /* 203 */ CWORD_CWORD_CWORD_CWORD
,
3055 /* 204 */ CWORD_CWORD_CWORD_CWORD
,
3056 /* 205 */ CWORD_CWORD_CWORD_CWORD
,
3057 /* 206 */ CWORD_CWORD_CWORD_CWORD
,
3058 /* 207 */ CWORD_CWORD_CWORD_CWORD
,
3059 /* 208 */ CWORD_CWORD_CWORD_CWORD
,
3060 /* 209 */ CWORD_CWORD_CWORD_CWORD
,
3061 /* 210 */ CWORD_CWORD_CWORD_CWORD
,
3062 /* 211 */ CWORD_CWORD_CWORD_CWORD
,
3063 /* 212 */ CWORD_CWORD_CWORD_CWORD
,
3064 /* 213 */ CWORD_CWORD_CWORD_CWORD
,
3065 /* 214 */ CWORD_CWORD_CWORD_CWORD
,
3066 /* 215 */ CWORD_CWORD_CWORD_CWORD
,
3067 /* 216 */ CWORD_CWORD_CWORD_CWORD
,
3068 /* 217 */ CWORD_CWORD_CWORD_CWORD
,
3069 /* 218 */ CWORD_CWORD_CWORD_CWORD
,
3070 /* 219 */ CWORD_CWORD_CWORD_CWORD
,
3071 /* 220 */ CWORD_CWORD_CWORD_CWORD
,
3072 /* 221 */ CWORD_CWORD_CWORD_CWORD
,
3073 /* 222 */ CWORD_CWORD_CWORD_CWORD
,
3074 /* 223 */ CWORD_CWORD_CWORD_CWORD
,
3075 /* 224 */ CWORD_CWORD_CWORD_CWORD
,
3076 /* 225 */ CWORD_CWORD_CWORD_CWORD
,
3077 /* 226 */ CWORD_CWORD_CWORD_CWORD
,
3078 /* 227 */ CWORD_CWORD_CWORD_CWORD
,
3079 /* 228 */ CWORD_CWORD_CWORD_CWORD
,
3080 /* 229 */ CWORD_CWORD_CWORD_CWORD
,
3081 /* 230 */ CWORD_CWORD_CWORD_CWORD
,
3082 /* 231 */ CWORD_CWORD_CWORD_CWORD
,
3083 /* 232 */ CWORD_CWORD_CWORD_CWORD
,
3084 /* 233 */ CWORD_CWORD_CWORD_CWORD
,
3085 /* 234 */ CWORD_CWORD_CWORD_CWORD
,
3086 /* 235 */ CWORD_CWORD_CWORD_CWORD
,
3087 /* 236 */ CWORD_CWORD_CWORD_CWORD
,
3088 /* 237 */ CWORD_CWORD_CWORD_CWORD
,
3089 /* 238 */ CWORD_CWORD_CWORD_CWORD
,
3090 /* 239 */ CWORD_CWORD_CWORD_CWORD
,
3091 /* 230 */ CWORD_CWORD_CWORD_CWORD
,
3092 /* 241 */ CWORD_CWORD_CWORD_CWORD
,
3093 /* 242 */ CWORD_CWORD_CWORD_CWORD
,
3094 /* 243 */ CWORD_CWORD_CWORD_CWORD
,
3095 /* 244 */ CWORD_CWORD_CWORD_CWORD
,
3096 /* 245 */ CWORD_CWORD_CWORD_CWORD
,
3097 /* 246 */ CWORD_CWORD_CWORD_CWORD
,
3098 /* 247 */ CWORD_CWORD_CWORD_CWORD
,
3099 /* 248 */ CWORD_CWORD_CWORD_CWORD
,
3100 /* 249 */ CWORD_CWORD_CWORD_CWORD
,
3101 /* 250 */ CWORD_CWORD_CWORD_CWORD
,
3102 /* 251 */ CWORD_CWORD_CWORD_CWORD
,
3103 /* 252 */ CWORD_CWORD_CWORD_CWORD
,
3104 /* 253 */ CWORD_CWORD_CWORD_CWORD
,
3105 /* 254 */ CWORD_CWORD_CWORD_CWORD
,
3106 /* 255 */ CWORD_CWORD_CWORD_CWORD
,
3107 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE
,
3108 # if ENABLE_ASH_ALIAS
3109 /* PEOA */ CSPCL_CIGN_CIGN_CIGN
,
3113 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3115 #endif /* !USE_SIT_FUNCTION */
3118 /* ============ Alias handling */
3120 #if ENABLE_ASH_ALIAS
3122 #define ALIASINUSE 1
3133 static struct alias
**atab
; // [ATABSIZE];
3134 #define INIT_G_alias() do { \
3135 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3139 static struct alias
**
3140 __lookupalias(const char *name
) {
3141 unsigned int hashval
;
3148 ch
= (unsigned char)*p
;
3152 ch
= (unsigned char)*++p
;
3154 app
= &atab
[hashval
% ATABSIZE
];
3156 for (; *app
; app
= &(*app
)->next
) {
3157 if (strcmp(name
, (*app
)->name
) == 0) {
3165 static struct alias
*
3166 lookupalias(const char *name
, int check
)
3168 struct alias
*ap
= *__lookupalias(name
);
3170 if (check
&& ap
&& (ap
->flag
& ALIASINUSE
))
3175 static struct alias
*
3176 freealias(struct alias
*ap
)
3180 if (ap
->flag
& ALIASINUSE
) {
3181 ap
->flag
|= ALIASDEAD
;
3193 setalias(const char *name
, const char *val
)
3195 struct alias
*ap
, **app
;
3197 app
= __lookupalias(name
);
3201 if (!(ap
->flag
& ALIASINUSE
)) {
3204 ap
->val
= ckstrdup(val
);
3205 ap
->flag
&= ~ALIASDEAD
;
3208 ap
= ckzalloc(sizeof(struct alias
));
3209 ap
->name
= ckstrdup(name
);
3210 ap
->val
= ckstrdup(val
);
3211 /*ap->flag = 0; - ckzalloc did it */
3212 /*ap->next = NULL;*/
3219 unalias(const char *name
)
3223 app
= __lookupalias(name
);
3227 *app
= freealias(*app
);
3238 struct alias
*ap
, **app
;
3242 for (i
= 0; i
< ATABSIZE
; i
++) {
3244 for (ap
= *app
; ap
; ap
= *app
) {
3245 *app
= freealias(*app
);
3255 printalias(const struct alias
*ap
)
3257 out1fmt("%s=%s\n", ap
->name
, single_quote(ap
->val
));
3261 * TODO - sort output
3263 static int FAST_FUNC
3264 aliascmd(int argc UNUSED_PARAM
, char **argv
)
3273 for (i
= 0; i
< ATABSIZE
; i
++) {
3274 for (ap
= atab
[i
]; ap
; ap
= ap
->next
) {
3280 while ((n
= *++argv
) != NULL
) {
3281 v
= strchr(n
+1, '=');
3282 if (v
== NULL
) { /* n+1: funny ksh stuff */
3283 ap
= *__lookupalias(n
);
3285 fprintf(stderr
, "%s: %s not found\n", "alias", n
);
3298 static int FAST_FUNC
3299 unaliascmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
3303 while ((i
= nextopt("a")) != '\0') {
3309 for (i
= 0; *argptr
; argptr
++) {
3310 if (unalias(*argptr
)) {
3311 fprintf(stderr
, "%s: %s not found\n", "unalias", *argptr
);
3319 #endif /* ASH_ALIAS */
3322 /* ============ jobs.c */
3324 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3327 #define FORK_NOJOB 2
3329 /* mode flags for showjob(s) */
3330 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3331 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3332 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3335 * A job structure contains information about a job. A job is either a
3336 * single process or a set of processes contained in a pipeline. In the
3337 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3341 pid_t ps_pid
; /* process id */
3342 int ps_status
; /* last process status from wait() */
3343 char *ps_cmd
; /* text of command being run */
3347 struct procstat ps0
; /* status of process */
3348 struct procstat
*ps
; /* status or processes when more than one */
3350 int stopstatus
; /* status of a stopped job */
3353 nprocs
: 16, /* number of processes */
3355 #define JOBRUNNING 0 /* at least one proc running */
3356 #define JOBSTOPPED 1 /* all procs are stopped */
3357 #define JOBDONE 2 /* all procs are completed */
3359 sigint
: 1, /* job was killed by SIGINT */
3360 jobctl
: 1, /* job running under job control */
3362 waited
: 1, /* true if this entry has been waited for */
3363 used
: 1, /* true if this entry is in used */
3364 changed
: 1; /* true if status has changed */
3365 struct job
*prev_job
; /* previous job */
3368 static struct job
*makejob(/*union node *,*/ int);
3369 static int forkshell(struct job
*, union node
*, int);
3370 static int waitforjob(struct job
*);
3373 enum { doing_jobctl
= 0 };
3374 #define setjobctl(on) do {} while (0)
3376 static smallint doing_jobctl
; //references:8
3377 static void setjobctl(int);
3384 ignoresig(int signo
)
3386 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3387 if (sigmode
[signo
- 1] != S_IGN
&& sigmode
[signo
- 1] != S_HARD_IGN
) {
3388 /* No, need to do it */
3389 signal(signo
, SIG_IGN
);
3391 sigmode
[signo
- 1] = S_HARD_IGN
;
3395 * Only one usage site - in setsignal()
3398 signal_handler(int signo
)
3400 gotsig
[signo
- 1] = 1;
3402 if (signo
== SIGINT
&& !trap
[SIGINT
]) {
3403 if (!suppress_int
) {
3405 raise_interrupt(); /* does not return */
3409 pending_sig
= signo
;
3414 * Set the signal handler for the specified signal. The routine figures
3415 * out what it should be set to.
3418 setsignal(int signo
)
3421 char cur_act
, new_act
;
3422 struct sigaction act
;
3426 if (t
!= NULL
) { /* trap for this sig is set */
3428 if (t
[0] == '\0') /* trap is "": ignore this sig */
3432 if (rootshell
&& new_act
== S_DFL
) {
3435 if (iflag
|| minusc
|| sflag
== 0)
3444 * "In all cases, bash ignores SIGQUIT. Non-builtin
3445 * commands run by bash have signal handlers
3446 * set to the values inherited by the shell
3447 * from its parent". */
3463 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3464 //whereas we have to restore it to what shell got on entry
3465 //from the parent. See comment above
3467 t
= &sigmode
[signo
- 1];
3470 /* current setting is not yet known */
3471 if (sigaction(signo
, NULL
, &act
)) {
3472 /* pretend it worked; maybe we should give a warning,
3473 * but other shells don't. We don't alter sigmode,
3474 * so we retry every time.
3475 * btw, in Linux it never fails. --vda */
3478 if (act
.sa_handler
== SIG_IGN
) {
3479 cur_act
= S_HARD_IGN
;
3481 && (signo
== SIGTSTP
|| signo
== SIGTTIN
|| signo
== SIGTTOU
)
3483 cur_act
= S_IGN
; /* don't hard ignore these */
3487 if (cur_act
== S_HARD_IGN
|| cur_act
== new_act
)
3490 act
.sa_handler
= SIG_DFL
;
3493 act
.sa_handler
= signal_handler
;
3496 act
.sa_handler
= SIG_IGN
;
3500 /* flags and mask matter only if !DFL and !IGN, but we do it
3501 * for all cases for more deterministic behavior:
3504 sigfillset(&act
.sa_mask
);
3506 sigaction_set(signo
, &act
);
3511 /* mode flags for set_curjob */
3512 #define CUR_DELETE 2
3513 #define CUR_RUNNING 1
3514 #define CUR_STOPPED 0
3516 /* mode flags for dowait */
3517 #define DOWAIT_NONBLOCK WNOHANG
3518 #define DOWAIT_BLOCK 0
3521 /* pgrp of shell on invocation */
3522 static int initialpgrp
; //references:2
3523 static int ttyfd
= -1; //5
3526 static struct job
*jobtab
; //5
3528 static unsigned njobs
; //4
3530 static struct job
*curjob
; //lots
3531 /* number of presumed living untracked jobs */
3532 static int jobless
; //4
3535 set_curjob(struct job
*jp
, unsigned mode
)
3538 struct job
**jpp
, **curp
;
3540 /* first remove from list */
3541 jpp
= curp
= &curjob
;
3546 jpp
= &jp1
->prev_job
;
3548 *jpp
= jp1
->prev_job
;
3550 /* Then re-insert in correct position */
3558 /* job being deleted */
3561 /* newly created job or backgrounded job,
3562 put after all stopped jobs. */
3566 if (!jp1
|| jp1
->state
!= JOBSTOPPED
)
3569 jpp
= &jp1
->prev_job
;
3575 /* newly stopped job - becomes curjob */
3576 jp
->prev_job
= *jpp
;
3584 jobno(const struct job
*jp
)
3586 return jp
- jobtab
+ 1;
3591 * Convert a job name to a job structure.
3594 #define getjob(name, getctl) getjob(name)
3597 getjob(const char *name
, int getctl
)
3601 const char *err_msg
= "%s: no such job";
3605 char *(*match
)(const char *, const char *);
3620 if (c
== '+' || c
== '%') {
3622 err_msg
= "No current job";
3628 err_msg
= "No previous job";
3639 jp
= jobtab
+ num
- 1;
3654 if (match(jp
->ps
[0].ps_cmd
, p
)) {
3658 err_msg
= "%s: ambiguous";
3668 err_msg
= "job %s not created under job control";
3669 if (getctl
&& jp
->jobctl
== 0)
3674 ash_msg_and_raise_error(err_msg
, name
);
3678 * Mark a job structure as unused.
3681 freejob(struct job
*jp
)
3683 struct procstat
*ps
;
3687 for (i
= jp
->nprocs
, ps
= jp
->ps
; --i
>= 0; ps
++) {
3688 if (ps
->ps_cmd
!= nullstr
)
3691 if (jp
->ps
!= &jp
->ps0
)
3694 set_curjob(jp
, CUR_DELETE
);
3700 xtcsetpgrp(int fd
, pid_t pgrp
)
3702 if (tcsetpgrp(fd
, pgrp
))
3703 ash_msg_and_raise_error("can't set tty process group (%m)");
3707 * Turn job control on and off.
3709 * Note: This code assumes that the third arg to ioctl is a character
3710 * pointer, which is true on Berkeley systems but not System V. Since
3711 * System V doesn't have job control yet, this isn't a problem now.
3713 * Called with interrupts off.
3721 if (on
== doing_jobctl
|| rootshell
== 0)
3725 ofd
= fd
= open(_PATH_TTY
, O_RDWR
);
3727 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3728 * That sometimes helps to acquire controlling tty.
3729 * Obviously, a workaround for bugs when someone
3730 * failed to provide a controlling tty to bash! :) */
3736 fd
= fcntl(fd
, F_DUPFD
, 10);
3741 /* fd is a tty at this point */
3742 close_on_exec_on(fd
);
3743 while (1) { /* while we are in the background */
3744 pgrp
= tcgetpgrp(fd
);
3747 ash_msg("can't access tty; job control turned off");
3751 if (pgrp
== getpgrp())
3762 xtcsetpgrp(fd
, pgrp
);
3764 /* turning job control off */
3767 /* was xtcsetpgrp, but this can make exiting ash
3768 * loop forever if pty is already deleted */
3769 tcsetpgrp(fd
, pgrp
);
3783 static int FAST_FUNC
3784 killcmd(int argc
, char **argv
)
3786 if (argv
[1] && strcmp(argv
[1], "-l") != 0) {
3789 if (argv
[i
][0] == '%') {
3791 * "kill %N" - job kill
3792 * Converting to pgrp / pid kill
3798 jp
= getjob(argv
[i
], 0);
3800 * In jobs started under job control, we signal
3801 * entire process group by kill -PGRP_ID.
3802 * This happens, f.e., in interactive shell.
3804 * Otherwise, we signal each child via
3805 * kill PID1 PID2 PID3.
3807 * sh -c 'sleep 1|sleep 1 & kill %1'
3808 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3809 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3811 n
= jp
->nprocs
; /* can't be 0 (I hope) */
3814 dst
= alloca(n
* sizeof(int)*4);
3816 for (j
= 0; j
< n
; j
++) {
3817 struct procstat
*ps
= &jp
->ps
[j
];
3818 /* Skip non-running and not-stopped members
3819 * (i.e. dead members) of the job
3821 if (ps
->ps_status
!= -1 && !WIFSTOPPED(ps
->ps_status
))
3824 * kill_main has matching code to expect
3825 * leading space. Needed to not confuse
3826 * negative pids with "kill -SIGNAL_NO" syntax
3828 dst
+= sprintf(dst
, jp
->jobctl
? " -%u" : " %u", (int)ps
->ps_pid
);
3832 } while (argv
[++i
]);
3834 return kill_main(argc
, argv
);
3838 showpipe(struct job
*jp
/*, FILE *out*/)
3840 struct procstat
*ps
;
3841 struct procstat
*psend
;
3843 psend
= jp
->ps
+ jp
->nprocs
;
3844 for (ps
= jp
->ps
+ 1; ps
< psend
; ps
++)
3845 printf(" | %s", ps
->ps_cmd
);
3846 outcslow('\n', stdout
);
3847 flush_stdout_stderr();
3852 restartjob(struct job
*jp
, int mode
)
3854 struct procstat
*ps
;
3860 if (jp
->state
== JOBDONE
)
3862 jp
->state
= JOBRUNNING
;
3863 pgid
= jp
->ps
[0].ps_pid
;
3864 if (mode
== FORK_FG
)
3865 xtcsetpgrp(ttyfd
, pgid
);
3866 killpg(pgid
, SIGCONT
);
3870 if (WIFSTOPPED(ps
->ps_status
)) {
3876 status
= (mode
== FORK_FG
) ? waitforjob(jp
) : 0;
3881 static int FAST_FUNC
3882 fg_bgcmd(int argc UNUSED_PARAM
, char **argv
)
3888 mode
= (**argv
== 'f') ? FORK_FG
: FORK_BG
;
3892 jp
= getjob(*argv
, 1);
3893 if (mode
== FORK_BG
) {
3894 set_curjob(jp
, CUR_RUNNING
);
3895 printf("[%d] ", jobno(jp
));
3897 out1str(jp
->ps
[0].ps_cmd
);
3898 showpipe(jp
/*, stdout*/);
3899 retval
= restartjob(jp
, mode
);
3900 } while (*argv
&& *++argv
);
3906 sprint_status(char *s
, int status
, int sigonly
)
3912 if (!WIFEXITED(status
)) {
3914 if (WIFSTOPPED(status
))
3915 st
= WSTOPSIG(status
);
3918 st
= WTERMSIG(status
);
3920 if (st
== SIGINT
|| st
== SIGPIPE
)
3923 if (WIFSTOPPED(status
))
3928 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
3929 col
= fmtstr(s
, 32, strsignal(st
));
3930 if (WCOREDUMP(status
)) {
3931 col
+= fmtstr(s
+ col
, 16, " (core dumped)");
3933 } else if (!sigonly
) {
3934 st
= WEXITSTATUS(status
);
3936 col
= fmtstr(s
, 16, "Done(%d)", st
);
3938 col
= fmtstr(s
, 16, "Done");
3945 dowait(int wait_flags
, struct job
*job
)
3950 struct job
*thisjob
;
3953 TRACE(("dowait(0x%x) called\n", wait_flags
));
3955 /* Do a wait system call. If job control is compiled in, we accept
3956 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3957 * NB: _not_ safe_waitpid, we need to detect EINTR */
3959 wait_flags
|= WUNTRACED
;
3960 pid
= waitpid(-1, &status
, wait_flags
);
3961 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3962 pid
, status
, errno
, strerror(errno
)));
3968 for (jp
= curjob
; jp
; jp
= jp
->prev_job
) {
3969 struct procstat
*ps
;
3970 struct procstat
*psend
;
3971 if (jp
->state
== JOBDONE
)
3975 psend
= ps
+ jp
->nprocs
;
3977 if (ps
->ps_pid
== pid
) {
3978 TRACE(("Job %d: changing status of proc %d "
3979 "from 0x%x to 0x%x\n",
3980 jobno(jp
), pid
, ps
->ps_status
, status
));
3981 ps
->ps_status
= status
;
3984 if (ps
->ps_status
== -1)
3987 if (state
== JOBRUNNING
)
3989 if (WIFSTOPPED(ps
->ps_status
)) {
3990 jp
->stopstatus
= ps
->ps_status
;
3994 } while (++ps
< psend
);
3999 if (!WIFSTOPPED(status
))
4005 if (state
!= JOBRUNNING
) {
4006 thisjob
->changed
= 1;
4008 if (thisjob
->state
!= state
) {
4009 TRACE(("Job %d: changing state from %d to %d\n",
4010 jobno(thisjob
), thisjob
->state
, state
));
4011 thisjob
->state
= state
;
4013 if (state
== JOBSTOPPED
) {
4014 set_curjob(thisjob
, CUR_STOPPED
);
4023 if (thisjob
&& thisjob
== job
) {
4027 len
= sprint_status(s
, status
, 1);
4038 blocking_wait_with_raise_on_sig(void)
4040 pid_t pid
= dowait(DOWAIT_BLOCK
, NULL
);
4041 if (pid
<= 0 && pending_sig
)
4042 raise_exception(EXSIG
);
4048 showjob(FILE *out
, struct job
*jp
, int mode
)
4050 struct procstat
*ps
;
4051 struct procstat
*psend
;
4058 if (mode
& SHOW_ONLY_PGID
) { /* jobs -p */
4059 /* just output process (group) id of pipeline */
4060 fprintf(out
, "%d\n", ps
->ps_pid
);
4064 col
= fmtstr(s
, 16, "[%d] ", jobno(jp
));
4069 else if (curjob
&& jp
== curjob
->prev_job
)
4072 if (mode
& SHOW_PIDS
)
4073 col
+= fmtstr(s
+ col
, 16, "%d ", ps
->ps_pid
);
4075 psend
= ps
+ jp
->nprocs
;
4077 if (jp
->state
== JOBRUNNING
) {
4078 strcpy(s
+ col
, "Running");
4079 col
+= sizeof("Running") - 1;
4081 int status
= psend
[-1].ps_status
;
4082 if (jp
->state
== JOBSTOPPED
)
4083 status
= jp
->stopstatus
;
4084 col
+= sprint_status(s
+ col
, status
, 0);
4086 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4088 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4089 * or prints several "PID | <cmdN>" lines,
4090 * depending on SHOW_PIDS bit.
4091 * We do not print status of individual processes
4092 * between PID and <cmdN>. bash does it, but not very well:
4093 * first line shows overall job status, not process status,
4094 * making it impossible to know 1st process status.
4098 /* for each process */
4101 if (mode
& SHOW_PIDS
)
4102 col
= fmtstr(s
, 48, "\n%*c%d ", indent_col
, ' ', ps
->ps_pid
) - 1;
4104 fprintf(out
, "%s%*c%s%s",
4106 33 - col
>= 0 ? 33 - col
: 0, ' ',
4107 ps
== jp
->ps
? "" : "| ",
4110 } while (++ps
!= psend
);
4111 outcslow('\n', out
);
4115 if (jp
->state
== JOBDONE
) {
4116 TRACE(("showjob: freeing job %d\n", jobno(jp
)));
4122 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4123 * statuses have changed since the last call to showjobs.
4126 showjobs(FILE *out
, int mode
)
4130 TRACE(("showjobs(0x%x) called\n", mode
));
4132 /* Handle all finished jobs */
4133 while (dowait(DOWAIT_NONBLOCK
, NULL
) > 0)
4136 for (jp
= curjob
; jp
; jp
= jp
->prev_job
) {
4137 if (!(mode
& SHOW_CHANGED
) || jp
->changed
) {
4138 showjob(out
, jp
, mode
);
4143 static int FAST_FUNC
4144 jobscmd(int argc UNUSED_PARAM
, char **argv
)
4149 while ((m
= nextopt("lp")) != '\0') {
4153 mode
|= SHOW_ONLY_PGID
;
4159 showjob(stdout
, getjob(*argv
, 0), mode
);
4162 showjobs(stdout
, mode
);
4169 /* Called only on finished or stopped jobs (no members are running) */
4171 getstatus(struct job
*job
)
4175 struct procstat
*ps
;
4177 /* Fetch last member's status */
4178 ps
= job
->ps
+ job
->nprocs
- 1;
4179 status
= ps
->ps_status
;
4181 /* "set -o pipefail" mode: use last _nonzero_ status */
4182 while (status
== 0 && --ps
>= job
->ps
)
4183 status
= ps
->ps_status
;
4186 retval
= WEXITSTATUS(status
);
4187 if (!WIFEXITED(status
)) {
4189 retval
= WSTOPSIG(status
);
4190 if (!WIFSTOPPED(status
))
4193 /* XXX: limits number of signals */
4194 retval
= WTERMSIG(status
);
4196 if (retval
== SIGINT
)
4202 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4203 jobno(job
), job
->nprocs
, status
, retval
));
4207 static int FAST_FUNC
4208 waitcmd(int argc UNUSED_PARAM
, char **argv
)
4215 raise_exception(EXSIG
);
4222 /* wait for all jobs */
4226 if (!jp
) /* no running procs */
4228 if (jp
->state
== JOBRUNNING
)
4233 blocking_wait_with_raise_on_sig();
4235 * "When bash is waiting for an asynchronous command via
4236 * the wait builtin, the reception of a signal for which a trap
4237 * has been set will cause the wait builtin to return immediately
4238 * with an exit status greater than 128, immediately after which
4239 * the trap is executed."
4241 * blocking_wait_with_raise_on_sig raises signal handlers
4242 * if it gets no pid (pid < 0). However,
4243 * if child sends us a signal *and immediately exits*,
4244 * blocking_wait_with_raise_on_sig gets pid > 0
4245 * and does not handle pending_sig. Check this case: */
4247 raise_exception(EXSIG
);
4253 if (**argv
!= '%') {
4254 pid_t pid
= number(*argv
);
4259 if (job
->ps
[job
->nprocs
- 1].ps_pid
== pid
)
4261 job
= job
->prev_job
;
4264 job
= getjob(*argv
, 0);
4266 /* loop until process terminated or stopped */
4267 while (job
->state
== JOBRUNNING
)
4268 blocking_wait_with_raise_on_sig();
4270 retval
= getstatus(job
);
4283 struct job
*jp
, *jq
;
4285 len
= njobs
* sizeof(*jp
);
4287 jp
= ckrealloc(jq
, len
+ 4 * sizeof(*jp
));
4289 offset
= (char *)jp
- (char *)jq
;
4291 /* Relocate pointers */
4294 jq
= (struct job
*)((char *)jq
+ l
);
4298 #define joff(p) ((struct job *)((char *)(p) + l))
4299 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4300 if (joff(jp
)->ps
== &jq
->ps0
)
4301 jmove(joff(jp
)->ps
);
4302 if (joff(jp
)->prev_job
)
4303 jmove(joff(jp
)->prev_job
);
4313 jp
= (struct job
*)((char *)jp
+ len
);
4317 } while (--jq
>= jp
);
4322 * Return a new job structure.
4323 * Called with interrupts off.
4326 makejob(/*union node *node,*/ int nprocs
)
4331 for (i
= njobs
, jp
= jobtab
; ; jp
++) {
4338 if (jp
->state
!= JOBDONE
|| !jp
->waited
)
4347 memset(jp
, 0, sizeof(*jp
));
4349 /* jp->jobctl is a bitfield.
4350 * "jp->jobctl |= jobctl" likely to give awful code */
4354 jp
->prev_job
= curjob
;
4359 jp
->ps
= ckmalloc(nprocs
* sizeof(struct procstat
));
4361 TRACE(("makejob(%d) returns %%%d\n", nprocs
,
4368 * Return a string identifying a command (to be printed by the
4371 static char *cmdnextc
;
4374 cmdputs(const char *s
)
4376 static const char vstype
[VSTYPE
+ 1][3] = {
4377 "", "}", "-", "+", "?", "=",
4378 "%", "%%", "#", "##"
4379 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4382 const char *p
, *str
;
4386 unsigned char subtype
= 0;
4390 nextc
= makestrspace((strlen(s
) + 1) * 8, cmdnextc
);
4392 while ((c
= *p
++) != '\0') {
4400 if ((subtype
& VSTYPE
) == VSLENGTH
)
4404 if (!(subtype
& VSQUOTE
) == !(quoted
& 1))
4410 str
= "\"}" + !(quoted
& 1);
4417 case CTLBACKQ
+CTLQUOTE
:
4420 #if ENABLE_SH_MATH_SUPPORT
4435 if ((subtype
& VSTYPE
) != VSNORMAL
)
4437 str
= vstype
[subtype
& VSTYPE
];
4438 if (subtype
& VSNUL
)
4447 /* These can only happen inside quotes */
4460 while ((c
= *str
++) != '\0') {
4463 } /* while *p++ not NUL */
4466 USTPUTC('"', nextc
);
4472 /* cmdtxt() and cmdlist() call each other */
4473 static void cmdtxt(union node
*n
);
4476 cmdlist(union node
*np
, int sep
)
4478 for (; np
; np
= np
->narg
.next
) {
4482 if (sep
&& np
->narg
.next
)
4488 cmdtxt(union node
*n
)
4491 struct nodelist
*lp
;
4502 lp
= n
->npipe
.cmdlist
;
4520 cmdtxt(n
->nbinary
.ch1
);
4536 cmdtxt(n
->nif
.test
);
4538 if (n
->nif
.elsepart
) {
4539 cmdtxt(n
->nif
.ifpart
);
4541 n
= n
->nif
.elsepart
;
4559 cmdtxt(n
->nbinary
.ch1
);
4569 cmdputs(n
->nfor
.var
);
4571 cmdlist(n
->nfor
.args
, 1);
4576 cmdputs(n
->narg
.text
);
4580 cmdlist(n
->ncmd
.args
, 1);
4581 cmdlist(n
->ncmd
.redirect
, 0);
4594 cmdputs(n
->ncase
.expr
->narg
.text
);
4596 for (np
= n
->ncase
.cases
; np
; np
= np
->nclist
.next
) {
4597 cmdtxt(np
->nclist
.pattern
);
4599 cmdtxt(np
->nclist
.body
);
4613 #if ENABLE_ASH_BASH_COMPAT
4628 cmdputs(utoa(n
->nfile
.fd
));
4630 if (n
->type
== NTOFD
|| n
->type
== NFROMFD
) {
4631 cmdputs(utoa(n
->ndup
.dupfd
));
4640 commandtext(union node
*n
)
4644 STARTSTACKSTR(cmdnextc
);
4646 name
= stackblock();
4647 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4648 name
, cmdnextc
, cmdnextc
));
4649 return ckstrdup(name
);
4654 * Fork off a subshell. If we are doing job control, give the subshell its
4655 * own process group. Jp is a job structure that the job is to be added to.
4656 * N is the command that will be evaluated by the child. Both jp and n may
4657 * be NULL. The mode parameter can be one of the following:
4658 * FORK_FG - Fork off a foreground process.
4659 * FORK_BG - Fork off a background process.
4660 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4661 * process group even if job control is on.
4663 * When job control is turned off, background processes have their standard
4664 * input redirected to /dev/null (except for the second and later processes
4667 * Called with interrupts off.
4670 * Clear traps on a fork.
4677 for (tp
= trap
; tp
< &trap
[NSIG
]; tp
++) {
4678 if (*tp
&& **tp
) { /* trap not NULL or "" (SIG_IGN) */
4680 if (trap_ptr
== trap
)
4682 /* else: it "belongs" to trap_ptr vector, don't free */
4684 if ((tp
- trap
) != 0)
4685 setsignal(tp
- trap
);
4692 /* Lives far away from here, needed for forkchild */
4693 static void closescript(void);
4695 /* Called after fork(), in child */
4696 static NOINLINE
void
4697 forkchild(struct job
*jp
, union node
*n
, int mode
)
4701 TRACE(("Child shell %d\n", getpid()));
4705 /* man bash: "Non-builtin commands run by bash have signal handlers
4706 * set to the values inherited by the shell from its parent".
4707 * Do we do it correctly? */
4711 if (mode
== FORK_NOJOB
/* is it `xxx` ? */
4712 && n
&& n
->type
== NCMD
/* is it single cmd? */
4713 /* && n->ncmd.args->type == NARG - always true? */
4714 && n
->ncmd
.args
&& strcmp(n
->ncmd
.args
->narg
.text
, "trap") == 0
4715 && n
->ncmd
.args
->narg
.next
== NULL
/* "trap" with no arguments */
4716 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4718 TRACE(("Trap hack\n"));
4719 /* Awful hack for `trap` or $(trap).
4721 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4722 * contains an example where "trap" is executed in a subshell:
4724 * save_traps=$(trap)
4726 * eval "$save_traps"
4728 * Standard does not say that "trap" in subshell shall print
4729 * parent shell's traps. It only says that its output
4730 * must have suitable form, but then, in the above example
4731 * (which is not supposed to be normative), it implies that.
4733 * bash (and probably other shell) does implement it
4734 * (traps are reset to defaults, but "trap" still shows them),
4735 * but as a result, "trap" logic is hopelessly messed up:
4738 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4739 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4740 * # true | trap <--- trap is in subshell - no output (ditto)
4741 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4742 * trap -- 'echo Ho' SIGWINCH
4743 * # echo `(trap)` <--- in subshell in subshell - output
4744 * trap -- 'echo Ho' SIGWINCH
4745 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4746 * trap -- 'echo Ho' SIGWINCH
4748 * The rules when to forget and when to not forget traps
4749 * get really complex and nonsensical.
4751 * Our solution: ONLY bare $(trap) or `trap` is special.
4753 /* Save trap handler strings for trap builtin to print */
4754 trap_ptr
= memcpy(xmalloc(sizeof(trap
)), trap
, sizeof(trap
));
4755 /* Fall through into clearing traps */
4759 /* do job control only in root shell */
4761 if (mode
!= FORK_NOJOB
&& jp
->jobctl
&& oldlvl
== 0) {
4764 if (jp
->nprocs
== 0)
4767 pgrp
= jp
->ps
[0].ps_pid
;
4768 /* this can fail because we are doing it in the parent also */
4770 if (mode
== FORK_FG
)
4771 xtcsetpgrp(ttyfd
, pgrp
);
4776 if (mode
== FORK_BG
) {
4777 /* man bash: "When job control is not in effect,
4778 * asynchronous commands ignore SIGINT and SIGQUIT" */
4781 if (jp
->nprocs
== 0) {
4783 if (open(bb_dev_null
, O_RDONLY
) != 0)
4784 ash_msg_and_raise_error("can't open '%s'", bb_dev_null
);
4788 if (iflag
) { /* why if iflag only? */
4793 * "In all cases, bash ignores SIGQUIT. Non-builtin
4794 * commands run by bash have signal handlers
4795 * set to the values inherited by the shell
4797 * Take care of the second rule: */
4801 if (n
&& n
->type
== NCMD
4802 && n
->ncmd
.args
&& strcmp(n
->ncmd
.args
->narg
.text
, "jobs") == 0
4804 TRACE(("Job hack\n"));
4805 /* "jobs": we do not want to clear job list for it,
4806 * instead we remove only _its_ own_ job from job list.
4807 * This makes "jobs .... | cat" more useful.
4813 for (jp
= curjob
; jp
; jp
= jp
->prev_job
)
4818 /* Called after fork(), in parent */
4820 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4823 forkparent(struct job
*jp
, union node
*n
, int mode
, pid_t pid
)
4825 TRACE(("In parent shell: child = %d\n", pid
));
4827 while (jobless
&& dowait(DOWAIT_NONBLOCK
, NULL
) > 0)
4833 if (mode
!= FORK_NOJOB
&& jp
->jobctl
) {
4836 if (jp
->nprocs
== 0)
4839 pgrp
= jp
->ps
[0].ps_pid
;
4840 /* This can fail because we are doing it in the child also */
4844 if (mode
== FORK_BG
) {
4845 backgndpid
= pid
; /* set $! */
4846 set_curjob(jp
, CUR_RUNNING
);
4849 struct procstat
*ps
= &jp
->ps
[jp
->nprocs
++];
4852 ps
->ps_cmd
= nullstr
;
4854 if (doing_jobctl
&& n
)
4855 ps
->ps_cmd
= commandtext(n
);
4861 forkshell(struct job
*jp
, union node
*n
, int mode
)
4865 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp
), n
, mode
));
4868 TRACE(("Fork failed, errno=%d", errno
));
4871 ash_msg_and_raise_error("can't fork");
4874 CLEAR_RANDOM_T(&random_gen
); /* or else $RANDOM repeats in child */
4875 forkchild(jp
, n
, mode
);
4877 forkparent(jp
, n
, mode
, pid
);
4883 * Wait for job to finish.
4885 * Under job control we have the problem that while a child process
4886 * is running interrupts generated by the user are sent to the child
4887 * but not to the shell. This means that an infinite loop started by
4888 * an interactive user may be hard to kill. With job control turned off,
4889 * an interactive user may place an interactive program inside a loop.
4890 * If the interactive program catches interrupts, the user doesn't want
4891 * these interrupts to also abort the loop. The approach we take here
4892 * is to have the shell ignore interrupt signals while waiting for a
4893 * foreground process to terminate, and then send itself an interrupt
4894 * signal if the child process was terminated by an interrupt signal.
4895 * Unfortunately, some programs want to do a bit of cleanup and then
4896 * exit on interrupt; unless these processes terminate themselves by
4897 * sending a signal to themselves (instead of calling exit) they will
4898 * confuse this approach.
4900 * Called with interrupts off.
4903 waitforjob(struct job
*jp
)
4907 TRACE(("waitforjob(%%%d) called\n", jobno(jp
)));
4910 while (jp
->state
== JOBRUNNING
) {
4911 /* In non-interactive shells, we _can_ get
4912 * a keyboard signal here and be EINTRed,
4913 * but we just loop back, waiting for command to complete.
4916 * "If bash is waiting for a command to complete and receives
4917 * a signal for which a trap has been set, the trap
4918 * will not be executed until the command completes."
4920 * Reality is that even if trap is not set, bash
4921 * will not act on the signal until command completes.
4922 * Try this. sleep5intoff.c:
4923 * #include <signal.h>
4924 * #include <unistd.h>
4927 * sigemptyset(&set);
4928 * sigaddset(&set, SIGINT);
4929 * sigaddset(&set, SIGQUIT);
4930 * sigprocmask(SIG_BLOCK, &set, NULL);
4934 * $ bash -c './sleep5intoff; echo hi'
4935 * ^C^C^C^C <--- pressing ^C once a second
4937 * $ bash -c './sleep5intoff; echo hi'
4938 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4941 dowait(DOWAIT_BLOCK
, jp
);
4948 xtcsetpgrp(ttyfd
, rootpid
);
4950 * This is truly gross.
4951 * If we're doing job control, then we did a TIOCSPGRP which
4952 * caused us (the shell) to no longer be in the controlling
4953 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4954 * intuit from the subprocess exit status whether a SIGINT
4955 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4957 if (jp
->sigint
) /* TODO: do the same with all signals */
4958 raise(SIGINT
); /* ... by raise(jp->sig) instead? */
4960 if (jp
->state
== JOBDONE
)
4967 * return 1 if there are stopped jobs, otherwise 0
4979 if (jp
&& jp
->state
== JOBSTOPPED
) {
4980 out2str("You have stopped jobs.\n");
4989 /* ============ redir.c
4991 * Code for dealing with input/output redirection.
4996 #define EMPTY -2 /* marks an unused slot in redirtab */
4997 #define CLOSED -3 /* marks a slot of previously-closed fd */
5000 * Open a file in noclobber mode.
5001 * The code was copied from bash.
5004 noclobberopen(const char *fname
)
5007 struct stat finfo
, finfo2
;
5010 * If the file exists and is a regular file, return an error
5013 r
= stat(fname
, &finfo
);
5014 if (r
== 0 && S_ISREG(finfo
.st_mode
)) {
5020 * If the file was not present (r != 0), make sure we open it
5021 * exclusively so that if it is created before we open it, our open
5022 * will fail. Make sure that we do not truncate an existing file.
5023 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5024 * file was not a regular file, we leave O_EXCL off.
5027 return open(fname
, O_WRONLY
|O_CREAT
|O_EXCL
, 0666);
5028 fd
= open(fname
, O_WRONLY
|O_CREAT
, 0666);
5030 /* If the open failed, return the file descriptor right away. */
5035 * OK, the open succeeded, but the file may have been changed from a
5036 * non-regular file to a regular file between the stat and the open.
5037 * We are assuming that the O_EXCL open handles the case where FILENAME
5038 * did not exist and is symlinked to an existing file between the stat
5043 * If we can open it and fstat the file descriptor, and neither check
5044 * revealed that it was a regular file, and the file has not been
5045 * replaced, return the file descriptor.
5047 if (fstat(fd
, &finfo2
) == 0
5048 && !S_ISREG(finfo2
.st_mode
)
5049 && finfo
.st_dev
== finfo2
.st_dev
5050 && finfo
.st_ino
== finfo2
.st_ino
5055 /* The file has been replaced. badness. */
5062 * Handle here documents. Normally we fork off a process to write the
5063 * data to a pipe. If the document is short, we can stuff the data in
5064 * the pipe without forking.
5066 /* openhere needs this forward reference */
5067 static void expandhere(union node
*arg
, int fd
);
5069 openhere(union node
*redir
)
5075 ash_msg_and_raise_error("pipe call failed");
5076 if (redir
->type
== NHERE
) {
5077 len
= strlen(redir
->nhere
.doc
->narg
.text
);
5078 if (len
<= PIPE_BUF
) {
5079 full_write(pip
[1], redir
->nhere
.doc
->narg
.text
, len
);
5083 if (forkshell((struct job
*)NULL
, (union node
*)NULL
, FORK_NOJOB
) == 0) {
5086 ignoresig(SIGINT
); //signal(SIGINT, SIG_IGN);
5087 ignoresig(SIGQUIT
); //signal(SIGQUIT, SIG_IGN);
5088 ignoresig(SIGHUP
); //signal(SIGHUP, SIG_IGN);
5089 ignoresig(SIGTSTP
); //signal(SIGTSTP, SIG_IGN);
5090 signal(SIGPIPE
, SIG_DFL
);
5091 if (redir
->type
== NHERE
)
5092 full_write(pip
[1], redir
->nhere
.doc
->narg
.text
, len
);
5094 expandhere(redir
->nhere
.doc
, pip
[1]);
5095 _exit(EXIT_SUCCESS
);
5103 openredirect(union node
*redir
)
5108 switch (redir
->nfile
.type
) {
5110 fname
= redir
->nfile
.expfname
;
5111 f
= open(fname
, O_RDONLY
);
5116 fname
= redir
->nfile
.expfname
;
5117 f
= open(fname
, O_RDWR
|O_CREAT
, 0666);
5122 #if ENABLE_ASH_BASH_COMPAT
5125 /* Take care of noclobber mode. */
5127 fname
= redir
->nfile
.expfname
;
5128 f
= noclobberopen(fname
);
5135 fname
= redir
->nfile
.expfname
;
5136 f
= open(fname
, O_WRONLY
|O_CREAT
|O_TRUNC
, 0666);
5141 fname
= redir
->nfile
.expfname
;
5142 f
= open(fname
, O_WRONLY
|O_CREAT
|O_APPEND
, 0666);
5150 /* Fall through to eliminate warning. */
5151 /* Our single caller does this itself */
5158 f
= openhere(redir
);
5164 ash_msg_and_raise_error("can't create %s: %s", fname
, errmsg(errno
, "nonexistent directory"));
5166 ash_msg_and_raise_error("can't open %s: %s", fname
, errmsg(errno
, "no such file"));
5170 * Copy a file descriptor to be >= to. Returns -1
5171 * if the source file descriptor is closed, EMPTY if there are no unused
5172 * file descriptors left.
5174 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5175 * old code was doing close(to) prior to copyfd() to achieve the same */
5177 COPYFD_EXACT
= (int)~(INT_MAX
),
5178 COPYFD_RESTORE
= (int)((unsigned)COPYFD_EXACT
>> 1),
5181 copyfd(int from
, int to
)
5185 if (to
& COPYFD_EXACT
) {
5186 to
&= ~COPYFD_EXACT
;
5188 newfd
= dup2(from
, to
);
5190 newfd
= fcntl(from
, F_DUPFD
, to
);
5193 if (errno
== EMFILE
)
5195 /* Happens when source fd is not open: try "echo >&99" */
5196 ash_msg_and_raise_error("%d: %m", from
);
5201 /* Struct def and variable are moved down to the first usage site */
5206 struct redirtab
*next
;
5209 struct two_fd_t two_fd
[];
5211 #define redirlist (G_var.redirlist)
5213 static int need_to_remember(struct redirtab
*rp
, int fd
)
5217 if (!rp
) /* remembering was not requested */
5220 for (i
= 0; i
< rp
->pair_count
; i
++) {
5221 if (rp
->two_fd
[i
].orig
== fd
) {
5222 /* already remembered */
5229 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5230 static int is_hidden_fd(struct redirtab
*rp
, int fd
)
5233 struct parsefile
*pf
;
5237 /* Check open scripts' fds */
5240 /* We skip pf_fd == 0 case because of the following case:
5241 * $ ash # running ash interactively
5243 * and in script.sh: "exec 9>&0".
5244 * Even though top-level pf_fd _is_ 0,
5245 * it's still ok to use it: "read" builtin uses it,
5246 * why should we cripple "exec" builtin?
5248 if (pf
->pf_fd
> 0 && fd
== pf
->pf_fd
) {
5256 /* Check saved fds of redirects */
5257 fd
|= COPYFD_RESTORE
;
5258 for (i
= 0; i
< rp
->pair_count
; i
++) {
5259 if (rp
->two_fd
[i
].copy
== fd
) {
5267 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5268 * old file descriptors are stashed away so that the redirection can be
5269 * undone by calling popredir.
5271 /* flags passed to redirect */
5272 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5273 #define REDIR_SAVEFD2 03 /* set preverrout */
5275 redirect(union node
*redir
, int flags
)
5277 struct redirtab
*sv
;
5282 int copied_fd2
= -1;
5292 if (flags
& REDIR_PUSH
) {
5293 union node
*tmp
= redir
;
5296 #if ENABLE_ASH_BASH_COMPAT
5297 if (tmp
->nfile
.type
== NTO2
)
5300 tmp
= tmp
->nfile
.next
;
5302 sv
= ckmalloc(sizeof(*sv
) + sv_pos
* sizeof(sv
->two_fd
[0]));
5303 sv
->next
= redirlist
;
5304 sv
->pair_count
= sv_pos
;
5306 sv
->nullredirs
= g_nullredirs
- 1;
5308 while (sv_pos
> 0) {
5310 sv
->two_fd
[sv_pos
].orig
= sv
->two_fd
[sv_pos
].copy
= EMPTY
;
5316 fd
= redir
->nfile
.fd
;
5317 if (redir
->nfile
.type
== NTOFD
|| redir
->nfile
.type
== NFROMFD
) {
5318 right_fd
= redir
->ndup
.dupfd
;
5319 //bb_error_msg("doing %d > %d", fd, right_fd);
5320 /* redirect from/to same file descriptor? */
5323 /* "echo >&10" and 10 is a fd opened to a sh script? */
5324 if (is_hidden_fd(sv
, right_fd
)) {
5325 errno
= EBADF
; /* as if it is closed */
5326 ash_msg_and_raise_error("%d: %m", right_fd
);
5330 newfd
= openredirect(redir
); /* always >= 0 */
5332 /* Descriptor wasn't open before redirect.
5333 * Mark it for close in the future */
5334 if (need_to_remember(sv
, fd
)) {
5335 goto remember_to_close
;
5340 #if ENABLE_ASH_BASH_COMPAT
5343 if (need_to_remember(sv
, fd
)) {
5344 /* Copy old descriptor */
5345 /* Careful to not accidentally "save"
5346 * to the same fd as right side fd in N>&M */
5347 int minfd
= right_fd
< 10 ? 10 : right_fd
+ 1;
5348 i
= fcntl(fd
, F_DUPFD
, minfd
);
5349 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5350 * are closed in popredir() in the child, preventing them from leaking
5351 * into child. (popredir() also cleans up the mess in case of failures)
5356 /* Strange error (e.g. "too many files" EMFILE?) */
5360 ash_msg_and_raise_error("%d: %m", fd
);
5363 /* EBADF: it is not open - good, remember to close it */
5366 } else { /* fd is open, save its copy */
5367 /* "exec fd>&-" should not close fds
5368 * which point to script file(s).
5369 * Force them to be restored afterwards */
5370 if (is_hidden_fd(sv
, fd
))
5371 i
|= COPYFD_RESTORE
;
5375 sv
->two_fd
[sv_pos
].orig
= fd
;
5376 sv
->two_fd
[sv_pos
].copy
= i
;
5380 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5381 if (redir
->ndup
.dupfd
< 0) { /* "fd>&-" */
5382 /* Don't want to trigger debugging */
5386 copyfd(redir
->ndup
.dupfd
, fd
| COPYFD_EXACT
);
5388 } else if (fd
!= newfd
) { /* move newfd to fd */
5389 copyfd(newfd
, fd
| COPYFD_EXACT
);
5390 #if ENABLE_ASH_BASH_COMPAT
5391 if (!(redir
->nfile
.type
== NTO2
&& fd
== 2))
5395 #if ENABLE_ASH_BASH_COMPAT
5396 if (redir
->nfile
.type
== NTO2
&& fd
== 1) {
5397 /* We already redirected it to fd 1, now copy it to 2 */
5403 } while ((redir
= redir
->nfile
.next
) != NULL
);
5406 if ((flags
& REDIR_SAVEFD2
) && copied_fd2
>= 0)
5407 preverrout_fd
= copied_fd2
;
5411 * Undo the effects of the last redirection.
5414 popredir(int drop
, int restore
)
5416 struct redirtab
*rp
;
5419 if (--g_nullredirs
>= 0)
5423 for (i
= 0; i
< rp
->pair_count
; i
++) {
5424 int fd
= rp
->two_fd
[i
].orig
;
5425 int copy
= rp
->two_fd
[i
].copy
;
5426 if (copy
== CLOSED
) {
5431 if (copy
!= EMPTY
) {
5432 if (!drop
|| (restore
&& (copy
& COPYFD_RESTORE
))) {
5433 copy
&= ~COPYFD_RESTORE
;
5435 copyfd(copy
, fd
| COPYFD_EXACT
);
5437 close(copy
& ~COPYFD_RESTORE
);
5440 redirlist
= rp
->next
;
5441 g_nullredirs
= rp
->nullredirs
;
5447 * Undo all redirections. Called on error or interrupt.
5451 * Discard all saved file descriptors.
5454 clearredir(int drop
)
5460 popredir(drop
, /*restore:*/ 0);
5465 redirectsafe(union node
*redir
, int flags
)
5468 volatile int saveint
;
5469 struct jmploc
*volatile savehandler
= exception_handler
;
5470 struct jmploc jmploc
;
5473 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5474 err
= setjmp(jmploc
.loc
); // huh?? was = setjmp(jmploc.loc) * 2;
5476 exception_handler
= &jmploc
;
5477 redirect(redir
, flags
);
5479 exception_handler
= savehandler
;
5480 if (err
&& exception_type
!= EXERROR
)
5481 longjmp(exception_handler
->loc
, 1);
5482 RESTORE_INT(saveint
);
5487 /* ============ Routines to expand arguments to commands
5489 * We have to deal with backquotes, shell variables, and file metacharacters.
5492 #if ENABLE_SH_MATH_SUPPORT
5494 ash_arith(const char *s
)
5496 arith_state_t math_state
;
5499 math_state
.lookupvar
= lookupvar
;
5500 math_state
.setvar
= setvar2
;
5501 //math_state.endofname = endofname;
5504 result
= arith(&math_state
, s
);
5505 if (math_state
.errmsg
)
5506 ash_msg_and_raise_error(math_state
.errmsg
);
5516 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5517 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5518 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5519 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5520 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5521 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5522 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5523 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5524 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5528 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5529 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5530 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5531 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5532 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5535 * Structure specifying which parts of the string should be searched
5536 * for IFS characters.
5539 struct ifsregion
*next
; /* next region in list */
5540 int begoff
; /* offset of start of region */
5541 int endoff
; /* offset of end of region */
5542 int nulonly
; /* search for nul bytes only */
5546 struct strlist
*list
;
5547 struct strlist
**lastp
;
5550 /* output of current string */
5551 static char *expdest
;
5552 /* list of back quote expressions */
5553 static struct nodelist
*argbackq
;
5554 /* first struct in list of ifs regions */
5555 static struct ifsregion ifsfirst
;
5556 /* last struct in list */
5557 static struct ifsregion
*ifslastp
;
5558 /* holds expanded arg list */
5559 static struct arglist exparg
;
5564 #if !ENABLE_SH_MATH_SUPPORT
5565 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5566 typedef long arith_t
;
5567 # define ARITH_FMT "%ld"
5574 expdest
= makestrspace(32, expdest
);
5575 len
= fmtstr(expdest
, 32, ARITH_FMT
, num
);
5576 STADJUST(len
, expdest
);
5581 esclen(const char *start
, const char *p
)
5585 while (p
> start
&& (unsigned char)*--p
== CTLESC
) {
5592 * Remove any CTLESC characters from a string.
5595 rmescapes(char *str
, int flag
)
5597 static const char qchars
[] ALIGN1
= { CTLESC
, CTLQUOTEMARK
, '\0' };
5601 unsigned protect_against_glob
;
5604 p
= strpbrk(str
, qchars
);
5610 if (flag
& RMESCAPE_ALLOC
) {
5611 size_t len
= p
- str
;
5612 size_t fulllen
= len
+ strlen(p
) + 1;
5614 if (flag
& RMESCAPE_GROW
) {
5615 int strloc
= str
- (char *)stackblock();
5616 r
= makestrspace(fulllen
, expdest
);
5617 /* p and str may be invalidated by makestrspace */
5618 str
= (char *)stackblock() + strloc
;
5620 } else if (flag
& RMESCAPE_HEAP
) {
5621 r
= ckmalloc(fulllen
);
5623 r
= stalloc(fulllen
);
5627 q
= (char *)memcpy(q
, str
, len
) + len
;
5631 inquotes
= (flag
& RMESCAPE_QUOTED
) ^ RMESCAPE_QUOTED
;
5632 globbing
= flag
& RMESCAPE_GLOB
;
5633 protect_against_glob
= globbing
;
5635 if ((unsigned char)*p
== CTLQUOTEMARK
) {
5636 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5637 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5638 // Note: both inquotes and protect_against_glob only affect whether
5639 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5640 inquotes
= ~inquotes
;
5642 protect_against_glob
= globbing
;
5646 /* naked back slash */
5647 protect_against_glob
= 0;
5650 if ((unsigned char)*p
== CTLESC
) {
5652 if (protect_against_glob
&& inquotes
&& *p
!= '/') {
5656 protect_against_glob
= globbing
;
5661 if (flag
& RMESCAPE_GROW
) {
5663 STADJUST(q
- r
+ 1, expdest
);
5667 #define pmatch(a, b) !fnmatch((a), (b), 0)
5670 * Prepare a pattern for a expmeta (internal glob(3)) call.
5672 * Returns an stalloced string.
5675 preglob(const char *pattern
, int quoted
, int flag
)
5677 flag
|= RMESCAPE_GLOB
;
5679 flag
|= RMESCAPE_QUOTED
;
5681 return rmescapes((char *)pattern
, flag
);
5685 * Put a string on the stack.
5688 memtodest(const char *p
, size_t len
, int syntax
, int quotes
)
5692 q
= makestrspace(quotes
? len
* 2 : len
, q
);
5695 unsigned char c
= *p
++;
5699 int n
= SIT(c
, syntax
);
5700 if (n
== CCTL
|| n
== CBACK
)
5710 strtodest(const char *p
, int syntax
, int quotes
)
5712 memtodest(p
, strlen(p
), syntax
, quotes
);
5716 * Record the fact that we have to scan this region of the
5717 * string for IFS characters.
5720 recordregion(int start
, int end
, int nulonly
)
5722 struct ifsregion
*ifsp
;
5724 if (ifslastp
== NULL
) {
5728 ifsp
= ckzalloc(sizeof(*ifsp
));
5729 /*ifsp->next = NULL; - ckzalloc did it */
5730 ifslastp
->next
= ifsp
;
5734 ifslastp
->begoff
= start
;
5735 ifslastp
->endoff
= end
;
5736 ifslastp
->nulonly
= nulonly
;
5740 removerecordregions(int endoff
)
5742 if (ifslastp
== NULL
)
5745 if (ifsfirst
.endoff
> endoff
) {
5746 while (ifsfirst
.next
) {
5747 struct ifsregion
*ifsp
;
5749 ifsp
= ifsfirst
.next
->next
;
5750 free(ifsfirst
.next
);
5751 ifsfirst
.next
= ifsp
;
5754 if (ifsfirst
.begoff
> endoff
) {
5757 ifslastp
= &ifsfirst
;
5758 ifsfirst
.endoff
= endoff
;
5763 ifslastp
= &ifsfirst
;
5764 while (ifslastp
->next
&& ifslastp
->next
->begoff
< endoff
)
5765 ifslastp
= ifslastp
->next
;
5766 while (ifslastp
->next
) {
5767 struct ifsregion
*ifsp
;
5769 ifsp
= ifslastp
->next
->next
;
5770 free(ifslastp
->next
);
5771 ifslastp
->next
= ifsp
;
5774 if (ifslastp
->endoff
> endoff
)
5775 ifslastp
->endoff
= endoff
;
5779 exptilde(char *startp
, char *p
, int flags
)
5785 int quotes
= flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
);
5790 while ((c
= *++p
) != '\0') {
5797 if (flags
& EXP_VARTILDE
)
5807 if (*name
== '\0') {
5808 home
= lookupvar("HOME");
5810 pw
= getpwnam(name
);
5815 if (!home
|| !*home
)
5818 startloc
= expdest
- (char *)stackblock();
5819 strtodest(home
, SQSYNTAX
, quotes
);
5820 recordregion(startloc
, expdest
- (char *)stackblock(), 0);
5828 * Execute a command inside back quotes. If it's a builtin command, we
5829 * want to save its output in a block obtained from malloc. Otherwise
5830 * we fork off a subprocess and get the output of the command via a pipe.
5831 * Should be called with interrupts off.
5833 struct backcmd
{ /* result of evalbackcmd */
5834 int fd
; /* file descriptor to read from */
5835 int nleft
; /* number of chars in buffer */
5836 char *buf
; /* buffer */
5837 struct job
*jp
; /* job structure for command */
5840 /* These forward decls are needed to use "eval" code for backticks handling: */
5841 static uint8_t back_exitstatus
; /* exit status of backquoted command */
5842 #define EV_EXIT 01 /* exit after evaluating tree */
5843 static void evaltree(union node
*, int);
5845 static void FAST_FUNC
5846 evalbackcmd(union node
*n
, struct backcmd
*result
)
5857 saveherefd
= herefd
;
5865 ash_msg_and_raise_error("pipe call failed");
5866 jp
= makejob(/*n,*/ 1);
5867 if (forkshell(jp
, n
, FORK_NOJOB
) == 0) {
5872 copyfd(pip
[1], 1 | COPYFD_EXACT
);
5876 evaltree(n
, EV_EXIT
); /* actually evaltreenr... */
5880 result
->fd
= pip
[0];
5883 herefd
= saveherefd
;
5885 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5886 result
->fd
, result
->buf
, result
->nleft
, result
->jp
));
5890 * Expand stuff in backwards quotes.
5893 expbackq(union node
*cmd
, int quoted
, int quotes
)
5901 int syntax
= quoted
? DQSYNTAX
: BASESYNTAX
;
5902 struct stackmark smark
;
5905 setstackmark(&smark
);
5907 startloc
= dest
- (char *)stackblock();
5909 evalbackcmd(cmd
, &in
);
5910 popstackmark(&smark
);
5917 memtodest(p
, i
, syntax
, quotes
);
5921 i
= nonblock_immune_read(in
.fd
, buf
, sizeof(buf
), /*loop_on_EINTR:*/ 1);
5922 TRACE(("expbackq: read returns %d\n", i
));
5931 back_exitstatus
= waitforjob(in
.jp
);
5935 /* Eat all trailing newlines */
5937 for (; dest
> (char *)stackblock() && dest
[-1] == '\n';)
5942 recordregion(startloc
, dest
- (char *)stackblock(), 0);
5943 TRACE(("evalbackq: size:%d:'%.*s'\n",
5944 (int)((dest
- (char *)stackblock()) - startloc
),
5945 (int)((dest
- (char *)stackblock()) - startloc
),
5946 stackblock() + startloc
));
5949 #if ENABLE_SH_MATH_SUPPORT
5951 * Expand arithmetic expression. Backup to start of expression,
5952 * evaluate, place result in (backed up) result, adjust string position.
5965 * This routine is slightly over-complicated for
5966 * efficiency. Next we scan backwards looking for the
5967 * start of arithmetic.
5969 start
= stackblock();
5976 while ((unsigned char)*p
!= CTLARI
) {
5980 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5985 esc
= esclen(start
, p
);
5995 removerecordregions(begoff
);
6002 rmescapes(p
+ 2, 0);
6004 len
= cvtnum(ash_arith(p
+ 2));
6007 recordregion(begoff
, begoff
+ len
, 0);
6011 /* argstr needs it */
6012 static char *evalvar(char *p
, int flags
, struct strlist
*var_str_list
);
6015 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6016 * characters to allow for further processing. Otherwise treat
6017 * $@ like $* since no splitting will be performed.
6019 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6020 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
6021 * for correct expansion of "B=$A" word.
6024 argstr(char *p
, int flags
, struct strlist
*var_str_list
)
6026 static const char spclchars
[] ALIGN1
= {
6034 CTLBACKQ
| CTLQUOTE
,
6035 #if ENABLE_SH_MATH_SUPPORT
6040 const char *reject
= spclchars
;
6041 int quotes
= flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
); /* do CTLESC */
6042 int breakall
= flags
& EXP_WORD
;
6047 if (!(flags
& EXP_VARTILDE
)) {
6049 } else if (flags
& EXP_VARTILDE2
) {
6054 if (flags
& EXP_TILDE
) {
6057 flags
&= ~EXP_TILDE
;
6060 if ((unsigned char)*q
== CTLESC
&& (flags
& EXP_QWORD
))
6063 p
= exptilde(p
, q
, flags
);
6066 startloc
= expdest
- (char *)stackblock();
6070 length
+= strcspn(p
+ length
, reject
);
6074 IF_SH_MATH_SUPPORT(|| c
== CTLENDARI
)
6076 /* c == '=' || c == ':' || c == CTLENDARI */
6082 expdest
= stack_nputstr(p
, length
, expdest
);
6083 newloc
= expdest
- (char *)stackblock();
6084 if (breakall
&& !inquotes
&& newloc
> startloc
) {
6085 recordregion(startloc
, newloc
, 0);
6096 if (flags
& EXP_VARTILDE2
) {
6100 flags
|= EXP_VARTILDE2
;
6105 * sort of a hack - expand tildes in variable
6106 * assignments (after the first '=' and after ':'s).
6115 case CTLENDVAR
: /* ??? */
6118 /* "$@" syntax adherence hack */
6120 && memcmp(p
, dolatstr
, 4) == 0
6121 && ( p
[4] == (char)CTLQUOTEMARK
6122 || (p
[4] == (char)CTLENDVAR
&& p
[5] == (char)CTLQUOTEMARK
)
6125 p
= evalvar(p
+ 1, flags
, /* var_str_list: */ NULL
) + 1;
6128 inquotes
= !inquotes
;
6141 p
= evalvar(p
, flags
, var_str_list
);
6145 case CTLBACKQ
|CTLQUOTE
:
6146 expbackq(argbackq
->n
, c
, quotes
);
6147 argbackq
= argbackq
->next
;
6149 #if ENABLE_SH_MATH_SUPPORT
6161 scanleft(char *startp
, char *rmesc
, char *rmescend UNUSED_PARAM
,
6162 char *pattern
, int quotes
, int zero
)
6171 const char *s
= loc2
;
6178 match
= pmatch(pattern
, s
);
6183 if (quotes
&& (unsigned char)*loc
== CTLESC
)
6192 scanright(char *startp
, char *rmesc
, char *rmescend
,
6193 char *pattern
, int quotes
, int match_at_start
)
6195 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6196 int try2optimize
= match_at_start
;
6202 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6203 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6204 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6206 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6207 * and on each iteration they go back two/one char until they reach the beginning.
6208 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6210 /* TODO: document in what other circumstances we are called. */
6212 for (loc
= pattern
- 1, loc2
= rmescend
; loc
>= startp
; loc2
--) {
6215 const char *s
= loc2
;
6216 if (match_at_start
) {
6220 match
= pmatch(pattern
, s
);
6221 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6225 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6227 /* Maybe we can optimize this:
6228 * if pattern ends with unescaped *, we can avoid checking
6229 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6230 * it wont match truncated "raw_value_of_" strings too.
6232 unsigned plen
= strlen(pattern
);
6233 /* Does it end with "*"? */
6234 if (plen
!= 0 && pattern
[--plen
] == '*') {
6235 /* "xxxx*" is not escaped */
6236 /* "xxx\*" is escaped */
6237 /* "xx\\*" is not escaped */
6238 /* "x\\\*" is escaped */
6240 while (plen
!= 0 && pattern
[--plen
] == '\\')
6243 break; /* ends with unescaped "*" */
6251 esc
= esclen(startp
, loc
);
6262 static void varunset(const char *, const char *, const char *, int) NORETURN
;
6264 varunset(const char *end
, const char *var
, const char *umsg
, int varflags
)
6270 msg
= "parameter not set";
6272 if ((unsigned char)*end
== CTLENDVAR
) {
6273 if (varflags
& VSNUL
)
6279 ash_msg_and_raise_error("%.*s: %s%s", (int)(end
- var
- 1), var
, msg
, tail
);
6282 #if ENABLE_ASH_BASH_COMPAT
6284 parse_sub_pattern(char *arg
, int varflags
)
6286 char *idx
, *repl
= NULL
;
6289 //char *org_arg = arg;
6290 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6297 /* Only the first '/' seen is our separator */
6306 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6307 * The result is a_\_z_c (not a\_\_z_c)!
6309 * Enable debug prints in this function and you'll see:
6310 * ash: arg:'\\b/_\\_z_' varflags:d
6311 * ash: pattern:'\\b' repl:'_\_z_'
6312 * That is, \\b is interpreted as \\b, but \\_ as \_!
6313 * IOW: search pattern and replace string treat backslashes
6314 * differently! That is the reason why we check repl below:
6316 if (c
== '\\' && *arg
== '\\' && repl
&& !(varflags
& VSQUOTE
))
6317 arg
++; /* skip both '\', not just first one */
6320 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6324 #endif /* ENABLE_ASH_BASH_COMPAT */
6327 subevalvar(char *p
, char *varname
, int strloc
, int subtype
,
6328 int startloc
, int varflags
, int quotes
, struct strlist
*var_str_list
)
6330 struct nodelist
*saveargbackq
= argbackq
;
6333 char *rmesc
, *rmescend
;
6335 IF_ASH_BASH_COMPAT(const char *repl
= NULL
;)
6336 IF_ASH_BASH_COMPAT(int pos
, len
, orig_len
;)
6337 int saveherefd
= herefd
;
6338 int amount
, workloc
, resetloc
;
6340 char *(*scan
)(char*, char*, char*, char*, int, int);
6342 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6343 // p, varname, strloc, subtype, startloc, varflags, quotes);
6346 argstr(p
, (subtype
!= VSASSIGN
&& subtype
!= VSQUESTION
) ? EXP_CASE
: 0,
6348 STPUTC('\0', expdest
);
6349 herefd
= saveherefd
;
6350 argbackq
= saveargbackq
;
6351 startp
= (char *)stackblock() + startloc
;
6355 setvar(varname
, startp
, 0);
6356 amount
= startp
- expdest
;
6357 STADJUST(amount
, expdest
);
6361 varunset(p
, varname
, startp
, varflags
);
6364 #if ENABLE_ASH_BASH_COMPAT
6366 loc
= str
= stackblock() + strloc
;
6367 /* Read POS in ${var:POS:LEN} */
6368 pos
= atoi(loc
); /* number(loc) errors out on "1:4" */
6369 len
= str
- startp
- 1;
6371 /* *loc != '\0', guaranteed by parser */
6375 /* Adjust the length by the number of escapes */
6376 for (ptr
= startp
; ptr
< (str
- 1); ptr
++) {
6377 if ((unsigned char)*ptr
== CTLESC
) {
6385 if (*loc
++ == ':') {
6389 /* Skip POS in ${var:POS:LEN} */
6391 while (*loc
&& *loc
!= ':') {
6393 * bash complains on: var=qwe; echo ${var:1a:123}
6395 ash_msg_and_raise_error(msg_illnum, str);
6399 if (*loc
++ == ':') {
6403 if (pos
>= orig_len
) {
6407 if (len
> (orig_len
- pos
))
6408 len
= orig_len
- pos
;
6410 for (str
= startp
; pos
; str
++, pos
--) {
6411 if (quotes
&& (unsigned char)*str
== CTLESC
)
6414 for (loc
= startp
; len
; len
--) {
6415 if (quotes
&& (unsigned char)*str
== CTLESC
)
6420 amount
= loc
- expdest
;
6421 STADJUST(amount
, expdest
);
6426 resetloc
= expdest
- (char *)stackblock();
6428 /* We'll comeback here if we grow the stack while handling
6429 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6430 * stack will need rebasing, and we'll need to remove our work
6433 IF_ASH_BASH_COMPAT(restart
:)
6435 amount
= expdest
- ((char *)stackblock() + resetloc
);
6436 STADJUST(-amount
, expdest
);
6437 startp
= (char *)stackblock() + startloc
;
6440 rmescend
= (char *)stackblock() + strloc
;
6442 rmesc
= rmescapes(startp
, RMESCAPE_ALLOC
| RMESCAPE_GROW
);
6443 if (rmesc
!= startp
) {
6445 startp
= (char *)stackblock() + startloc
;
6449 str
= (char *)stackblock() + strloc
;
6450 preglob(str
, varflags
& VSQUOTE
, 0);
6451 workloc
= expdest
- (char *)stackblock();
6453 #if ENABLE_ASH_BASH_COMPAT
6454 if (subtype
== VSREPLACE
|| subtype
== VSREPLACEALL
) {
6458 repl
= parse_sub_pattern(str
, varflags
);
6459 //bb_error_msg("repl:'%s'", repl);
6464 /* If there's no pattern to match, return the expansion unmolested */
6473 loc
= scanright(idx
, rmesc
, rmescend
, str
, quotes
, 1);
6474 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6476 /* No match, advance */
6477 char *restart_detect
= stackblock();
6479 STPUTC(*idx
, expdest
);
6480 if (quotes
&& (unsigned char)*idx
== CTLESC
) {
6483 STPUTC(*idx
, expdest
);
6485 if (stackblock() != restart_detect
)
6490 /* continue; - prone to quadratic behavior, smarter code: */
6493 if (str
[0] == '*') {
6494 /* Pattern is "*foo". If "*foo" does not match "long_string",
6495 * it would never match "ong_string" etc, no point in trying.
6502 if (subtype
== VSREPLACEALL
) {
6504 if (quotes
&& (unsigned char)*idx
== CTLESC
)
6513 //bb_error_msg("repl:'%s'", repl);
6514 for (loc
= (char*)repl
; *loc
; loc
++) {
6515 char *restart_detect
= stackblock();
6516 if (quotes
&& *loc
== '\\') {
6517 STPUTC(CTLESC
, expdest
);
6520 STPUTC(*loc
, expdest
);
6521 if (stackblock() != restart_detect
)
6526 if (subtype
== VSREPLACE
) {
6527 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6529 char *restart_detect
= stackblock();
6530 STPUTC(*idx
, expdest
);
6531 if (stackblock() != restart_detect
)
6540 /* We've put the replaced text into a buffer at workloc, now
6541 * move it to the right place and adjust the stack.
6543 STPUTC('\0', expdest
);
6544 startp
= (char *)stackblock() + startloc
;
6545 memmove(startp
, (char *)stackblock() + workloc
, len
+ 1);
6546 //bb_error_msg("startp:'%s'", startp);
6547 amount
= expdest
- (startp
+ len
);
6548 STADJUST(-amount
, expdest
);
6551 #endif /* ENABLE_ASH_BASH_COMPAT */
6553 subtype
-= VSTRIMRIGHT
;
6555 if (subtype
< 0 || subtype
> 7)
6558 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6559 zero
= subtype
>> 1;
6560 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6561 scan
= (subtype
& 1) ^ zero
? scanleft
: scanright
;
6563 loc
= scan(startp
, rmesc
, rmescend
, str
, quotes
, zero
);
6566 memmove(startp
, loc
, str
- loc
);
6567 loc
= startp
+ (str
- loc
) - 1;
6570 amount
= loc
- expdest
;
6571 STADJUST(amount
, expdest
);
6577 * Add the value of a specialized variable to the stack string.
6578 * name parameter (examples):
6579 * ash -c 'echo $1' name:'1='
6580 * ash -c 'echo $qwe' name:'qwe='
6581 * ash -c 'echo $$' name:'$='
6582 * ash -c 'echo ${$}' name:'$='
6583 * ash -c 'echo ${$##q}' name:'$=q'
6584 * ash -c 'echo ${#$}' name:'$='
6585 * note: examples with bad shell syntax:
6586 * ash -c 'echo ${#$1}' name:'$=1'
6587 * ash -c 'echo ${#1#}' name:'1=#'
6589 static NOINLINE ssize_t
6590 varvalue(char *name
, int varflags
, int flags
, struct strlist
*var_str_list
)
6597 int subtype
= varflags
& VSTYPE
;
6598 int quotes
= flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
);
6599 int quoted
= varflags
& VSQUOTE
;
6600 int syntax
= quoted
? DQSYNTAX
: BASESYNTAX
;
6610 num
= shellparam
.nparam
;
6618 goto check_1char_name
;
6620 expdest
= makestrspace(NOPTS
, expdest
);
6621 for (i
= NOPTS
- 1; i
>= 0; i
--) {
6623 USTPUTC(optletters(i
), expdest
);
6629 /* handles cases similar to ${#$1} */
6630 if (name
[2] != '\0')
6631 raise_error_syntax("bad substitution");
6638 if (quoted
&& (flags
& EXP_FULL
)) {
6639 /* note: this is not meant as PEOF value */
6640 sep
= 1 << CHAR_BIT
;
6645 sep
= ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6646 i
= SIT(sep
, syntax
);
6647 if (quotes
&& (i
== CCTL
|| i
== CBACK
))
6653 while ((p
= *ap
++) != NULL
) {
6656 partlen
= strlen(p
);
6659 if (!(subtype
== VSPLUS
|| subtype
== VSLENGTH
))
6660 memtodest(p
, partlen
, syntax
, quotes
);
6666 if (subtype
== VSPLUS
|| subtype
== VSLENGTH
) {
6672 /* note: may put NUL despite sep != 0
6673 * (see sep = 1 << CHAR_BIT above) */
6679 } /* case '@' and '*' */
6690 num
= atoi(name
); /* number(name) fails on ${N#str} etc */
6691 if (num
< 0 || num
> shellparam
.nparam
)
6693 p
= num
? shellparam
.p
[num
- 1] : arg0
;
6696 /* NB: name has form "VAR=..." */
6698 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6699 * which should be considered before we check variables. */
6701 unsigned name_len
= (strchrnul(name
, '=') - name
) + 1;
6705 str
= var_str_list
->text
;
6706 eq
= strchr(str
, '=');
6707 if (!eq
) /* stop at first non-assignment */
6710 if (name_len
== (unsigned)(eq
- str
)
6711 && strncmp(str
, name
, name_len
) == 0
6714 /* goto value; - WRONG! */
6715 /* think "A=1 A=2 B=$A" */
6717 var_str_list
= var_str_list
->next
;
6718 } while (var_str_list
);
6722 p
= lookupvar(name
);
6728 if (!(subtype
== VSPLUS
|| subtype
== VSLENGTH
))
6729 memtodest(p
, len
, syntax
, quotes
);
6733 if (subtype
== VSPLUS
|| subtype
== VSLENGTH
)
6734 STADJUST(-len
, expdest
);
6739 * Expand a variable, and return a pointer to the next character in the
6743 evalvar(char *p
, int flags
, struct strlist
*var_str_list
)
6754 varflags
= (unsigned char) *p
++;
6755 subtype
= varflags
& VSTYPE
;
6756 quoted
= varflags
& VSQUOTE
;
6758 easy
= (!quoted
|| (*var
== '@' && shellparam
.nparam
));
6759 startloc
= expdest
- (char *)stackblock();
6760 p
= strchr(p
, '=') + 1; //TODO: use var_end(p)?
6763 varlen
= varvalue(var
, varflags
, flags
, var_str_list
);
6764 if (varflags
& VSNUL
)
6767 if (subtype
== VSPLUS
) {
6768 varlen
= -1 - varlen
;
6772 if (subtype
== VSMINUS
) {
6777 flags
| (quoted
? EXP_TILDE
|EXP_QWORD
: EXP_TILDE
|EXP_WORD
),
6787 if (subtype
== VSASSIGN
|| subtype
== VSQUESTION
) {
6789 if (subevalvar(p
, var
, /* strloc: */ 0,
6790 subtype
, startloc
, varflags
,
6796 * Remove any recorded regions beyond
6799 removerecordregions(startloc
);
6809 if (varlen
< 0 && uflag
)
6810 varunset(p
, var
, 0, 0);
6812 if (subtype
== VSLENGTH
) {
6813 cvtnum(varlen
> 0 ? varlen
: 0);
6817 if (subtype
== VSNORMAL
) {
6828 case VSTRIMRIGHTMAX
:
6829 #if ENABLE_ASH_BASH_COMPAT
6842 * Terminate the string and start recording the pattern
6845 STPUTC('\0', expdest
);
6846 patloc
= expdest
- (char *)stackblock();
6847 if (NULL
== subevalvar(p
, /* varname: */ NULL
, patloc
, subtype
,
6849 /* quotes: */ flags
& (EXP_FULL
| EXP_CASE
| EXP_REDIR
),
6852 int amount
= expdest
- (
6853 (char *)stackblock() + patloc
- 1
6855 STADJUST(-amount
, expdest
);
6857 /* Remove any recorded regions beyond start of variable */
6858 removerecordregions(startloc
);
6860 recordregion(startloc
, expdest
- (char *)stackblock(), quoted
);
6864 if (subtype
!= VSNORMAL
) { /* skip to end of alternative */
6867 unsigned char c
= *p
++;
6870 else if (c
== CTLBACKQ
|| c
== (CTLBACKQ
|CTLQUOTE
)) {
6872 argbackq
= argbackq
->next
;
6873 } else if (c
== CTLVAR
) {
6874 if ((*p
++ & VSTYPE
) != VSNORMAL
)
6876 } else if (c
== CTLENDVAR
) {
6886 * Break the argument string into pieces based upon IFS and add the
6887 * strings to the argument list. The regions of the string to be
6888 * searched for IFS characters have been stored by recordregion.
6891 ifsbreakup(char *string
, struct arglist
*arglist
)
6893 struct ifsregion
*ifsp
;
6898 const char *ifs
, *realifs
;
6903 if (ifslastp
!= NULL
) {
6906 realifs
= ifsset() ? ifsval() : defifs
;
6909 p
= string
+ ifsp
->begoff
;
6910 nulonly
= ifsp
->nulonly
;
6911 ifs
= nulonly
? nullstr
: realifs
;
6913 while (p
< string
+ ifsp
->endoff
) {
6915 if ((unsigned char)*p
== CTLESC
)
6917 if (!strchr(ifs
, *p
)) {
6922 ifsspc
= (strchr(defifs
, *p
) != NULL
);
6923 /* Ignore IFS whitespace at start */
6924 if (q
== start
&& ifsspc
) {
6930 sp
= stzalloc(sizeof(*sp
));
6932 *arglist
->lastp
= sp
;
6933 arglist
->lastp
= &sp
->next
;
6937 if (p
>= string
+ ifsp
->endoff
) {
6941 if ((unsigned char)*p
== CTLESC
)
6943 if (strchr(ifs
, *p
) == NULL
) {
6947 if (strchr(defifs
, *p
) == NULL
) {
6962 } while (ifsp
!= NULL
);
6971 sp
= stzalloc(sizeof(*sp
));
6973 *arglist
->lastp
= sp
;
6974 arglist
->lastp
= &sp
->next
;
6980 struct ifsregion
*p
;
6985 struct ifsregion
*ifsp
;
6991 ifsfirst
.next
= NULL
;
6996 * Add a file name to the list.
6999 addfname(const char *name
)
7003 sp
= stzalloc(sizeof(*sp
));
7004 sp
->text
= ststrdup(name
);
7006 exparg
.lastp
= &sp
->next
;
7010 * Do metacharacter (i.e. *, ?, [...]) expansion.
7013 expmeta(char *expdir
, char *enddir
, char *name
)
7028 for (p
= name
; *p
; p
++) {
7029 if (*p
== '*' || *p
== '?')
7031 else if (*p
== '[') {
7038 if (*q
== '/' || *q
== '\0')
7045 } else if (*p
== '\\')
7047 else if (*p
== '/') {
7054 if (metaflag
== 0) { /* we've reached the end of the file name */
7055 if (enddir
!= expdir
)
7063 if (metaflag
== 0 || lstat(expdir
, &statb
) >= 0)
7074 } while (p
< start
);
7076 if (enddir
== expdir
) {
7078 } else if (enddir
== expdir
+ 1 && *expdir
== '/') {
7087 if (enddir
!= expdir
)
7089 if (*endname
== 0) {
7101 while (!pending_int
&& (dp
= readdir(dirp
)) != NULL
) {
7102 if (dp
->d_name
[0] == '.' && !matchdot
)
7104 if (pmatch(start
, dp
->d_name
)) {
7106 strcpy(enddir
, dp
->d_name
);
7109 for (p
= enddir
, cp
= dp
->d_name
; (*p
++ = *cp
++) != '\0';)
7112 expmeta(expdir
, p
, endname
);
7121 static struct strlist
*
7122 msort(struct strlist
*list
, int len
)
7124 struct strlist
*p
, *q
= NULL
;
7125 struct strlist
**lpp
;
7133 for (n
= half
; --n
>= 0;) {
7137 q
->next
= NULL
; /* terminate first half of list */
7138 q
= msort(list
, half
); /* sort first half of list */
7139 p
= msort(p
, len
- half
); /* sort second half */
7142 #if ENABLE_LOCALE_SUPPORT
7143 if (strcoll(p
->text
, q
->text
) < 0)
7145 if (strcmp(p
->text
, q
->text
) < 0)
7169 * Sort the results of file name expansion. It calculates the number of
7170 * strings to sort and then calls msort (short for merge sort) to do the
7173 static struct strlist
*
7174 expsort(struct strlist
*str
)
7180 for (sp
= str
; sp
; sp
= sp
->next
)
7182 return msort(str
, len
);
7186 expandmeta(struct strlist
*str
/*, int flag*/)
7188 static const char metachars
[] ALIGN1
= {
7191 /* TODO - EXP_REDIR */
7195 struct strlist
**savelastp
;
7201 if (!strpbrk(str
->text
, metachars
))
7203 savelastp
= exparg
.lastp
;
7206 p
= preglob(str
->text
, 0, RMESCAPE_ALLOC
| RMESCAPE_HEAP
);
7208 int i
= strlen(str
->text
);
7209 expdir
= ckmalloc(i
< 2048 ? 2048 : i
); /* XXX */
7211 expmeta(expdir
, expdir
, p
);
7216 if (exparg
.lastp
== savelastp
) {
7221 *exparg
.lastp
= str
;
7222 rmescapes(str
->text
, 0);
7223 exparg
.lastp
= &str
->next
;
7225 *exparg
.lastp
= NULL
;
7226 *savelastp
= sp
= expsort(*savelastp
);
7227 while (sp
->next
!= NULL
)
7229 exparg
.lastp
= &sp
->next
;
7236 * Perform variable substitution and command substitution on an argument,
7237 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7238 * perform splitting and file name expansion. When arglist is NULL, perform
7239 * here document expansion.
7242 expandarg(union node
*arg
, struct arglist
*arglist
, int flag
)
7247 argbackq
= arg
->narg
.backquote
;
7248 STARTSTACKSTR(expdest
);
7249 ifsfirst
.next
= NULL
;
7251 argstr(arg
->narg
.text
, flag
,
7252 /* var_str_list: */ arglist
? arglist
->list
: NULL
);
7253 p
= _STPUTC('\0', expdest
);
7255 if (arglist
== NULL
) {
7256 return; /* here document expanded */
7258 p
= grabstackstr(p
);
7259 exparg
.lastp
= &exparg
.list
;
7263 if (flag
& EXP_FULL
) {
7264 ifsbreakup(p
, &exparg
);
7265 *exparg
.lastp
= NULL
;
7266 exparg
.lastp
= &exparg
.list
;
7267 expandmeta(exparg
.list
/*, flag*/);
7269 if (flag
& EXP_REDIR
) /*XXX - for now, just remove escapes */
7271 sp
= stzalloc(sizeof(*sp
));
7274 exparg
.lastp
= &sp
->next
;
7278 *exparg
.lastp
= NULL
;
7280 *arglist
->lastp
= exparg
.list
;
7281 arglist
->lastp
= exparg
.lastp
;
7286 * Expand shell variables and backquotes inside a here document.
7289 expandhere(union node
*arg
, int fd
)
7292 expandarg(arg
, (struct arglist
*)NULL
, 0);
7293 full_write(fd
, stackblock(), expdest
- (char *)stackblock());
7297 * Returns true if the pattern matches the string.
7300 patmatch(char *pattern
, const char *string
)
7302 return pmatch(preglob(pattern
, 0, 0), string
);
7306 * See if a pattern matches in a case statement.
7309 casematch(union node
*pattern
, char *val
)
7311 struct stackmark smark
;
7314 setstackmark(&smark
);
7315 argbackq
= pattern
->narg
.backquote
;
7316 STARTSTACKSTR(expdest
);
7318 argstr(pattern
->narg
.text
, EXP_TILDE
| EXP_CASE
,
7319 /* var_str_list: */ NULL
);
7320 STACKSTRNUL(expdest
);
7321 result
= patmatch(stackblock(), val
);
7322 popstackmark(&smark
);
7327 /* ============ find_command */
7331 int (*builtin
)(int, char **) FAST_FUNC
;
7332 /* unsigned flags; */
7334 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7335 /* "regular" builtins always take precedence over commands,
7336 * regardless of PATH=....%builtin... position */
7337 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7338 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7341 smallint cmdtype
; /* CMDxxx */
7344 /* index >= 0 for commands without path (slashes) */
7345 /* (TODO: what exactly does the value mean? PATH position?) */
7346 /* index == -1 for commands with slashes */
7347 /* index == (-2 - applet_no) for NOFORK applets */
7348 const struct builtincmd
*cmd
;
7349 struct funcnode
*func
;
7352 /* values of cmdtype */
7353 #define CMDUNKNOWN -1 /* no entry in table for command */
7354 #define CMDNORMAL 0 /* command is an executable program */
7355 #define CMDFUNCTION 1 /* command is a shell function */
7356 #define CMDBUILTIN 2 /* command is a shell builtin */
7358 /* action to find_command() */
7359 #define DO_ERR 0x01 /* prints errors */
7360 #define DO_ABS 0x02 /* checks absolute paths */
7361 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7362 #define DO_ALTPATH 0x08 /* using alternate path */
7363 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7365 static void find_command(char *, struct cmdentry
*, int, const char *);
7368 /* ============ Hashing commands */
7371 * When commands are first encountered, they are entered in a hash table.
7372 * This ensures that a full path search will not have to be done for them
7373 * on each invocation.
7375 * We should investigate converting to a linear search, even though that
7376 * would make the command name "hash" a misnomer.
7380 struct tblentry
*next
; /* next entry in hash chain */
7381 union param param
; /* definition of builtin function */
7382 smallint cmdtype
; /* CMDxxx */
7383 char rehash
; /* if set, cd done since entry created */
7384 char cmdname
[1]; /* name of command */
7387 static struct tblentry
**cmdtable
;
7388 #define INIT_G_cmdtable() do { \
7389 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7392 static int builtinloc
= -1; /* index in path of %builtin, or -1 */
7396 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no
,) char *cmd
, char **argv
, char **envp
)
7398 #if ENABLE_FEATURE_SH_STANDALONE
7399 if (applet_no
>= 0) {
7400 if (APPLET_IS_NOEXEC(applet_no
)) {
7404 run_applet_no_and_exit(applet_no
, argv
);
7406 /* re-exec ourselves with the new arguments */
7407 execve(bb_busybox_exec_path
, argv
, envp
);
7408 /* If they called chroot or otherwise made the binary no longer
7409 * executable, fall through */
7416 execve(cmd
, argv
, envp
);
7417 } while (errno
== EINTR
);
7419 execve(cmd
, argv
, envp
);
7421 if (cmd
== (char*) bb_busybox_exec_path
) {
7425 if (errno
== ENOEXEC
) {
7429 for (ap
= argv
; *ap
; ap
++)
7431 new = ckmalloc((ap
- argv
+ 2) * sizeof(new[0]));
7432 new[0] = (char*) "ash";
7435 while ((*ap
++ = *++argv
) != NULL
)
7437 cmd
= (char*) bb_busybox_exec_path
;
7444 * Exec a program. Never returns. If you change this routine, you may
7445 * have to change the find_command routine as well.
7447 static void shellexec(char **, const char *, int) NORETURN
;
7449 shellexec(char **argv
, const char *path
, int idx
)
7455 int applet_no
= -1; /* used only by FEATURE_SH_STANDALONE */
7457 clearredir(/*drop:*/ 1);
7458 envp
= listvars(VEXPORT
, VUNSET
, /*end:*/ NULL
);
7459 if (strchr(argv
[0], '/') != NULL
7460 #if ENABLE_FEATURE_SH_STANDALONE
7461 || (applet_no
= find_applet_by_name(argv
[0])) >= 0
7464 tryexec(IF_FEATURE_SH_STANDALONE(applet_no
,) argv
[0], argv
, envp
);
7465 if (applet_no
>= 0) {
7466 /* We tried execing ourself, but it didn't work.
7467 * Maybe /proc/self/exe doesn't exist?
7476 while ((cmdname
= path_advance(&path
, argv
[0])) != NULL
) {
7477 if (--idx
< 0 && pathopt
== NULL
) {
7478 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname
, argv
, envp
);
7479 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
7486 /* Map to POSIX errors */
7498 exitstatus
= exerrno
;
7499 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7500 argv
[0], e
, suppress_int
));
7501 ash_msg_and_raise(EXEXEC
, "%s: %s", argv
[0], errmsg(e
, "not found"));
7506 printentry(struct tblentry
*cmdp
)
7512 idx
= cmdp
->param
.index
;
7515 name
= path_advance(&path
, cmdp
->cmdname
);
7517 } while (--idx
>= 0);
7518 out1fmt("%s%s\n", name
, (cmdp
->rehash
? "*" : nullstr
));
7522 * Clear out command entries. The argument specifies the first entry in
7523 * PATH which has changed.
7526 clearcmdentry(int firstchange
)
7528 struct tblentry
**tblp
;
7529 struct tblentry
**pp
;
7530 struct tblentry
*cmdp
;
7533 for (tblp
= cmdtable
; tblp
< &cmdtable
[CMDTABLESIZE
]; tblp
++) {
7535 while ((cmdp
= *pp
) != NULL
) {
7536 if ((cmdp
->cmdtype
== CMDNORMAL
&&
7537 cmdp
->param
.index
>= firstchange
)
7538 || (cmdp
->cmdtype
== CMDBUILTIN
&&
7539 builtinloc
>= firstchange
)
7552 * Locate a command in the command hash table. If "add" is nonzero,
7553 * add the command to the table if it is not already present. The
7554 * variable "lastcmdentry" is set to point to the address of the link
7555 * pointing to the entry, so that delete_cmd_entry can delete the
7558 * Interrupts must be off if called with add != 0.
7560 static struct tblentry
**lastcmdentry
;
7562 static struct tblentry
*
7563 cmdlookup(const char *name
, int add
)
7565 unsigned int hashval
;
7567 struct tblentry
*cmdp
;
7568 struct tblentry
**pp
;
7571 hashval
= (unsigned char)*p
<< 4;
7573 hashval
+= (unsigned char)*p
++;
7575 pp
= &cmdtable
[hashval
% CMDTABLESIZE
];
7576 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
7577 if (strcmp(cmdp
->cmdname
, name
) == 0)
7581 if (add
&& cmdp
== NULL
) {
7582 cmdp
= *pp
= ckzalloc(sizeof(struct tblentry
)
7584 /* + 1 - already done because
7585 * tblentry::cmdname is char[1] */);
7586 /*cmdp->next = NULL; - ckzalloc did it */
7587 cmdp
->cmdtype
= CMDUNKNOWN
;
7588 strcpy(cmdp
->cmdname
, name
);
7595 * Delete the command entry returned on the last lookup.
7598 delete_cmd_entry(void)
7600 struct tblentry
*cmdp
;
7603 cmdp
= *lastcmdentry
;
7604 *lastcmdentry
= cmdp
->next
;
7605 if (cmdp
->cmdtype
== CMDFUNCTION
)
7606 freefunc(cmdp
->param
.func
);
7612 * Add a new command entry, replacing any existing command entry for
7613 * the same name - except special builtins.
7616 addcmdentry(char *name
, struct cmdentry
*entry
)
7618 struct tblentry
*cmdp
;
7620 cmdp
= cmdlookup(name
, 1);
7621 if (cmdp
->cmdtype
== CMDFUNCTION
) {
7622 freefunc(cmdp
->param
.func
);
7624 cmdp
->cmdtype
= entry
->cmdtype
;
7625 cmdp
->param
= entry
->u
;
7629 static int FAST_FUNC
7630 hashcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
7632 struct tblentry
**pp
;
7633 struct tblentry
*cmdp
;
7635 struct cmdentry entry
;
7638 if (nextopt("r") != '\0') {
7643 if (*argptr
== NULL
) {
7644 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
]; pp
++) {
7645 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
7646 if (cmdp
->cmdtype
== CMDNORMAL
)
7654 while ((name
= *argptr
) != NULL
) {
7655 cmdp
= cmdlookup(name
, 0);
7657 && (cmdp
->cmdtype
== CMDNORMAL
7658 || (cmdp
->cmdtype
== CMDBUILTIN
&& builtinloc
>= 0))
7662 find_command(name
, &entry
, DO_ERR
, pathval());
7663 if (entry
.cmdtype
== CMDUNKNOWN
)
7671 * Called when a cd is done. Marks all commands so the next time they
7672 * are executed they will be rehashed.
7677 struct tblentry
**pp
;
7678 struct tblentry
*cmdp
;
7680 for (pp
= cmdtable
; pp
< &cmdtable
[CMDTABLESIZE
]; pp
++) {
7681 for (cmdp
= *pp
; cmdp
; cmdp
= cmdp
->next
) {
7682 if (cmdp
->cmdtype
== CMDNORMAL
7683 || (cmdp
->cmdtype
== CMDBUILTIN
7684 && !IS_BUILTIN_REGULAR(cmdp
->param
.cmd
)
7694 * Fix command hash table when PATH changed.
7695 * Called before PATH is changed. The argument is the new value of PATH;
7696 * pathval() still returns the old value at this point.
7697 * Called with interrupts off.
7699 static void FAST_FUNC
7700 changepath(const char *new)
7708 firstchange
= 9999; /* assume no change */
7714 if ((*old
== '\0' && *new == ':')
7715 || (*old
== ':' && *new == '\0')
7719 old
= new; /* ignore subsequent differences */
7723 if (*new == '%' && idx_bltin
< 0 && prefix(new + 1, "builtin"))
7730 if (builtinloc
< 0 && idx_bltin
>= 0)
7731 builtinloc
= idx_bltin
; /* zap builtins */
7732 if (builtinloc
>= 0 && idx_bltin
< 0)
7734 clearcmdentry(firstchange
);
7735 builtinloc
= idx_bltin
;
7750 #define TENDBQUOTE 12
7767 typedef smallint token_id_t
;
7769 /* first char is indicating which tokens mark the end of a list */
7770 static const char *const tokname_array
[] = {
7784 #define KWDOFFSET 13
7785 /* the following are keywords */
7804 /* Wrapper around strcmp for qsort/bsearch/... */
7806 pstrcmp(const void *a
, const void *b
)
7808 return strcmp((char*) a
, (*(char**) b
) + 1);
7811 static const char *const *
7812 findkwd(const char *s
)
7814 return bsearch(s
, tokname_array
+ KWDOFFSET
,
7815 ARRAY_SIZE(tokname_array
) - KWDOFFSET
,
7816 sizeof(tokname_array
[0]), pstrcmp
);
7820 * Locate and print what a word is...
7823 describe_command(char *command
, int describe_command_verbose
)
7825 struct cmdentry entry
;
7826 struct tblentry
*cmdp
;
7827 #if ENABLE_ASH_ALIAS
7828 const struct alias
*ap
;
7830 const char *path
= pathval();
7832 if (describe_command_verbose
) {
7836 /* First look at the keywords */
7837 if (findkwd(command
)) {
7838 out1str(describe_command_verbose
? " is a shell keyword" : command
);
7842 #if ENABLE_ASH_ALIAS
7843 /* Then look at the aliases */
7844 ap
= lookupalias(command
, 0);
7846 if (!describe_command_verbose
) {
7851 out1fmt(" is an alias for %s", ap
->val
);
7855 /* Then check if it is a tracked alias */
7856 cmdp
= cmdlookup(command
, 0);
7858 entry
.cmdtype
= cmdp
->cmdtype
;
7859 entry
.u
= cmdp
->param
;
7861 /* Finally use brute force */
7862 find_command(command
, &entry
, DO_ABS
, path
);
7865 switch (entry
.cmdtype
) {
7867 int j
= entry
.u
.index
;
7873 p
= path_advance(&path
, command
);
7877 if (describe_command_verbose
) {
7879 (cmdp
? " a tracked alias for" : nullstr
), p
7888 if (describe_command_verbose
) {
7889 out1str(" is a shell function");
7896 if (describe_command_verbose
) {
7897 out1fmt(" is a %sshell builtin",
7898 IS_BUILTIN_SPECIAL(entry
.u
.cmd
) ?
7899 "special " : nullstr
7907 if (describe_command_verbose
) {
7908 out1str(": not found\n");
7917 static int FAST_FUNC
7918 typecmd(int argc UNUSED_PARAM
, char **argv
)
7924 /* type -p ... ? (we don't bother checking for 'p') */
7925 if (argv
[1] && argv
[1][0] == '-') {
7930 err
|= describe_command(argv
[i
++], verbose
);
7935 #if ENABLE_ASH_CMDCMD
7936 static int FAST_FUNC
7937 commandcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
7945 while ((c
= nextopt("pvV")) != '\0')
7947 verify
|= VERIFY_VERBOSE
;
7949 verify
|= VERIFY_BRIEF
;
7954 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7955 if (verify
&& (*argptr
!= NULL
)) {
7956 return describe_command(*argptr
, verify
- VERIFY_BRIEF
);
7964 /* ============ eval.c */
7966 static int funcblocksize
; /* size of structures in function */
7967 static int funcstringsize
; /* size of strings in node */
7968 static void *funcblock
; /* block to allocate function from */
7969 static char *funcstring
; /* block to allocate strings from */
7971 /* flags in argument to evaltree */
7972 #define EV_EXIT 01 /* exit after evaluating tree */
7973 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7974 #define EV_BACKCMD 04 /* command executing within back quotes */
7976 static const uint8_t nodesize
[N_NUMBER
] = {
7977 [NCMD
] = SHELL_ALIGN(sizeof(struct ncmd
)),
7978 [NPIPE
] = SHELL_ALIGN(sizeof(struct npipe
)),
7979 [NREDIR
] = SHELL_ALIGN(sizeof(struct nredir
)),
7980 [NBACKGND
] = SHELL_ALIGN(sizeof(struct nredir
)),
7981 [NSUBSHELL
] = SHELL_ALIGN(sizeof(struct nredir
)),
7982 [NAND
] = SHELL_ALIGN(sizeof(struct nbinary
)),
7983 [NOR
] = SHELL_ALIGN(sizeof(struct nbinary
)),
7984 [NSEMI
] = SHELL_ALIGN(sizeof(struct nbinary
)),
7985 [NIF
] = SHELL_ALIGN(sizeof(struct nif
)),
7986 [NWHILE
] = SHELL_ALIGN(sizeof(struct nbinary
)),
7987 [NUNTIL
] = SHELL_ALIGN(sizeof(struct nbinary
)),
7988 [NFOR
] = SHELL_ALIGN(sizeof(struct nfor
)),
7989 [NCASE
] = SHELL_ALIGN(sizeof(struct ncase
)),
7990 [NCLIST
] = SHELL_ALIGN(sizeof(struct nclist
)),
7991 [NDEFUN
] = SHELL_ALIGN(sizeof(struct narg
)),
7992 [NARG
] = SHELL_ALIGN(sizeof(struct narg
)),
7993 [NTO
] = SHELL_ALIGN(sizeof(struct nfile
)),
7994 #if ENABLE_ASH_BASH_COMPAT
7995 [NTO2
] = SHELL_ALIGN(sizeof(struct nfile
)),
7997 [NCLOBBER
] = SHELL_ALIGN(sizeof(struct nfile
)),
7998 [NFROM
] = SHELL_ALIGN(sizeof(struct nfile
)),
7999 [NFROMTO
] = SHELL_ALIGN(sizeof(struct nfile
)),
8000 [NAPPEND
] = SHELL_ALIGN(sizeof(struct nfile
)),
8001 [NTOFD
] = SHELL_ALIGN(sizeof(struct ndup
)),
8002 [NFROMFD
] = SHELL_ALIGN(sizeof(struct ndup
)),
8003 [NHERE
] = SHELL_ALIGN(sizeof(struct nhere
)),
8004 [NXHERE
] = SHELL_ALIGN(sizeof(struct nhere
)),
8005 [NNOT
] = SHELL_ALIGN(sizeof(struct nnot
)),
8008 static void calcsize(union node
*n
);
8011 sizenodelist(struct nodelist
*lp
)
8014 funcblocksize
+= SHELL_ALIGN(sizeof(struct nodelist
));
8021 calcsize(union node
*n
)
8025 funcblocksize
+= nodesize
[n
->type
];
8028 calcsize(n
->ncmd
.redirect
);
8029 calcsize(n
->ncmd
.args
);
8030 calcsize(n
->ncmd
.assign
);
8033 sizenodelist(n
->npipe
.cmdlist
);
8038 calcsize(n
->nredir
.redirect
);
8039 calcsize(n
->nredir
.n
);
8046 calcsize(n
->nbinary
.ch2
);
8047 calcsize(n
->nbinary
.ch1
);
8050 calcsize(n
->nif
.elsepart
);
8051 calcsize(n
->nif
.ifpart
);
8052 calcsize(n
->nif
.test
);
8055 funcstringsize
+= strlen(n
->nfor
.var
) + 1;
8056 calcsize(n
->nfor
.body
);
8057 calcsize(n
->nfor
.args
);
8060 calcsize(n
->ncase
.cases
);
8061 calcsize(n
->ncase
.expr
);
8064 calcsize(n
->nclist
.body
);
8065 calcsize(n
->nclist
.pattern
);
8066 calcsize(n
->nclist
.next
);
8070 sizenodelist(n
->narg
.backquote
);
8071 funcstringsize
+= strlen(n
->narg
.text
) + 1;
8072 calcsize(n
->narg
.next
);
8075 #if ENABLE_ASH_BASH_COMPAT
8082 calcsize(n
->nfile
.fname
);
8083 calcsize(n
->nfile
.next
);
8087 calcsize(n
->ndup
.vname
);
8088 calcsize(n
->ndup
.next
);
8092 calcsize(n
->nhere
.doc
);
8093 calcsize(n
->nhere
.next
);
8096 calcsize(n
->nnot
.com
);
8102 nodeckstrdup(char *s
)
8104 char *rtn
= funcstring
;
8106 strcpy(funcstring
, s
);
8107 funcstring
+= strlen(s
) + 1;
8111 static union node
*copynode(union node
*);
8113 static struct nodelist
*
8114 copynodelist(struct nodelist
*lp
)
8116 struct nodelist
*start
;
8117 struct nodelist
**lpp
;
8122 funcblock
= (char *) funcblock
+ SHELL_ALIGN(sizeof(struct nodelist
));
8123 (*lpp
)->n
= copynode(lp
->n
);
8125 lpp
= &(*lpp
)->next
;
8132 copynode(union node
*n
)
8139 funcblock
= (char *) funcblock
+ nodesize
[n
->type
];
8143 new->ncmd
.redirect
= copynode(n
->ncmd
.redirect
);
8144 new->ncmd
.args
= copynode(n
->ncmd
.args
);
8145 new->ncmd
.assign
= copynode(n
->ncmd
.assign
);
8148 new->npipe
.cmdlist
= copynodelist(n
->npipe
.cmdlist
);
8149 new->npipe
.pipe_backgnd
= n
->npipe
.pipe_backgnd
;
8154 new->nredir
.redirect
= copynode(n
->nredir
.redirect
);
8155 new->nredir
.n
= copynode(n
->nredir
.n
);
8162 new->nbinary
.ch2
= copynode(n
->nbinary
.ch2
);
8163 new->nbinary
.ch1
= copynode(n
->nbinary
.ch1
);
8166 new->nif
.elsepart
= copynode(n
->nif
.elsepart
);
8167 new->nif
.ifpart
= copynode(n
->nif
.ifpart
);
8168 new->nif
.test
= copynode(n
->nif
.test
);
8171 new->nfor
.var
= nodeckstrdup(n
->nfor
.var
);
8172 new->nfor
.body
= copynode(n
->nfor
.body
);
8173 new->nfor
.args
= copynode(n
->nfor
.args
);
8176 new->ncase
.cases
= copynode(n
->ncase
.cases
);
8177 new->ncase
.expr
= copynode(n
->ncase
.expr
);
8180 new->nclist
.body
= copynode(n
->nclist
.body
);
8181 new->nclist
.pattern
= copynode(n
->nclist
.pattern
);
8182 new->nclist
.next
= copynode(n
->nclist
.next
);
8186 new->narg
.backquote
= copynodelist(n
->narg
.backquote
);
8187 new->narg
.text
= nodeckstrdup(n
->narg
.text
);
8188 new->narg
.next
= copynode(n
->narg
.next
);
8191 #if ENABLE_ASH_BASH_COMPAT
8198 new->nfile
.fname
= copynode(n
->nfile
.fname
);
8199 new->nfile
.fd
= n
->nfile
.fd
;
8200 new->nfile
.next
= copynode(n
->nfile
.next
);
8204 new->ndup
.vname
= copynode(n
->ndup
.vname
);
8205 new->ndup
.dupfd
= n
->ndup
.dupfd
;
8206 new->ndup
.fd
= n
->ndup
.fd
;
8207 new->ndup
.next
= copynode(n
->ndup
.next
);
8211 new->nhere
.doc
= copynode(n
->nhere
.doc
);
8212 new->nhere
.fd
= n
->nhere
.fd
;
8213 new->nhere
.next
= copynode(n
->nhere
.next
);
8216 new->nnot
.com
= copynode(n
->nnot
.com
);
8219 new->type
= n
->type
;
8224 * Make a copy of a parse tree.
8226 static struct funcnode
*
8227 copyfunc(union node
*n
)
8232 funcblocksize
= offsetof(struct funcnode
, n
);
8235 blocksize
= funcblocksize
;
8236 f
= ckmalloc(blocksize
+ funcstringsize
);
8237 funcblock
= (char *) f
+ offsetof(struct funcnode
, n
);
8238 funcstring
= (char *) f
+ blocksize
;
8245 * Define a shell function.
8248 defun(char *name
, union node
*func
)
8250 struct cmdentry entry
;
8253 entry
.cmdtype
= CMDFUNCTION
;
8254 entry
.u
.func
= copyfunc(func
);
8255 addcmdentry(name
, &entry
);
8259 /* Reasons for skipping commands (see comment on breakcmd routine) */
8260 #define SKIPBREAK (1 << 0)
8261 #define SKIPCONT (1 << 1)
8262 #define SKIPFUNC (1 << 2)
8263 #define SKIPFILE (1 << 3)
8264 #define SKIPEVAL (1 << 4)
8265 static smallint evalskip
; /* set to SKIPxxx if we are skipping commands */
8266 static int skipcount
; /* number of levels to skip */
8267 static int funcnest
; /* depth of function calls */
8268 static int loopnest
; /* current loop nesting level */
8270 /* Forward decl way out to parsing code - dotrap needs it */
8271 static int evalstring(char *s
, int mask
);
8273 /* Called to execute a trap.
8274 * Single callsite - at the end of evaltree().
8275 * If we return non-zero, evaltree raises EXEXIT exception.
8277 * Perhaps we should avoid entering new trap handlers
8278 * while we are executing a trap handler. [is it a TODO?]
8287 savestatus
= exitstatus
;
8291 TRACE(("dotrap entered\n"));
8292 for (sig
= 1, g
= gotsig
; sig
< NSIG
; sig
++, g
++) {
8299 /* non-trapped SIGINT is handled separately by raise_interrupt,
8300 * don't upset it by resetting gotsig[SIGINT-1] */
8301 if (sig
== SIGINT
&& !t
)
8304 TRACE(("sig %d is active, will run handler '%s'\n", sig
, t
));
8308 want_exexit
= evalstring(t
, SKIPEVAL
);
8309 exitstatus
= savestatus
;
8311 TRACE(("dotrap returns %d\n", want_exexit
));
8316 TRACE(("dotrap returns 0\n"));
8320 /* forward declarations - evaluation is fairly recursive business... */
8321 static void evalloop(union node
*, int);
8322 static void evalfor(union node
*, int);
8323 static void evalcase(union node
*, int);
8324 static void evalsubshell(union node
*, int);
8325 static void expredir(union node
*);
8326 static void evalpipe(union node
*, int);
8327 static void evalcommand(union node
*, int);
8328 static int evalbltin(const struct builtincmd
*, int, char **);
8329 static void prehash(union node
*);
8332 * Evaluate a parse tree. The value is left in the global variable
8336 evaltree(union node
*n
, int flags
)
8338 struct jmploc
*volatile savehandler
= exception_handler
;
8339 struct jmploc jmploc
;
8341 void (*evalfn
)(union node
*, int);
8345 SAVE_INT(int_level
);
8348 TRACE(("evaltree(NULL) called\n"));
8351 TRACE(("evaltree(%p: %d, %d) called\n", n
, n
->type
, flags
));
8353 exception_handler
= &jmploc
;
8355 int err
= setjmp(jmploc
.loc
);
8357 /* if it was a signal, check for trap handlers */
8358 if (exception_type
== EXSIG
) {
8359 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8360 exception_type
, err
));
8363 /* continue on the way out */
8364 TRACE(("exception %d in evaltree, propagating err=%d\n",
8365 exception_type
, err
));
8366 exception_handler
= savehandler
;
8367 longjmp(exception_handler
->loc
, err
);
8374 out1fmt("Node type = %d\n", n
->type
);
8379 evaltree(n
->nnot
.com
, EV_TESTED
);
8380 status
= !exitstatus
;
8383 expredir(n
->nredir
.redirect
);
8384 status
= redirectsafe(n
->nredir
.redirect
, REDIR_PUSH
);
8386 evaltree(n
->nredir
.n
, flags
& EV_TESTED
);
8387 status
= exitstatus
;
8389 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8392 evalfn
= evalcommand
;
8394 if (eflag
&& !(flags
& EV_TESTED
))
8406 evalfn
= evalsubshell
;
8419 #error NAND + 1 != NOR
8421 #if NOR + 1 != NSEMI
8422 #error NOR + 1 != NSEMI
8424 unsigned is_or
= n
->type
- NAND
;
8427 (flags
| ((is_or
>> 1) - 1)) & EV_TESTED
8429 if (!exitstatus
== is_or
)
8442 evaltree(n
->nif
.test
, EV_TESTED
);
8445 if (exitstatus
== 0) {
8449 if (n
->nif
.elsepart
) {
8450 n
= n
->nif
.elsepart
;
8455 defun(n
->narg
.text
, n
->narg
.next
);
8459 exitstatus
= status
;
8464 exception_handler
= savehandler
;
8467 /* Order of checks below is important:
8468 * signal handlers trigger before exit caused by "set -e".
8470 if (pending_sig
&& dotrap())
8472 if (checkexit
& exitstatus
)
8473 evalskip
|= SKIPEVAL
;
8475 if (flags
& EV_EXIT
) {
8477 raise_exception(EXEXIT
);
8480 RESTORE_INT(int_level
);
8481 TRACE(("leaving evaltree (no interrupts)\n"));
8484 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8487 void evaltreenr(union node
*, int) __attribute__ ((alias("evaltree"),__noreturn__
));
8490 evalloop(union node
*n
, int flags
)
8500 evaltree(n
->nbinary
.ch1
, EV_TESTED
);
8503 if (evalskip
== SKIPCONT
&& --skipcount
<= 0) {
8507 if (evalskip
== SKIPBREAK
&& --skipcount
<= 0)
8512 if (n
->type
!= NWHILE
)
8516 evaltree(n
->nbinary
.ch2
, flags
);
8517 status
= exitstatus
;
8522 exitstatus
= status
;
8526 evalfor(union node
*n
, int flags
)
8528 struct arglist arglist
;
8531 struct stackmark smark
;
8533 setstackmark(&smark
);
8534 arglist
.list
= NULL
;
8535 arglist
.lastp
= &arglist
.list
;
8536 for (argp
= n
->nfor
.args
; argp
; argp
= argp
->narg
.next
) {
8537 expandarg(argp
, &arglist
, EXP_FULL
| EXP_TILDE
| EXP_RECORD
);
8542 *arglist
.lastp
= NULL
;
8547 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
8548 setvar(n
->nfor
.var
, sp
->text
, 0);
8549 evaltree(n
->nfor
.body
, flags
);
8551 if (evalskip
== SKIPCONT
&& --skipcount
<= 0) {
8555 if (evalskip
== SKIPBREAK
&& --skipcount
<= 0)
8562 popstackmark(&smark
);
8566 evalcase(union node
*n
, int flags
)
8570 struct arglist arglist
;
8571 struct stackmark smark
;
8573 setstackmark(&smark
);
8574 arglist
.list
= NULL
;
8575 arglist
.lastp
= &arglist
.list
;
8576 expandarg(n
->ncase
.expr
, &arglist
, EXP_TILDE
);
8578 for (cp
= n
->ncase
.cases
; cp
&& evalskip
== 0; cp
= cp
->nclist
.next
) {
8579 for (patp
= cp
->nclist
.pattern
; patp
; patp
= patp
->narg
.next
) {
8580 if (casematch(patp
, arglist
.list
->text
)) {
8581 if (evalskip
== 0) {
8582 evaltree(cp
->nclist
.body
, flags
);
8589 popstackmark(&smark
);
8593 * Kick off a subshell to evaluate a tree.
8596 evalsubshell(union node
*n
, int flags
)
8599 int backgnd
= (n
->type
== NBACKGND
);
8602 expredir(n
->nredir
.redirect
);
8603 if (!backgnd
&& (flags
& EV_EXIT
) && !may_have_traps
)
8606 jp
= makejob(/*n,*/ 1);
8607 if (forkshell(jp
, n
, backgnd
) == 0) {
8612 flags
&= ~EV_TESTED
;
8614 redirect(n
->nredir
.redirect
, 0);
8615 evaltreenr(n
->nredir
.n
, flags
);
8620 status
= waitforjob(jp
);
8621 exitstatus
= status
;
8626 * Compute the names of the files in a redirection list.
8628 static void fixredir(union node
*, const char *, int);
8630 expredir(union node
*n
)
8634 for (redir
= n
; redir
; redir
= redir
->nfile
.next
) {
8638 fn
.lastp
= &fn
.list
;
8639 switch (redir
->type
) {
8643 #if ENABLE_ASH_BASH_COMPAT
8648 expandarg(redir
->nfile
.fname
, &fn
, EXP_TILDE
| EXP_REDIR
);
8649 #if ENABLE_ASH_BASH_COMPAT
8652 redir
->nfile
.expfname
= fn
.list
->text
;
8655 case NTOFD
: /* >& */
8656 if (redir
->ndup
.vname
) {
8657 expandarg(redir
->ndup
.vname
, &fn
, EXP_FULL
| EXP_TILDE
);
8658 if (fn
.list
== NULL
)
8659 ash_msg_and_raise_error("redir error");
8660 #if ENABLE_ASH_BASH_COMPAT
8661 //FIXME: we used expandarg with different args!
8662 if (!isdigit_str9(fn
.list
->text
)) {
8663 /* >&file, not >&fd */
8664 if (redir
->nfile
.fd
!= 1) /* 123>&file - BAD */
8665 ash_msg_and_raise_error("redir error");
8667 goto store_expfname
;
8670 fixredir(redir
, fn
.list
->text
, 1);
8678 * Evaluate a pipeline. All the processes in the pipeline are children
8679 * of the process creating the pipeline. (This differs from some versions
8680 * of the shell, which make the last process in a pipeline the parent
8684 evalpipe(union node
*n
, int flags
)
8687 struct nodelist
*lp
;
8692 TRACE(("evalpipe(0x%lx) called\n", (long)n
));
8694 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
)
8698 jp
= makejob(/*n,*/ pipelen
);
8700 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
) {
8704 if (pipe(pip
) < 0) {
8706 ash_msg_and_raise_error("pipe call failed");
8709 if (forkshell(jp
, lp
->n
, n
->npipe
.pipe_backgnd
) == 0) {
8722 evaltreenr(lp
->n
, flags
);
8728 /* Don't want to trigger debugging */
8732 if (n
->npipe
.pipe_backgnd
== 0) {
8733 exitstatus
= waitforjob(jp
);
8734 TRACE(("evalpipe: job done exit status %d\n", exitstatus
));
8740 * Controls whether the shell is interactive or not.
8743 setinteractive(int on
)
8745 static smallint is_interactive
;
8747 if (++on
== is_interactive
)
8749 is_interactive
= on
;
8753 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8754 if (is_interactive
> 1) {
8755 /* Looks like they want an interactive shell */
8756 static smallint did_banner
;
8759 /* note: ash and hush share this string */
8760 out1fmt("\n\n%s %s\n"
8761 "Enter 'help' for a list of built-in commands."
8764 "built-in shell (ash)"
8778 setinteractive(iflag
);
8780 #if ENABLE_FEATURE_EDITING_VI
8782 line_input_state
->flags
|= VI_MODE
;
8784 line_input_state
->flags
&= ~VI_MODE
;
8786 viflag
= 0; /* forcibly keep the option off */
8790 static struct localvar
*localvars
;
8793 * Called after a function returns.
8794 * Interrupts must be off.
8799 struct localvar
*lvp
;
8802 while ((lvp
= localvars
) != NULL
) {
8803 localvars
= lvp
->next
;
8805 TRACE(("poplocalvar %s\n", vp
? vp
->var_text
: "-"));
8806 if (vp
== NULL
) { /* $- saved */
8807 memcpy(optlist
, lvp
->text
, sizeof(optlist
));
8808 free((char*)lvp
->text
);
8810 } else if ((lvp
->flags
& (VUNSET
|VSTRFIXED
)) == VUNSET
) {
8811 unsetvar(vp
->var_text
);
8814 vp
->var_func(var_end(lvp
->text
));
8815 if ((vp
->flags
& (VTEXTFIXED
|VSTACK
)) == 0)
8816 free((char*)vp
->var_text
);
8817 vp
->flags
= lvp
->flags
;
8818 vp
->var_text
= lvp
->text
;
8825 evalfun(struct funcnode
*func
, int argc
, char **argv
, int flags
)
8827 volatile struct shparam saveparam
;
8828 struct localvar
*volatile savelocalvars
;
8829 struct jmploc
*volatile savehandler
;
8830 struct jmploc jmploc
;
8833 saveparam
= shellparam
;
8834 savelocalvars
= localvars
;
8835 e
= setjmp(jmploc
.loc
);
8840 savehandler
= exception_handler
;
8841 exception_handler
= &jmploc
;
8843 shellparam
.malloced
= 0;
8847 shellparam
.nparam
= argc
- 1;
8848 shellparam
.p
= argv
+ 1;
8849 #if ENABLE_ASH_GETOPTS
8850 shellparam
.optind
= 1;
8851 shellparam
.optoff
= -1;
8853 evaltree(&func
->n
, flags
& EV_TESTED
);
8859 localvars
= savelocalvars
;
8860 freeparam(&shellparam
);
8861 shellparam
= saveparam
;
8862 exception_handler
= savehandler
;
8864 evalskip
&= ~SKIPFUNC
;
8868 #if ENABLE_ASH_CMDCMD
8870 parse_command_args(char **argv
, const char **path
)
8883 if (c
== '-' && !*cp
) {
8890 *path
= bb_default_path
;
8893 /* run 'typecmd' for other options */
8904 * Make a variable a local variable. When a variable is made local, it's
8905 * value and flags are saved in a localvar structure. The saved values
8906 * will be restored when the shell function returns. We handle the name
8907 * "-" as a special case.
8912 struct localvar
*lvp
;
8917 lvp
= ckzalloc(sizeof(struct localvar
));
8918 if (LONE_DASH(name
)) {
8920 p
= ckmalloc(sizeof(optlist
));
8921 lvp
->text
= memcpy(p
, optlist
, sizeof(optlist
));
8926 vpp
= hashvar(name
);
8927 vp
= *findvar(vpp
, name
);
8928 eq
= strchr(name
, '=');
8931 setvareq(name
, VSTRFIXED
);
8933 setvar(name
, NULL
, VSTRFIXED
);
8934 vp
= *vpp
; /* the new variable */
8935 lvp
->flags
= VUNSET
;
8937 lvp
->text
= vp
->var_text
;
8938 lvp
->flags
= vp
->flags
;
8939 vp
->flags
|= VSTRFIXED
|VTEXTFIXED
;
8945 lvp
->next
= localvars
;
8951 * The "local" command.
8953 static int FAST_FUNC
8954 localcmd(int argc UNUSED_PARAM
, char **argv
)
8959 while ((name
= *argv
++) != NULL
) {
8965 static int FAST_FUNC
8966 falsecmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
8971 static int FAST_FUNC
8972 truecmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
8977 static int FAST_FUNC
8978 execcmd(int argc UNUSED_PARAM
, char **argv
)
8981 iflag
= 0; /* exit on error */
8984 shellexec(argv
+ 1, pathval(), 0);
8990 * The return command.
8992 static int FAST_FUNC
8993 returncmd(int argc UNUSED_PARAM
, char **argv
)
8996 * If called outside a function, do what ksh does;
8997 * skip the rest of the file.
8999 evalskip
= funcnest
? SKIPFUNC
: SKIPFILE
;
9000 return argv
[1] ? number(argv
[1]) : exitstatus
;
9003 /* Forward declarations for builtintab[] */
9004 static int breakcmd(int, char **) FAST_FUNC
;
9005 static int dotcmd(int, char **) FAST_FUNC
;
9006 static int evalcmd(int, char **) FAST_FUNC
;
9007 static int exitcmd(int, char **) FAST_FUNC
;
9008 static int exportcmd(int, char **) FAST_FUNC
;
9009 #if ENABLE_ASH_GETOPTS
9010 static int getoptscmd(int, char **) FAST_FUNC
;
9012 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9013 static int helpcmd(int, char **) FAST_FUNC
;
9015 #if ENABLE_SH_MATH_SUPPORT
9016 static int letcmd(int, char **) FAST_FUNC
;
9018 static int readcmd(int, char **) FAST_FUNC
;
9019 static int setcmd(int, char **) FAST_FUNC
;
9020 static int shiftcmd(int, char **) FAST_FUNC
;
9021 static int timescmd(int, char **) FAST_FUNC
;
9022 static int trapcmd(int, char **) FAST_FUNC
;
9023 static int umaskcmd(int, char **) FAST_FUNC
;
9024 static int unsetcmd(int, char **) FAST_FUNC
;
9025 static int ulimitcmd(int, char **) FAST_FUNC
;
9027 #define BUILTIN_NOSPEC "0"
9028 #define BUILTIN_SPECIAL "1"
9029 #define BUILTIN_REGULAR "2"
9030 #define BUILTIN_SPEC_REG "3"
9031 #define BUILTIN_ASSIGN "4"
9032 #define BUILTIN_SPEC_ASSG "5"
9033 #define BUILTIN_REG_ASSG "6"
9034 #define BUILTIN_SPEC_REG_ASSG "7"
9036 /* Stubs for calling non-FAST_FUNC's */
9037 #if ENABLE_ASH_BUILTIN_ECHO
9038 static int FAST_FUNC
echocmd(int argc
, char **argv
) { return echo_main(argc
, argv
); }
9040 #if ENABLE_ASH_BUILTIN_PRINTF
9041 static int FAST_FUNC
printfcmd(int argc
, char **argv
) { return printf_main(argc
, argv
); }
9043 #if ENABLE_ASH_BUILTIN_TEST
9044 static int FAST_FUNC
testcmd(int argc
, char **argv
) { return test_main(argc
, argv
); }
9047 /* Keep these in proper order since it is searched via bsearch() */
9048 static const struct builtincmd builtintab
[] = {
9049 { BUILTIN_SPEC_REG
"." , dotcmd
},
9050 { BUILTIN_SPEC_REG
":" , truecmd
},
9051 #if ENABLE_ASH_BUILTIN_TEST
9052 { BUILTIN_REGULAR
"[" , testcmd
},
9053 #if ENABLE_ASH_BASH_COMPAT
9054 { BUILTIN_REGULAR
"[[" , testcmd
},
9057 #if ENABLE_ASH_ALIAS
9058 { BUILTIN_REG_ASSG
"alias" , aliascmd
},
9061 { BUILTIN_REGULAR
"bg" , fg_bgcmd
},
9063 { BUILTIN_SPEC_REG
"break" , breakcmd
},
9064 { BUILTIN_REGULAR
"cd" , cdcmd
},
9065 { BUILTIN_NOSPEC
"chdir" , cdcmd
},
9066 #if ENABLE_ASH_CMDCMD
9067 { BUILTIN_REGULAR
"command" , commandcmd
},
9069 { BUILTIN_SPEC_REG
"continue", breakcmd
},
9070 #if ENABLE_ASH_BUILTIN_ECHO
9071 { BUILTIN_REGULAR
"echo" , echocmd
},
9073 { BUILTIN_SPEC_REG
"eval" , evalcmd
},
9074 { BUILTIN_SPEC_REG
"exec" , execcmd
},
9075 { BUILTIN_SPEC_REG
"exit" , exitcmd
},
9076 { BUILTIN_SPEC_REG_ASSG
"export" , exportcmd
},
9077 { BUILTIN_REGULAR
"false" , falsecmd
},
9079 { BUILTIN_REGULAR
"fg" , fg_bgcmd
},
9081 #if ENABLE_ASH_GETOPTS
9082 { BUILTIN_REGULAR
"getopts" , getoptscmd
},
9084 { BUILTIN_NOSPEC
"hash" , hashcmd
},
9085 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9086 { BUILTIN_NOSPEC
"help" , helpcmd
},
9089 { BUILTIN_REGULAR
"jobs" , jobscmd
},
9090 { BUILTIN_REGULAR
"kill" , killcmd
},
9092 #if ENABLE_SH_MATH_SUPPORT
9093 { BUILTIN_NOSPEC
"let" , letcmd
},
9095 { BUILTIN_ASSIGN
"local" , localcmd
},
9096 #if ENABLE_ASH_BUILTIN_PRINTF
9097 { BUILTIN_REGULAR
"printf" , printfcmd
},
9099 { BUILTIN_NOSPEC
"pwd" , pwdcmd
},
9100 { BUILTIN_REGULAR
"read" , readcmd
},
9101 { BUILTIN_SPEC_REG_ASSG
"readonly", exportcmd
},
9102 { BUILTIN_SPEC_REG
"return" , returncmd
},
9103 { BUILTIN_SPEC_REG
"set" , setcmd
},
9104 { BUILTIN_SPEC_REG
"shift" , shiftcmd
},
9105 #if ENABLE_ASH_BASH_COMPAT
9106 { BUILTIN_SPEC_REG
"source" , dotcmd
},
9108 #if ENABLE_ASH_BUILTIN_TEST
9109 { BUILTIN_REGULAR
"test" , testcmd
},
9111 { BUILTIN_SPEC_REG
"times" , timescmd
},
9112 { BUILTIN_SPEC_REG
"trap" , trapcmd
},
9113 { BUILTIN_REGULAR
"true" , truecmd
},
9114 { BUILTIN_NOSPEC
"type" , typecmd
},
9115 { BUILTIN_NOSPEC
"ulimit" , ulimitcmd
},
9116 { BUILTIN_REGULAR
"umask" , umaskcmd
},
9117 #if ENABLE_ASH_ALIAS
9118 { BUILTIN_REGULAR
"unalias" , unaliascmd
},
9120 { BUILTIN_SPEC_REG
"unset" , unsetcmd
},
9121 { BUILTIN_REGULAR
"wait" , waitcmd
},
9124 /* Should match the above table! */
9125 #define COMMANDCMD (builtintab + \
9127 1 * ENABLE_ASH_BUILTIN_TEST + \
9128 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9129 1 * ENABLE_ASH_ALIAS + \
9130 1 * ENABLE_ASH_JOB_CONTROL + \
9132 #define EXECCMD (builtintab + \
9134 1 * ENABLE_ASH_BUILTIN_TEST + \
9135 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9136 1 * ENABLE_ASH_ALIAS + \
9137 1 * ENABLE_ASH_JOB_CONTROL + \
9139 1 * ENABLE_ASH_CMDCMD + \
9141 ENABLE_ASH_BUILTIN_ECHO + \
9145 * Search the table of builtin commands.
9147 static struct builtincmd
*
9148 find_builtin(const char *name
)
9150 struct builtincmd
*bp
;
9153 name
, builtintab
, ARRAY_SIZE(builtintab
), sizeof(builtintab
[0]),
9160 * Execute a simple command.
9163 isassignment(const char *p
)
9165 const char *q
= endofname(p
);
9170 static int FAST_FUNC
9171 bltincmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
9173 /* Preserve exitstatus of a previous possible redirection
9174 * as POSIX mandates */
9175 return back_exitstatus
;
9178 evalcommand(union node
*cmd
, int flags
)
9180 static const struct builtincmd null_bltin
= {
9181 "\0\0", bltincmd
/* why three NULs? */
9183 struct stackmark smark
;
9185 struct arglist arglist
;
9186 struct arglist varlist
;
9189 const struct strlist
*sp
;
9190 struct cmdentry cmdentry
;
9197 struct builtincmd
*bcmd
;
9198 smallint cmd_is_exec
;
9199 smallint pseudovarflag
= 0;
9201 /* First expand the arguments. */
9202 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd
, flags
));
9203 setstackmark(&smark
);
9204 back_exitstatus
= 0;
9206 cmdentry
.cmdtype
= CMDBUILTIN
;
9207 cmdentry
.u
.cmd
= &null_bltin
;
9208 varlist
.lastp
= &varlist
.list
;
9209 *varlist
.lastp
= NULL
;
9210 arglist
.lastp
= &arglist
.list
;
9211 *arglist
.lastp
= NULL
;
9214 if (cmd
->ncmd
.args
) {
9215 bcmd
= find_builtin(cmd
->ncmd
.args
->narg
.text
);
9216 pseudovarflag
= bcmd
&& IS_BUILTIN_ASSIGN(bcmd
);
9219 for (argp
= cmd
->ncmd
.args
; argp
; argp
= argp
->narg
.next
) {
9220 struct strlist
**spp
;
9222 spp
= arglist
.lastp
;
9223 if (pseudovarflag
&& isassignment(argp
->narg
.text
))
9224 expandarg(argp
, &arglist
, EXP_VARTILDE
);
9226 expandarg(argp
, &arglist
, EXP_FULL
| EXP_TILDE
);
9228 for (sp
= *spp
; sp
; sp
= sp
->next
)
9232 argv
= nargv
= stalloc(sizeof(char *) * (argc
+ 1));
9233 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
9234 TRACE(("evalcommand arg: %s\n", sp
->text
));
9235 *nargv
++ = sp
->text
;
9240 if (iflag
&& funcnest
== 0 && argc
> 0)
9241 lastarg
= nargv
[-1];
9244 expredir(cmd
->ncmd
.redirect
);
9245 status
= redirectsafe(cmd
->ncmd
.redirect
, REDIR_PUSH
| REDIR_SAVEFD2
);
9247 path
= vpath
.var_text
;
9248 for (argp
= cmd
->ncmd
.assign
; argp
; argp
= argp
->narg
.next
) {
9249 struct strlist
**spp
;
9252 spp
= varlist
.lastp
;
9253 expandarg(argp
, &varlist
, EXP_VARTILDE
);
9256 * Modify the command lookup path, if a PATH= assignment
9260 if (varcmp(p
, path
) == 0)
9264 /* Print the command if xflag is set. */
9267 const char *p
= " %s" + 1;
9269 fdprintf(preverrout_fd
, p
, expandstr(ps4val()));
9271 for (n
= 0; n
< 2; n
++) {
9273 fdprintf(preverrout_fd
, p
, sp
->text
);
9279 safe_write(preverrout_fd
, "\n", 1);
9285 /* Now locate the command. */
9287 const char *oldpath
;
9288 int cmd_flag
= DO_ERR
;
9293 find_command(argv
[0], &cmdentry
, cmd_flag
, path
);
9294 if (cmdentry
.cmdtype
== CMDUNKNOWN
) {
9295 flush_stdout_stderr();
9300 /* implement bltin and command here */
9301 if (cmdentry
.cmdtype
!= CMDBUILTIN
)
9304 spclbltin
= IS_BUILTIN_SPECIAL(cmdentry
.u
.cmd
);
9305 if (cmdentry
.u
.cmd
== EXECCMD
)
9307 #if ENABLE_ASH_CMDCMD
9308 if (cmdentry
.u
.cmd
== COMMANDCMD
) {
9310 nargv
= parse_command_args(argv
, &path
);
9313 argc
-= nargv
- argv
;
9315 cmd_flag
|= DO_NOFUNC
;
9323 /* We have a redirection error. */
9325 raise_exception(EXERROR
);
9327 exitstatus
= status
;
9331 /* Execute the command. */
9332 switch (cmdentry
.cmdtype
) {
9335 #if ENABLE_FEATURE_SH_NOFORK
9336 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9337 * around run_nofork_applet() call.
9338 * (2) Should this check also be done in forkshell()?
9339 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9341 /* find_command() encodes applet_no as (-2 - applet_no) */
9342 int applet_no
= (- cmdentry
.u
.index
- 2);
9343 if (applet_no
>= 0 && APPLET_IS_NOFORK(applet_no
)) {
9344 listsetvar(varlist
.list
, VEXPORT
|VSTACK
);
9345 /* run <applet>_main() */
9346 exitstatus
= run_nofork_applet(applet_no
, argv
);
9350 /* Can we avoid forking off? For example, very last command
9351 * in a script or a subshell does not need forking,
9352 * we can just exec it.
9354 if (!(flags
& EV_EXIT
) || may_have_traps
) {
9355 /* No, forking off a child is necessary */
9357 jp
= makejob(/*cmd,*/ 1);
9358 if (forkshell(jp
, cmd
, FORK_FG
) != 0) {
9360 exitstatus
= waitforjob(jp
);
9362 TRACE(("forked child exited with %d\n", exitstatus
));
9367 /* fall through to exec'ing external program */
9369 listsetvar(varlist
.list
, VEXPORT
|VSTACK
);
9370 shellexec(argv
, path
, cmdentry
.u
.index
);
9374 cmdenviron
= varlist
.list
;
9376 struct strlist
*list
= cmdenviron
;
9378 if (spclbltin
> 0 || argc
== 0) {
9380 if (cmd_is_exec
&& argc
> 1)
9383 listsetvar(list
, i
);
9385 /* Tight loop with builtins only:
9386 * "while kill -0 $child; do true; done"
9387 * will never exit even if $child died, unless we do this
9388 * to reap the zombie and make kill detect that it's gone: */
9389 dowait(DOWAIT_NONBLOCK
, NULL
);
9391 if (evalbltin(cmdentry
.u
.cmd
, argc
, argv
)) {
9393 int i
= exception_type
;
9398 exit_status
= 128 + SIGINT
;
9400 exit_status
= 128 + pending_sig
;
9401 exitstatus
= exit_status
;
9402 if (i
== EXINT
|| spclbltin
> 0) {
9404 longjmp(exception_handler
->loc
, 1);
9411 listsetvar(varlist
.list
, 0);
9412 /* See above for the rationale */
9413 dowait(DOWAIT_NONBLOCK
, NULL
);
9414 if (evalfun(cmdentry
.u
.func
, argc
, argv
, flags
))
9421 popredir(/*drop:*/ cmd_is_exec
, /*restore:*/ cmd_is_exec
);
9423 /* dsl: I think this is intended to be used to support
9424 * '_' in 'vi' command mode during line editing...
9425 * However I implemented that within libedit itself.
9427 setvar("_", lastarg
, 0);
9429 popstackmark(&smark
);
9433 evalbltin(const struct builtincmd
*cmd
, int argc
, char **argv
)
9435 char *volatile savecmdname
;
9436 struct jmploc
*volatile savehandler
;
9437 struct jmploc jmploc
;
9440 savecmdname
= commandname
;
9441 i
= setjmp(jmploc
.loc
);
9444 savehandler
= exception_handler
;
9445 exception_handler
= &jmploc
;
9446 commandname
= argv
[0];
9448 optptr
= NULL
; /* initialize nextopt */
9449 exitstatus
= (*cmd
->builtin
)(argc
, argv
);
9450 flush_stdout_stderr();
9452 exitstatus
|= ferror(stdout
);
9454 commandname
= savecmdname
;
9455 exception_handler
= savehandler
;
9461 goodname(const char *p
)
9463 return endofname(p
)[0] == '\0';
9468 * Search for a command. This is called before we fork so that the
9469 * location of the command will be available in the parent as well as
9470 * the child. The check for "goodname" is an overly conservative
9471 * check that the name will not be subject to expansion.
9474 prehash(union node
*n
)
9476 struct cmdentry entry
;
9478 if (n
->type
== NCMD
&& n
->ncmd
.args
&& goodname(n
->ncmd
.args
->narg
.text
))
9479 find_command(n
->ncmd
.args
->narg
.text
, &entry
, 0, pathval());
9483 /* ============ Builtin commands
9485 * Builtin commands whose functions are closely tied to evaluation
9486 * are implemented here.
9490 * Handle break and continue commands. Break, continue, and return are
9491 * all handled by setting the evalskip flag. The evaluation routines
9492 * above all check this flag, and if it is set they start skipping
9493 * commands rather than executing them. The variable skipcount is
9494 * the number of loops to break/continue, or the number of function
9495 * levels to return. (The latter is always 1.) It should probably
9496 * be an error to break out of more loops than exist, but it isn't
9497 * in the standard shell so we don't make it one here.
9499 static int FAST_FUNC
9500 breakcmd(int argc UNUSED_PARAM
, char **argv
)
9502 int n
= argv
[1] ? number(argv
[1]) : 1;
9505 ash_msg_and_raise_error(msg_illnum
, argv
[1]);
9509 evalskip
= (**argv
== 'c') ? SKIPCONT
: SKIPBREAK
;
9516 /* ============ input.c
9518 * This implements the input routines used by the parser.
9522 INPUT_PUSH_FILE
= 1,
9523 INPUT_NOFILE_OK
= 2,
9526 static smallint checkkwd
;
9527 /* values of checkkwd variable */
9528 #define CHKALIAS 0x1
9533 * Push a string back onto the input at this current parsefile level.
9534 * We handle aliases this way.
9536 #if !ENABLE_ASH_ALIAS
9537 #define pushstring(s, ap) pushstring(s)
9540 pushstring(char *s
, struct alias
*ap
)
9547 if (g_parsefile
->strpush
) {
9548 sp
= ckzalloc(sizeof(*sp
));
9549 sp
->prev
= g_parsefile
->strpush
;
9551 sp
= &(g_parsefile
->basestrpush
);
9553 g_parsefile
->strpush
= sp
;
9554 sp
->prev_string
= g_parsefile
->next_to_pgetc
;
9555 sp
->prev_left_in_line
= g_parsefile
->left_in_line
;
9556 #if ENABLE_ASH_ALIAS
9559 ap
->flag
|= ALIASINUSE
;
9563 g_parsefile
->next_to_pgetc
= s
;
9564 g_parsefile
->left_in_line
= len
;
9571 struct strpush
*sp
= g_parsefile
->strpush
;
9574 #if ENABLE_ASH_ALIAS
9576 if (g_parsefile
->next_to_pgetc
[-1] == ' '
9577 || g_parsefile
->next_to_pgetc
[-1] == '\t'
9579 checkkwd
|= CHKALIAS
;
9581 if (sp
->string
!= sp
->ap
->val
) {
9584 sp
->ap
->flag
&= ~ALIASINUSE
;
9585 if (sp
->ap
->flag
& ALIASDEAD
) {
9586 unalias(sp
->ap
->name
);
9590 g_parsefile
->next_to_pgetc
= sp
->prev_string
;
9591 g_parsefile
->left_in_line
= sp
->prev_left_in_line
;
9592 g_parsefile
->strpush
= sp
->prev
;
9593 if (sp
!= &(g_parsefile
->basestrpush
))
9598 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9599 //it peeks whether it is &>, and then pushes back both chars.
9600 //This function needs to save last *next_to_pgetc to buf[0]
9601 //to make two pungetc() reliable. Currently,
9602 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9607 char *buf
= g_parsefile
->buf
;
9609 g_parsefile
->next_to_pgetc
= buf
;
9610 #if ENABLE_FEATURE_EDITING
9612 if (!iflag
|| g_parsefile
->pf_fd
!= STDIN_FILENO
)
9613 nr
= nonblock_immune_read(g_parsefile
->pf_fd
, buf
, IBUFSIZ
- 1, /*loop_on_EINTR:*/ 1);
9616 # if ENABLE_ASH_IDLE_TIMEOUT
9618 const char *tmout_var
= lookupvar("TMOUT");
9620 timeout
= atoi(tmout_var
) * 1000;
9626 # if ENABLE_FEATURE_TAB_COMPLETION
9627 line_input_state
->path_lookup
= pathval();
9629 /* Unicode support should be activated even if LANG is set
9630 * _during_ shell execution, not only if it was set when
9631 * shell was started. Therefore, re-check LANG every time:
9633 reinit_unicode(lookupvar("LANG"));
9634 nr
= read_line_input(line_input_state
, cmdedit_prompt
, buf
, IBUFSIZ
, timeout
);
9636 /* Ctrl+C pressed */
9647 /* Ctrl+D pressed */
9650 # if ENABLE_ASH_IDLE_TIMEOUT
9651 else if (errno
== EAGAIN
&& timeout
> 0) {
9652 printf("\007timed out waiting for input: auto-logout\n");
9659 nr
= nonblock_immune_read(g_parsefile
->pf_fd
, buf
, IBUFSIZ
- 1, /*loop_on_EINTR:*/ 1);
9662 #if 0 /* disabled: nonblock_immune_read() handles this problem */
9664 if (parsefile
->fd
== 0 && errno
== EWOULDBLOCK
) {
9665 int flags
= fcntl(0, F_GETFL
);
9666 if (flags
>= 0 && (flags
& O_NONBLOCK
)) {
9667 flags
&= ~O_NONBLOCK
;
9668 if (fcntl(0, F_SETFL
, flags
) >= 0) {
9669 out2str("sh: turning off NDELAY mode\n");
9680 * Refill the input buffer and return the next input character:
9682 * 1) If a string was pushed back on the input, pop it;
9683 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9684 * or we are reading from a string so we can't refill the buffer,
9686 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9687 * 4) Process input up to the next newline, deleting nul characters.
9689 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9690 #define pgetc_debug(...) ((void)0)
9697 while (g_parsefile
->strpush
) {
9698 #if ENABLE_ASH_ALIAS
9699 if (g_parsefile
->left_in_line
== -1
9700 && g_parsefile
->strpush
->ap
9701 && g_parsefile
->next_to_pgetc
[-1] != ' '
9702 && g_parsefile
->next_to_pgetc
[-1] != '\t'
9704 pgetc_debug("preadbuffer PEOA");
9709 /* try "pgetc" now: */
9710 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9711 g_parsefile
->left_in_line
,
9712 g_parsefile
->next_to_pgetc
,
9713 g_parsefile
->next_to_pgetc
);
9714 if (--g_parsefile
->left_in_line
>= 0)
9715 return (unsigned char)(*g_parsefile
->next_to_pgetc
++);
9717 /* on both branches above g_parsefile->left_in_line < 0.
9718 * "pgetc" needs refilling.
9721 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9722 * pungetc() may increment it a few times.
9723 * Assuming it won't increment it to less than -90.
9725 if (g_parsefile
->left_in_line
< -90 || g_parsefile
->buf
== NULL
) {
9726 pgetc_debug("preadbuffer PEOF1");
9727 /* even in failure keep left_in_line and next_to_pgetc
9728 * in lock step, for correct multi-layer pungetc.
9729 * left_in_line was decremented before preadbuffer(),
9730 * must inc next_to_pgetc: */
9731 g_parsefile
->next_to_pgetc
++;
9735 more
= g_parsefile
->left_in_buffer
;
9737 flush_stdout_stderr();
9741 /* don't try reading again */
9742 g_parsefile
->left_in_line
= -99;
9743 pgetc_debug("preadbuffer PEOF2");
9744 g_parsefile
->next_to_pgetc
++;
9749 /* Find out where's the end of line.
9750 * Set g_parsefile->left_in_line
9751 * and g_parsefile->left_in_buffer acordingly.
9752 * NUL chars are deleted.
9754 q
= g_parsefile
->next_to_pgetc
;
9762 memmove(q
, q
+ 1, more
);
9766 g_parsefile
->left_in_line
= q
- g_parsefile
->next_to_pgetc
- 1;
9772 g_parsefile
->left_in_line
= q
- g_parsefile
->next_to_pgetc
- 1;
9773 if (g_parsefile
->left_in_line
< 0)
9778 g_parsefile
->left_in_buffer
= more
;
9783 out2str(g_parsefile
->next_to_pgetc
);
9787 pgetc_debug("preadbuffer at %d:%p'%s'",
9788 g_parsefile
->left_in_line
,
9789 g_parsefile
->next_to_pgetc
,
9790 g_parsefile
->next_to_pgetc
);
9791 return (unsigned char)*g_parsefile
->next_to_pgetc
++;
9794 #define pgetc_as_macro() \
9795 (--g_parsefile->left_in_line >= 0 \
9796 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9803 pgetc_debug("pgetc_fast at %d:%p'%s'",
9804 g_parsefile
->left_in_line
,
9805 g_parsefile
->next_to_pgetc
,
9806 g_parsefile
->next_to_pgetc
);
9807 return pgetc_as_macro();
9810 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9811 # define pgetc_fast() pgetc()
9813 # define pgetc_fast() pgetc_as_macro()
9816 #if ENABLE_ASH_ALIAS
9818 pgetc_without_PEOA(void)
9822 pgetc_debug("pgetc_fast at %d:%p'%s'",
9823 g_parsefile
->left_in_line
,
9824 g_parsefile
->next_to_pgetc
,
9825 g_parsefile
->next_to_pgetc
);
9827 } while (c
== PEOA
);
9831 # define pgetc_without_PEOA() pgetc()
9835 * Read a line from the script.
9838 pfgets(char *line
, int len
)
9844 while (--nleft
> 0) {
9845 c
= pgetc_without_PEOA();
9860 * Undo the last call to pgetc. Only one character may be pushed back.
9861 * PEOF may be pushed back.
9866 g_parsefile
->left_in_line
++;
9867 g_parsefile
->next_to_pgetc
--;
9868 pgetc_debug("pushed back to %d:%p'%s'",
9869 g_parsefile
->left_in_line
,
9870 g_parsefile
->next_to_pgetc
,
9871 g_parsefile
->next_to_pgetc
);
9875 * To handle the "." command, a stack of input files is used. Pushfile
9876 * adds a new entry to the stack and popfile restores the previous level.
9881 struct parsefile
*pf
;
9883 pf
= ckzalloc(sizeof(*pf
));
9884 pf
->prev
= g_parsefile
;
9886 /*pf->strpush = NULL; - ckzalloc did it */
9887 /*pf->basestrpush.prev = NULL;*/
9894 struct parsefile
*pf
= g_parsefile
;
9902 g_parsefile
= pf
->prev
;
9908 * Return to top level.
9913 while (g_parsefile
!= &basepf
)
9918 * Close the file(s) that the shell is reading commands from. Called
9919 * after a fork is done.
9925 if (g_parsefile
->pf_fd
> 0) {
9926 close(g_parsefile
->pf_fd
);
9927 g_parsefile
->pf_fd
= 0;
9932 * Like setinputfile, but takes an open file descriptor. Call this with
9936 setinputfd(int fd
, int push
)
9938 close_on_exec_on(fd
);
9941 g_parsefile
->buf
= NULL
;
9943 g_parsefile
->pf_fd
= fd
;
9944 if (g_parsefile
->buf
== NULL
)
9945 g_parsefile
->buf
= ckmalloc(IBUFSIZ
);
9946 g_parsefile
->left_in_buffer
= 0;
9947 g_parsefile
->left_in_line
= 0;
9948 g_parsefile
->linno
= 1;
9952 * Set the input to take input from a file. If push is set, push the
9953 * old input onto the stack first.
9956 setinputfile(const char *fname
, int flags
)
9962 fd
= open(fname
, O_RDONLY
);
9964 if (flags
& INPUT_NOFILE_OK
)
9966 ash_msg_and_raise_error("can't open '%s'", fname
);
9969 fd2
= copyfd(fd
, 10);
9972 ash_msg_and_raise_error("out of file descriptors");
9975 setinputfd(fd
, flags
& INPUT_PUSH_FILE
);
9982 * Like setinputfile, but takes input from a string.
9985 setinputstring(char *string
)
9989 g_parsefile
->next_to_pgetc
= string
;
9990 g_parsefile
->left_in_line
= strlen(string
);
9991 g_parsefile
->buf
= NULL
;
9992 g_parsefile
->linno
= 1;
9997 /* ============ mail.c
9999 * Routines to check for mail.
10002 #if ENABLE_ASH_MAIL
10004 #define MAXMBOXES 10
10006 /* times of mailboxes */
10007 static time_t mailtime
[MAXMBOXES
];
10008 /* Set if MAIL or MAILPATH is changed. */
10009 static smallint mail_var_path_changed
;
10012 * Print appropriate message(s) if mail has arrived.
10013 * If mail_var_path_changed is set,
10014 * then the value of MAIL has mail_var_path_changed,
10015 * so we just update the values.
10024 struct stackmark smark
;
10027 setstackmark(&smark
);
10028 mpath
= mpathset() ? mpathval() : mailval();
10029 for (mtp
= mailtime
; mtp
< mailtime
+ MAXMBOXES
; mtp
++) {
10030 p
= path_advance(&mpath
, nullstr
);
10035 for (q
= p
; *q
; q
++)
10041 q
[-1] = '\0'; /* delete trailing '/' */
10042 if (stat(p
, &statb
) < 0) {
10046 if (!mail_var_path_changed
&& statb
.st_mtime
!= *mtp
) {
10049 pathopt
? pathopt
: "you have mail"
10052 *mtp
= statb
.st_mtime
;
10054 mail_var_path_changed
= 0;
10055 popstackmark(&smark
);
10058 static void FAST_FUNC
10059 changemail(const char *val UNUSED_PARAM
)
10061 mail_var_path_changed
= 1;
10064 #endif /* ASH_MAIL */
10067 /* ============ ??? */
10070 * Set the shell parameters.
10073 setparam(char **argv
)
10079 for (nparam
= 0; argv
[nparam
]; nparam
++)
10081 ap
= newparam
= ckmalloc((nparam
+ 1) * sizeof(*ap
));
10083 *ap
++ = ckstrdup(*argv
++);
10086 freeparam(&shellparam
);
10087 shellparam
.malloced
= 1;
10088 shellparam
.nparam
= nparam
;
10089 shellparam
.p
= newparam
;
10090 #if ENABLE_ASH_GETOPTS
10091 shellparam
.optind
= 1;
10092 shellparam
.optoff
= -1;
10097 * Process shell options. The global variable argptr contains a pointer
10098 * to the argument list; we advance it past the options.
10100 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10101 * For a non-interactive shell, an error condition encountered
10102 * by a special built-in ... shall cause the shell to write a diagnostic message
10103 * to standard error and exit as shown in the following table:
10104 * Error Special Built-In
10106 * Utility syntax error (option or operand error) Shall exit
10108 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10109 * we see that bash does not do that (set "finishes" with error code 1 instead,
10110 * and shell continues), and people rely on this behavior!
10112 * set -o barfoo 2>/dev/null
10115 * Oh well. Let's mimic that.
10118 plus_minus_o(char *name
, int val
)
10123 for (i
= 0; i
< NOPTS
; i
++) {
10124 if (strcmp(name
, optnames(i
)) == 0) {
10129 ash_msg("illegal option %co %s", val
? '-' : '+', name
);
10132 for (i
= 0; i
< NOPTS
; i
++) {
10134 out1fmt("%-16s%s\n", optnames(i
), optlist
[i
] ? "on" : "off");
10136 out1fmt("set %co %s\n", optlist
[i
] ? '-' : '+', optnames(i
));
10142 setoption(int flag
, int val
)
10146 for (i
= 0; i
< NOPTS
; i
++) {
10147 if (optletters(i
) == flag
) {
10152 ash_msg_and_raise_error("illegal option %c%c", val
? '-' : '+', flag
);
10156 options(int cmdline
)
10164 while ((p
= *argptr
) != NULL
) {
10166 if (c
!= '-' && c
!= '+')
10169 val
= 0; /* val = 0 if c == '+' */
10172 if (p
[0] == '\0' || LONE_DASH(p
)) {
10174 /* "-" means turn off -x and -v */
10177 /* "--" means reset params */
10178 else if (*argptr
== NULL
)
10181 break; /* "-" or "--" terminates options */
10184 /* first char was + or - */
10185 while ((c
= *p
++) != '\0') {
10186 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10187 if (c
== 'c' && cmdline
) {
10188 minusc
= p
; /* command is after shell args */
10189 } else if (c
== 'o') {
10190 if (plus_minus_o(*argptr
, val
)) {
10191 /* it already printed err message */
10192 return 1; /* error */
10196 } else if (cmdline
&& (c
== 'l')) { /* -l or +l == --login */
10198 /* bash does not accept +-login, we also won't */
10199 } else if (cmdline
&& val
&& (c
== '-')) { /* long options */
10200 if (strcmp(p
, "login") == 0)
10212 * The shift builtin command.
10214 static int FAST_FUNC
10215 shiftcmd(int argc UNUSED_PARAM
, char **argv
)
10222 n
= number(argv
[1]);
10223 if (n
> shellparam
.nparam
)
10224 n
= 0; /* bash compat, was = shellparam.nparam; */
10226 shellparam
.nparam
-= n
;
10227 for (ap1
= shellparam
.p
; --n
>= 0; ap1
++) {
10228 if (shellparam
.malloced
)
10231 ap2
= shellparam
.p
;
10232 while ((*ap2
++ = *ap1
++) != NULL
)
10234 #if ENABLE_ASH_GETOPTS
10235 shellparam
.optind
= 1;
10236 shellparam
.optoff
= -1;
10243 * POSIX requires that 'set' (but not export or readonly) output the
10244 * variables in lexicographic order - by the locale's collating order (sigh).
10245 * Maybe we could keep them in an ordered balanced binary tree
10246 * instead of hashed lists.
10247 * For now just roll 'em through qsort for printing...
10250 showvars(const char *sep_prefix
, int on
, int off
)
10253 char **ep
, **epend
;
10255 ep
= listvars(on
, off
, &epend
);
10256 qsort(ep
, epend
- ep
, sizeof(char *), vpcmp
);
10258 sep
= *sep_prefix
? " " : sep_prefix
;
10260 for (; ep
< epend
; ep
++) {
10264 p
= strchrnul(*ep
, '=');
10267 q
= single_quote(++p
);
10268 out1fmt("%s%s%.*s%s\n", sep_prefix
, sep
, (int)(p
- *ep
), *ep
, q
);
10274 * The set command builtin.
10276 static int FAST_FUNC
10277 setcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
10282 return showvars(nullstr
, 0, VUNSET
);
10285 retval
= options(/*cmdline:*/ 0);
10286 if (retval
== 0) { /* if no parse error... */
10288 if (*argptr
!= NULL
) {
10296 #if ENABLE_ASH_RANDOM_SUPPORT
10297 static void FAST_FUNC
10298 change_random(const char *value
)
10302 if (value
== NULL
) {
10303 /* "get", generate */
10304 t
= next_random(&random_gen
);
10305 /* set without recursion */
10306 setvar(vrandom
.var_text
, utoa(t
), VNOFUNC
);
10307 vrandom
.flags
&= ~VNOFUNC
;
10310 t
= strtoul(value
, NULL
, 10);
10311 INIT_RANDOM_T(&random_gen
, (t
? t
: 1), t
);
10316 #if ENABLE_ASH_GETOPTS
10318 getopts(char *optstr
, char *optvar
, char **optfirst
, int *param_optind
, int *optoff
)
10327 if (*param_optind
< 1)
10329 optnext
= optfirst
+ *param_optind
- 1;
10331 if (*param_optind
<= 1 || *optoff
< 0 || (int)strlen(optnext
[-1]) < *optoff
)
10334 p
= optnext
[-1] + *optoff
;
10335 if (p
== NULL
|| *p
== '\0') {
10336 /* Current word is done, advance */
10338 if (p
== NULL
|| *p
!= '-' || *++p
== '\0') {
10345 if (LONE_DASH(p
)) /* check for "--" */
10350 for (q
= optstr
; *q
!= c
;) {
10352 if (optstr
[0] == ':') {
10355 err
|= setvarsafe("OPTARG", s
, 0);
10357 fprintf(stderr
, "Illegal option -%c\n", c
);
10358 unsetvar("OPTARG");
10368 if (*p
== '\0' && (p
= *optnext
) == NULL
) {
10369 if (optstr
[0] == ':') {
10372 err
|= setvarsafe("OPTARG", s
, 0);
10375 fprintf(stderr
, "No arg for -%c option\n", c
);
10376 unsetvar("OPTARG");
10384 err
|= setvarsafe("OPTARG", p
, 0);
10387 err
|= setvarsafe("OPTARG", nullstr
, 0);
10389 *optoff
= p
? p
- *(optnext
- 1) : -1;
10390 *param_optind
= optnext
- optfirst
+ 1;
10391 fmtstr(s
, sizeof(s
), "%d", *param_optind
);
10392 err
|= setvarsafe("OPTIND", s
, VNOFUNC
);
10395 err
|= setvarsafe(optvar
, s
, 0);
10399 flush_stdout_stderr();
10400 raise_exception(EXERROR
);
10406 * The getopts builtin. Shellparam.optnext points to the next argument
10407 * to be processed. Shellparam.optptr points to the next character to
10408 * be processed in the current argument. If shellparam.optnext is NULL,
10409 * then it's the first time getopts has been called.
10411 static int FAST_FUNC
10412 getoptscmd(int argc
, char **argv
)
10417 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10419 optbase
= shellparam
.p
;
10420 if (shellparam
.optind
> shellparam
.nparam
+ 1) {
10421 shellparam
.optind
= 1;
10422 shellparam
.optoff
= -1;
10425 optbase
= &argv
[3];
10426 if (shellparam
.optind
> argc
- 2) {
10427 shellparam
.optind
= 1;
10428 shellparam
.optoff
= -1;
10432 return getopts(argv
[1], argv
[2], optbase
, &shellparam
.optind
,
10433 &shellparam
.optoff
);
10435 #endif /* ASH_GETOPTS */
10438 /* ============ Shell parser */
10441 struct heredoc
*next
; /* next here document in list */
10442 union node
*here
; /* redirection node */
10443 char *eofmark
; /* string indicating end of input */
10444 smallint striptabs
; /* if set, strip leading tabs */
10447 static smallint tokpushback
; /* last token pushed back */
10448 static smallint parsebackquote
; /* nonzero if we are inside backquotes */
10449 static smallint quoteflag
; /* set if (part of) last token was quoted */
10450 static token_id_t lasttoken
; /* last token read (integer id Txxx) */
10451 static struct heredoc
*heredoclist
; /* list of here documents to read */
10452 static char *wordtext
; /* text of last word returned by readtoken */
10453 static struct nodelist
*backquotelist
;
10454 static union node
*redirnode
;
10455 static struct heredoc
*heredoc
;
10457 static const char *
10458 tokname(char *buf
, int tok
)
10461 return tokname_array
[tok
] + 1;
10462 sprintf(buf
, "\"%s\"", tokname_array
[tok
] + 1);
10466 /* raise_error_unexpected_syntax:
10467 * Called when an unexpected token is read during the parse. The argument
10468 * is the token that is expected, or -1 if more than one type of token can
10469 * occur at this point.
10471 static void raise_error_unexpected_syntax(int) NORETURN
;
10473 raise_error_unexpected_syntax(int token
)
10479 l
= sprintf(msg
, "unexpected %s", tokname(buf
, lasttoken
));
10481 sprintf(msg
+ l
, " (expecting %s)", tokname(buf
, token
));
10482 raise_error_syntax(msg
);
10486 #define EOFMARKLEN 79
10488 /* parsing is heavily cross-recursive, need these forward decls */
10489 static union node
*andor(void);
10490 static union node
*pipeline(void);
10491 static union node
*parse_command(void);
10492 static void parseheredoc(void);
10493 static char peektoken(void);
10494 static int readtoken(void);
10496 static union node
*
10499 union node
*n1
, *n2
, *n3
;
10502 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10503 if (nlflag
== 2 && peektoken())
10509 if (tok
== TBACKGND
) {
10510 if (n2
->type
== NPIPE
) {
10511 n2
->npipe
.pipe_backgnd
= 1;
10513 if (n2
->type
!= NREDIR
) {
10514 n3
= stzalloc(sizeof(struct nredir
));
10516 /*n3->nredir.redirect = NULL; - stzalloc did it */
10519 n2
->type
= NBACKGND
;
10525 n3
= stzalloc(sizeof(struct nbinary
));
10527 n3
->nbinary
.ch1
= n1
;
10528 n3
->nbinary
.ch2
= n2
;
10544 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10552 pungetc(); /* push back EOF on input */
10556 raise_error_unexpected_syntax(-1);
10563 static union node
*
10566 union node
*n1
, *n2
, *n3
;
10574 } else if (t
== TOR
) {
10580 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10582 n3
= stzalloc(sizeof(struct nbinary
));
10584 n3
->nbinary
.ch1
= n1
;
10585 n3
->nbinary
.ch2
= n2
;
10590 static union node
*
10593 union node
*n1
, *n2
, *pipenode
;
10594 struct nodelist
*lp
, *prev
;
10598 TRACE(("pipeline: entered\n"));
10599 if (readtoken() == TNOT
) {
10601 checkkwd
= CHKKWD
| CHKALIAS
;
10604 n1
= parse_command();
10605 if (readtoken() == TPIPE
) {
10606 pipenode
= stzalloc(sizeof(struct npipe
));
10607 pipenode
->type
= NPIPE
;
10608 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10609 lp
= stzalloc(sizeof(struct nodelist
));
10610 pipenode
->npipe
.cmdlist
= lp
;
10614 lp
= stzalloc(sizeof(struct nodelist
));
10615 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10616 lp
->n
= parse_command();
10618 } while (readtoken() == TPIPE
);
10624 n2
= stzalloc(sizeof(struct nnot
));
10632 static union node
*
10637 n
= stzalloc(sizeof(struct narg
));
10639 /*n->narg.next = NULL; - stzalloc did it */
10640 n
->narg
.text
= wordtext
;
10641 n
->narg
.backquote
= backquotelist
;
10646 fixredir(union node
*n
, const char *text
, int err
)
10650 TRACE(("Fix redir %s %d\n", text
, err
));
10652 n
->ndup
.vname
= NULL
;
10654 fd
= bb_strtou(text
, NULL
, 10);
10655 if (!errno
&& fd
>= 0)
10656 n
->ndup
.dupfd
= fd
;
10657 else if (LONE_DASH(text
))
10658 n
->ndup
.dupfd
= -1;
10661 raise_error_syntax("bad fd number");
10662 n
->ndup
.vname
= makename();
10667 * Returns true if the text contains nothing to expand (no dollar signs
10671 noexpand(const char *text
)
10675 while ((c
= *text
++) != '\0') {
10676 if (c
== CTLQUOTEMARK
)
10680 else if (SIT(c
, BASESYNTAX
) == CCTL
)
10689 union node
*n
= redirnode
;
10691 if (readtoken() != TWORD
)
10692 raise_error_unexpected_syntax(-1);
10693 if (n
->type
== NHERE
) {
10694 struct heredoc
*here
= heredoc
;
10698 if (quoteflag
== 0)
10700 TRACE(("Here document %d\n", n
->type
));
10701 if (!noexpand(wordtext
) || (i
= strlen(wordtext
)) == 0 || i
> EOFMARKLEN
)
10702 raise_error_syntax("illegal eof marker for << redirection");
10703 rmescapes(wordtext
, 0);
10704 here
->eofmark
= wordtext
;
10706 if (heredoclist
== NULL
)
10707 heredoclist
= here
;
10709 for (p
= heredoclist
; p
->next
; p
= p
->next
)
10713 } else if (n
->type
== NTOFD
|| n
->type
== NFROMFD
) {
10714 fixredir(n
, wordtext
, 0);
10716 n
->nfile
.fname
= makename();
10720 static union node
*
10723 union node
*args
, **app
;
10724 union node
*n
= NULL
;
10725 union node
*vars
, **vpp
;
10726 union node
**rpp
, *redir
;
10728 #if ENABLE_ASH_BASH_COMPAT
10729 smallint double_brackets_flag
= 0;
10739 savecheckkwd
= CHKALIAS
;
10742 checkkwd
= savecheckkwd
;
10745 #if ENABLE_ASH_BASH_COMPAT
10746 case TAND
: /* "&&" */
10747 case TOR
: /* "||" */
10748 if (!double_brackets_flag
) {
10752 wordtext
= (char *) (t
== TAND
? "-a" : "-o");
10755 n
= stzalloc(sizeof(struct narg
));
10757 /*n->narg.next = NULL; - stzalloc did it */
10758 n
->narg
.text
= wordtext
;
10759 #if ENABLE_ASH_BASH_COMPAT
10760 if (strcmp("[[", wordtext
) == 0)
10761 double_brackets_flag
= 1;
10762 else if (strcmp("]]", wordtext
) == 0)
10763 double_brackets_flag
= 0;
10765 n
->narg
.backquote
= backquotelist
;
10766 if (savecheckkwd
&& isassignment(wordtext
)) {
10768 vpp
= &n
->narg
.next
;
10771 app
= &n
->narg
.next
;
10776 *rpp
= n
= redirnode
;
10777 rpp
= &n
->nfile
.next
;
10778 parsefname(); /* read name of redirection file */
10781 if (args
&& app
== &args
->narg
.next
10784 struct builtincmd
*bcmd
;
10787 /* We have a function */
10788 if (readtoken() != TRP
)
10789 raise_error_unexpected_syntax(TRP
);
10790 name
= n
->narg
.text
;
10791 if (!goodname(name
)
10792 || ((bcmd
= find_builtin(name
)) && IS_BUILTIN_SPECIAL(bcmd
))
10794 raise_error_syntax("bad function name");
10797 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10798 n
->narg
.next
= parse_command();
10811 n
= stzalloc(sizeof(struct ncmd
));
10813 n
->ncmd
.args
= args
;
10814 n
->ncmd
.assign
= vars
;
10815 n
->ncmd
.redirect
= redir
;
10819 static union node
*
10820 parse_command(void)
10822 union node
*n1
, *n2
;
10823 union node
*ap
, **app
;
10824 union node
*cp
, **cpp
;
10825 union node
*redir
, **rpp
;
10832 switch (readtoken()) {
10834 raise_error_unexpected_syntax(-1);
10837 n1
= stzalloc(sizeof(struct nif
));
10839 n1
->nif
.test
= list(0);
10840 if (readtoken() != TTHEN
)
10841 raise_error_unexpected_syntax(TTHEN
);
10842 n1
->nif
.ifpart
= list(0);
10844 while (readtoken() == TELIF
) {
10845 n2
->nif
.elsepart
= stzalloc(sizeof(struct nif
));
10846 n2
= n2
->nif
.elsepart
;
10848 n2
->nif
.test
= list(0);
10849 if (readtoken() != TTHEN
)
10850 raise_error_unexpected_syntax(TTHEN
);
10851 n2
->nif
.ifpart
= list(0);
10853 if (lasttoken
== TELSE
)
10854 n2
->nif
.elsepart
= list(0);
10856 n2
->nif
.elsepart
= NULL
;
10864 n1
= stzalloc(sizeof(struct nbinary
));
10865 n1
->type
= (lasttoken
== TWHILE
) ? NWHILE
: NUNTIL
;
10866 n1
->nbinary
.ch1
= list(0);
10869 TRACE(("expecting DO got '%s' %s\n", tokname_array
[got
] + 1,
10870 got
== TWORD
? wordtext
: ""));
10871 raise_error_unexpected_syntax(TDO
);
10873 n1
->nbinary
.ch2
= list(0);
10878 if (readtoken() != TWORD
|| quoteflag
|| !goodname(wordtext
))
10879 raise_error_syntax("bad for loop variable");
10880 n1
= stzalloc(sizeof(struct nfor
));
10882 n1
->nfor
.var
= wordtext
;
10883 checkkwd
= CHKKWD
| CHKALIAS
;
10884 if (readtoken() == TIN
) {
10886 while (readtoken() == TWORD
) {
10887 n2
= stzalloc(sizeof(struct narg
));
10889 /*n2->narg.next = NULL; - stzalloc did it */
10890 n2
->narg
.text
= wordtext
;
10891 n2
->narg
.backquote
= backquotelist
;
10893 app
= &n2
->narg
.next
;
10896 n1
->nfor
.args
= ap
;
10897 if (lasttoken
!= TNL
&& lasttoken
!= TSEMI
)
10898 raise_error_unexpected_syntax(-1);
10900 n2
= stzalloc(sizeof(struct narg
));
10902 /*n2->narg.next = NULL; - stzalloc did it */
10903 n2
->narg
.text
= (char *)dolatstr
;
10904 /*n2->narg.backquote = NULL;*/
10905 n1
->nfor
.args
= n2
;
10907 * Newline or semicolon here is optional (but note
10908 * that the original Bourne shell only allowed NL).
10910 if (lasttoken
!= TNL
&& lasttoken
!= TSEMI
)
10913 checkkwd
= CHKNL
| CHKKWD
| CHKALIAS
;
10914 if (readtoken() != TDO
)
10915 raise_error_unexpected_syntax(TDO
);
10916 n1
->nfor
.body
= list(0);
10920 n1
= stzalloc(sizeof(struct ncase
));
10922 if (readtoken() != TWORD
)
10923 raise_error_unexpected_syntax(TWORD
);
10924 n1
->ncase
.expr
= n2
= stzalloc(sizeof(struct narg
));
10926 /*n2->narg.next = NULL; - stzalloc did it */
10927 n2
->narg
.text
= wordtext
;
10928 n2
->narg
.backquote
= backquotelist
;
10930 checkkwd
= CHKKWD
| CHKALIAS
;
10931 } while (readtoken() == TNL
);
10932 if (lasttoken
!= TIN
)
10933 raise_error_unexpected_syntax(TIN
);
10934 cpp
= &n1
->ncase
.cases
;
10936 checkkwd
= CHKNL
| CHKKWD
;
10938 while (t
!= TESAC
) {
10939 if (lasttoken
== TLP
)
10941 *cpp
= cp
= stzalloc(sizeof(struct nclist
));
10943 app
= &cp
->nclist
.pattern
;
10945 *app
= ap
= stzalloc(sizeof(struct narg
));
10947 /*ap->narg.next = NULL; - stzalloc did it */
10948 ap
->narg
.text
= wordtext
;
10949 ap
->narg
.backquote
= backquotelist
;
10950 if (readtoken() != TPIPE
)
10952 app
= &ap
->narg
.next
;
10955 //ap->narg.next = NULL;
10956 if (lasttoken
!= TRP
)
10957 raise_error_unexpected_syntax(TRP
);
10958 cp
->nclist
.body
= list(2);
10960 cpp
= &cp
->nclist
.next
;
10962 checkkwd
= CHKNL
| CHKKWD
;
10966 raise_error_unexpected_syntax(TENDCASE
);
10973 n1
= stzalloc(sizeof(struct nredir
));
10974 n1
->type
= NSUBSHELL
;
10975 n1
->nredir
.n
= list(0);
10976 /*n1->nredir.redirect = NULL; - stzalloc did it */
10986 return simplecmd();
10989 if (readtoken() != t
)
10990 raise_error_unexpected_syntax(t
);
10993 /* Now check for redirection which may follow command */
10994 checkkwd
= CHKKWD
| CHKALIAS
;
10996 while (readtoken() == TREDIR
) {
10997 *rpp
= n2
= redirnode
;
10998 rpp
= &n2
->nfile
.next
;
11004 if (n1
->type
!= NSUBSHELL
) {
11005 n2
= stzalloc(sizeof(struct nredir
));
11010 n1
->nredir
.redirect
= redir
;
11015 #if ENABLE_ASH_BASH_COMPAT
11016 static int decode_dollar_squote(void)
11018 static const char C_escapes
[] ALIGN1
= "nrbtfav""x\\01234567";
11024 p
= strchr(C_escapes
, c
);
11029 if ((unsigned char)(c
- '0') <= 7) { /* \ooo */
11033 } while ((unsigned char)(c
- '0') <= 7 && --cnt
);
11035 } else if (c
== 'x') { /* \xHH */
11039 } while (isxdigit(c
) && --cnt
);
11041 if (cnt
== 3) { /* \x but next char is "bad" */
11045 } else { /* simple seq like \\ or \t */
11050 c
= bb_process_escape_sequence((void*)&p
);
11051 } else { /* unrecognized "\z": print both chars unless ' or " */
11052 if (c
!= '\'' && c
!= '"') {
11054 c
|= 0x100; /* "please encode \, then me" */
11062 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11063 * is not NULL, read a here document. In the latter case, eofmark is the
11064 * word which marks the end of the document and striptabs is true if
11065 * leading tabs should be stripped from the document. The argument c
11066 * is the first character of the input token or document.
11068 * Because C does not have internal subroutines, I have simulated them
11069 * using goto's to implement the subroutine linkage. The following macros
11070 * will run code that appears at the end of readtoken1.
11072 #define CHECKEND() {goto checkend; checkend_return:;}
11073 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11074 #define PARSESUB() {goto parsesub; parsesub_return:;}
11075 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11076 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11077 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11079 readtoken1(int c
, int syntax
, char *eofmark
, int striptabs
)
11081 /* NB: syntax parameter fits into smallint */
11082 /* c parameter is an unsigned char or PEOF or PEOA */
11085 char line
[EOFMARKLEN
+ 1];
11086 struct nodelist
*bqlist
;
11090 smallint prevsyntax
; /* syntax before arithmetic */
11091 #if ENABLE_ASH_EXPAND_PRMT
11092 smallint pssyntax
; /* we are expanding a prompt string */
11094 int varnest
; /* levels of variables expansion */
11095 int arinest
; /* levels of arithmetic expansion */
11096 int parenlevel
; /* levels of parens in arithmetic */
11097 int dqvarnest
; /* levels of variables expansion within double quotes */
11099 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote
= 0;)
11102 /* Avoid longjmp clobbering */
11108 (void) &parenlevel
;
11111 (void) &prevsyntax
;
11114 startlinno
= g_parsefile
->linno
;
11118 #if ENABLE_ASH_EXPAND_PRMT
11119 pssyntax
= (syntax
== PSSYNTAX
);
11123 dblquote
= (syntax
== DQSYNTAX
);
11129 STARTSTACKSTR(out
);
11131 /* For each line, until end of word */
11132 CHECKEND(); /* set c to PEOF if at end of here document */
11133 for (;;) { /* until end of line or end of word */
11134 CHECKSTRSPACE(4, out
); /* permit 4 calls to USTPUTC */
11135 switch (SIT(c
, syntax
)) {
11136 case CNL
: /* '\n' */
11137 if (syntax
== BASESYNTAX
)
11138 goto endword
; /* exit outer loop */
11140 g_parsefile
->linno
++;
11141 setprompt_if(doprompt
, 2);
11143 goto loop
; /* continue outer loop */
11148 if (eofmark
== NULL
|| dblquote
)
11149 USTPUTC(CTLESC
, out
);
11150 #if ENABLE_ASH_BASH_COMPAT
11151 if (c
== '\\' && bash_dollar_squote
) {
11152 c
= decode_dollar_squote();
11154 USTPUTC('\\', out
);
11155 c
= (unsigned char)c
;
11161 case CBACK
: /* backslash */
11162 c
= pgetc_without_PEOA();
11164 USTPUTC(CTLESC
, out
);
11165 USTPUTC('\\', out
);
11167 } else if (c
== '\n') {
11168 setprompt_if(doprompt
, 2);
11170 #if ENABLE_ASH_EXPAND_PRMT
11171 if (c
== '$' && pssyntax
) {
11172 USTPUTC(CTLESC
, out
);
11173 USTPUTC('\\', out
);
11176 /* Backslash is retained if we are in "str" and next char isn't special */
11181 && (c
!= '"' || eofmark
!= NULL
)
11183 USTPUTC(CTLESC
, out
);
11184 USTPUTC('\\', out
);
11186 if (SIT(c
, SQSYNTAX
) == CCTL
)
11187 USTPUTC(CTLESC
, out
);
11195 if (eofmark
== NULL
) {
11196 USTPUTC(CTLQUOTEMARK
, out
);
11204 IF_ASH_BASH_COMPAT(bash_dollar_squote
= 0;)
11205 if (eofmark
!= NULL
&& arinest
== 0
11210 if (dqvarnest
== 0) {
11211 syntax
= BASESYNTAX
;
11218 case CVAR
: /* '$' */
11219 PARSESUB(); /* parse substitution */
11221 case CENDVAR
: /* '}' */
11224 if (dqvarnest
> 0) {
11231 #if ENABLE_SH_MATH_SUPPORT
11232 case CLP
: /* '(' in arithmetic */
11236 case CRP
: /* ')' in arithmetic */
11237 if (parenlevel
> 0) {
11240 if (pgetc() == ')') {
11241 if (--arinest
== 0) {
11242 syntax
= prevsyntax
;
11243 dblquote
= (syntax
== DQSYNTAX
);
11248 * unbalanced parens
11249 * (don't 2nd guess - no error)
11257 case CBQUOTE
: /* '`' */
11261 goto endword
; /* exit outer loop */
11265 if (varnest
== 0) {
11266 #if ENABLE_ASH_BASH_COMPAT
11268 if (pgetc() == '>')
11269 c
= 0x100 + '>'; /* flag &> */
11273 goto endword
; /* exit outer loop */
11275 IF_ASH_ALIAS(if (c
!= PEOA
))
11282 #if ENABLE_SH_MATH_SUPPORT
11283 if (syntax
== ARISYNTAX
)
11284 raise_error_syntax("missing '))'");
11286 if (syntax
!= BASESYNTAX
&& !parsebackquote
&& eofmark
== NULL
)
11287 raise_error_syntax("unterminated quoted string");
11288 if (varnest
!= 0) {
11289 startlinno
= g_parsefile
->linno
;
11291 raise_error_syntax("missing '}'");
11293 USTPUTC('\0', out
);
11294 len
= out
- (char *)stackblock();
11295 out
= stackblock();
11296 if (eofmark
== NULL
) {
11297 if ((c
== '>' || c
== '<' IF_ASH_BASH_COMPAT( || c
== 0x100 + '>'))
11300 if (isdigit_str9(out
)) {
11301 PARSEREDIR(); /* passed as params: out, c */
11302 lasttoken
= TREDIR
;
11305 /* else: non-number X seen, interpret it
11306 * as "NNNX>file" = "NNNX >file" */
11310 quoteflag
= quotef
;
11311 backquotelist
= bqlist
;
11312 grabstackblock(len
);
11316 /* end of readtoken routine */
11319 * Check to see whether we are at the end of the here document. When this
11320 * is called, c is set to the first character of the next input line. If
11321 * we are at the end of the here document, this routine sets the c to PEOF.
11325 #if ENABLE_ASH_ALIAS
11327 c
= pgetc_without_PEOA();
11330 while (c
== '\t') {
11331 c
= pgetc_without_PEOA();
11334 if (c
== *eofmark
) {
11335 if (pfgets(line
, sizeof(line
)) != NULL
) {
11339 for (q
= eofmark
+ 1; *q
&& *p
== *q
; p
++, q
++)
11341 if (*p
== '\n' && *q
== '\0') {
11343 g_parsefile
->linno
++;
11344 needprompt
= doprompt
;
11346 pushstring(line
, NULL
);
11351 goto checkend_return
;
11355 * Parse a redirection operator. The variable "out" points to a string
11356 * specifying the fd to be redirected. The variable "c" contains the
11357 * first character of the redirection operator.
11360 /* out is already checked to be a valid number or "" */
11361 int fd
= (*out
== '\0' ? -1 : atoi(out
));
11364 np
= stzalloc(sizeof(struct nfile
));
11369 np
->type
= NAPPEND
;
11371 np
->type
= NCLOBBER
;
11374 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11380 #if ENABLE_ASH_BASH_COMPAT
11381 else if (c
== 0x100 + '>') { /* this flags &> redirection */
11383 pgetc(); /* this is '>', no need to check */
11387 else { /* c == '<' */
11388 /*np->nfile.fd = 0; - stzalloc did it */
11392 if (sizeof(struct nfile
) != sizeof(struct nhere
)) {
11393 np
= stzalloc(sizeof(struct nhere
));
11394 /*np->nfile.fd = 0; - stzalloc did it */
11397 heredoc
= stzalloc(sizeof(struct heredoc
));
11398 heredoc
->here
= np
;
11401 heredoc
->striptabs
= 1;
11403 /*heredoc->striptabs = 0; - stzalloc did it */
11409 np
->type
= NFROMFD
;
11413 np
->type
= NFROMTO
;
11425 goto parseredir_return
;
11429 * Parse a substitution. At this point, we have read the dollar sign
11430 * and nothing else.
11433 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11434 * (assuming ascii char codes, as the original implementation did) */
11435 #define is_special(c) \
11436 (((unsigned)(c) - 33 < 32) \
11437 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11439 unsigned char subtype
;
11444 if (c
> 255 /* PEOA or PEOF */
11445 || (c
!= '(' && c
!= '{' && !is_name(c
) && !is_special(c
))
11447 #if ENABLE_ASH_BASH_COMPAT
11449 bash_dollar_squote
= 1;
11454 } else if (c
== '(') {
11455 /* $(command) or $((arith)) */
11456 if (pgetc() == '(') {
11457 #if ENABLE_SH_MATH_SUPPORT
11460 raise_error_syntax("you disabled math support for $((arith)) syntax");
11467 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11468 USTPUTC(CTLVAR
, out
);
11469 typeloc
= out
- (char *)stackblock();
11470 USTPUTC(VSNORMAL
, out
);
11471 subtype
= VSNORMAL
;
11477 c
= '#'; /* ${#} - same as $# */
11479 subtype
= VSLENGTH
; /* ${#VAR} */
11484 if (c
<= 255 /* not PEOA or PEOF */ && is_name(c
)) {
11485 /* $[{[#]]NAME[}] */
11489 } while (c
<= 255 /* not PEOA or PEOF */ && is_in_name(c
));
11490 } else if (isdigit(c
)) {
11491 /* $[{[#]]NUM[}] */
11495 } while (isdigit(c
));
11496 } else if (is_special(c
)) {
11497 /* $[{[#]]<specialchar>[}] */
11502 raise_error_syntax("bad substitution");
11504 if (c
!= '}' && subtype
== VSLENGTH
) {
11505 /* ${#VAR didn't end with } */
11511 if (subtype
== 0) {
11512 /* ${VAR...} but not $VAR or ${#VAR} */
11513 /* c == first char after VAR */
11517 #if ENABLE_ASH_BASH_COMPAT
11518 if (c
== ':' || c
== '$' || isdigit(c
)) {
11519 //TODO: support more general format ${v:EXPR:EXPR},
11520 // where EXPR follows $(()) rules
11521 subtype
= VSSUBSTR
;
11523 break; /* "goto do_pungetc" is bigger (!) */
11529 static const char types
[] ALIGN1
= "}-+?=";
11530 const char *p
= strchr(types
, c
);
11533 subtype
= p
- types
+ VSNORMAL
;
11539 subtype
= (c
== '#' ? VSTRIMLEFT
: VSTRIMRIGHT
);
11546 #if ENABLE_ASH_BASH_COMPAT
11548 /* ${v/[/]pattern/repl} */
11549 //TODO: encode pattern and repl separately.
11550 // Currently ${v/$var_with_slash/repl} is horribly broken
11551 subtype
= VSREPLACE
;
11555 subtype
++; /* VSREPLACEALL */
11563 if (dblquote
|| arinest
)
11565 ((unsigned char *)stackblock())[typeloc
] = subtype
| flags
;
11566 if (subtype
!= VSNORMAL
) {
11568 if (dblquote
|| arinest
) {
11573 goto parsesub_return
;
11577 * Called to parse command substitutions. Newstyle is set if the command
11578 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11579 * list of commands (passed by reference), and savelen is the number of
11580 * characters on the top of the stack which must be preserved.
11583 struct nodelist
**nlpp
;
11586 char *volatile str
;
11587 struct jmploc jmploc
;
11588 struct jmploc
*volatile savehandler
;
11590 smallint saveprompt
= 0;
11593 (void) &saveprompt
;
11595 savepbq
= parsebackquote
;
11596 if (setjmp(jmploc
.loc
)) {
11598 parsebackquote
= 0;
11599 exception_handler
= savehandler
;
11600 longjmp(exception_handler
->loc
, 1);
11604 savelen
= out
- (char *)stackblock();
11606 str
= ckmalloc(savelen
);
11607 memcpy(str
, stackblock(), savelen
);
11609 savehandler
= exception_handler
;
11610 exception_handler
= &jmploc
;
11613 /* We must read until the closing backquote, giving special
11614 treatment to some slashes, and then push the string and
11615 reread it as input, interpreting it normally. */
11620 STARTSTACKSTR(pout
);
11624 setprompt_if(needprompt
, 2);
11633 g_parsefile
->linno
++;
11634 setprompt_if(doprompt
, 2);
11636 * If eating a newline, avoid putting
11637 * the newline into the new character
11638 * stream (via the STPUTC after the
11643 if (pc
!= '\\' && pc
!= '`' && pc
!= '$'
11644 && (!dblquote
|| pc
!= '"')
11646 STPUTC('\\', pout
);
11648 if (pc
<= 255 /* not PEOA or PEOF */) {
11654 IF_ASH_ALIAS(case PEOA
:)
11655 startlinno
= g_parsefile
->linno
;
11656 raise_error_syntax("EOF in backquote substitution");
11659 g_parsefile
->linno
++;
11660 needprompt
= doprompt
;
11669 STPUTC('\0', pout
);
11670 psavelen
= pout
- (char *)stackblock();
11671 if (psavelen
> 0) {
11672 pstr
= grabstackstr(pout
);
11673 setinputstring(pstr
);
11678 nlpp
= &(*nlpp
)->next
;
11679 *nlpp
= stzalloc(sizeof(**nlpp
));
11680 /* (*nlpp)->next = NULL; - stzalloc did it */
11681 parsebackquote
= oldstyle
;
11684 saveprompt
= doprompt
;
11691 doprompt
= saveprompt
;
11692 else if (readtoken() != TRP
)
11693 raise_error_unexpected_syntax(TRP
);
11698 * Start reading from old file again, ignoring any pushed back
11699 * tokens left from the backquote parsing
11704 while (stackblocksize() <= savelen
)
11706 STARTSTACKSTR(out
);
11708 memcpy(out
, str
, savelen
);
11709 STADJUST(savelen
, out
);
11715 parsebackquote
= savepbq
;
11716 exception_handler
= savehandler
;
11717 if (arinest
|| dblquote
)
11718 USTPUTC(CTLBACKQ
| CTLQUOTE
, out
);
11720 USTPUTC(CTLBACKQ
, out
);
11722 goto parsebackq_oldreturn
;
11723 goto parsebackq_newreturn
;
11726 #if ENABLE_SH_MATH_SUPPORT
11728 * Parse an arithmetic expansion (indicate start of one and set state)
11731 if (++arinest
== 1) {
11732 prevsyntax
= syntax
;
11733 syntax
= ARISYNTAX
;
11734 USTPUTC(CTLARI
, out
);
11741 * we collapse embedded arithmetic expansion to
11742 * parenthesis, which should be equivalent
11746 goto parsearith_return
;
11750 } /* end of readtoken */
11753 * Read the next input token.
11754 * If the token is a word, we set backquotelist to the list of cmds in
11755 * backquotes. We set quoteflag to true if any part of the word was
11757 * If the token is TREDIR, then we set redirnode to a structure containing
11759 * In all cases, the variable startlinno is set to the number of the line
11760 * on which the token starts.
11762 * [Change comment: here documents and internal procedures]
11763 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11764 * word parsing code into a separate routine. In this case, readtoken
11765 * doesn't need to have any internal procedures, but parseword does.
11766 * We could also make parseoperator in essence the main routine, and
11767 * have parseword (readtoken1?) handle both words and redirection.]
11769 #define NEW_xxreadtoken
11770 #ifdef NEW_xxreadtoken
11771 /* singles must be first! */
11772 static const char xxreadtoken_chars
[7] ALIGN1
= {
11773 '\n', '(', ')', /* singles */
11774 '&', '|', ';', /* doubles */
11778 #define xxreadtoken_singles 3
11779 #define xxreadtoken_doubles 3
11781 static const char xxreadtoken_tokens
[] ALIGN1
= {
11782 TNL
, TLP
, TRP
, /* only single occurrence allowed */
11783 TBACKGND
, TPIPE
, TSEMI
, /* if single occurrence */
11784 TEOF
, /* corresponds to trailing nul */
11785 TAND
, TOR
, TENDCASE
/* if double occurrence */
11797 setprompt_if(needprompt
, 2);
11798 startlinno
= g_parsefile
->linno
;
11799 for (;;) { /* until token or start of word found */
11801 if (c
== ' ' || c
== '\t' IF_ASH_ALIAS( || c
== PEOA
))
11805 while ((c
= pgetc()) != '\n' && c
!= PEOF
)
11808 } else if (c
== '\\') {
11809 if (pgetc() != '\n') {
11811 break; /* return readtoken1(...) */
11813 startlinno
= ++g_parsefile
->linno
;
11814 setprompt_if(doprompt
, 2);
11818 p
= xxreadtoken_chars
+ sizeof(xxreadtoken_chars
) - 1;
11821 g_parsefile
->linno
++;
11822 needprompt
= doprompt
;
11825 p
= strchr(xxreadtoken_chars
, c
);
11827 break; /* return readtoken1(...) */
11829 if ((int)(p
- xxreadtoken_chars
) >= xxreadtoken_singles
) {
11831 if (cc
== c
) { /* double occurrence? */
11832 p
+= xxreadtoken_doubles
+ 1;
11835 #if ENABLE_ASH_BASH_COMPAT
11836 if (c
== '&' && cc
== '>') /* &> */
11837 break; /* return readtoken1(...) */
11842 lasttoken
= xxreadtoken_tokens
[p
- xxreadtoken_chars
];
11847 return readtoken1(c
, BASESYNTAX
, (char *) NULL
, 0);
11849 #else /* old xxreadtoken */
11850 #define RETURN(token) return lasttoken = token
11860 setprompt_if(needprompt
, 2);
11861 startlinno
= g_parsefile
->linno
;
11862 for (;;) { /* until token or start of word found */
11865 case ' ': case '\t':
11866 IF_ASH_ALIAS(case PEOA
:)
11869 while ((c
= pgetc()) != '\n' && c
!= PEOF
)
11874 if (pgetc() == '\n') {
11875 startlinno
= ++g_parsefile
->linno
;
11876 setprompt_if(doprompt
, 2);
11882 g_parsefile
->linno
++;
11883 needprompt
= doprompt
;
11888 if (pgetc() == '&')
11893 if (pgetc() == '|')
11898 if (pgetc() == ';')
11911 return readtoken1(c
, BASESYNTAX
, (char *)NULL
, 0);
11914 #endif /* old xxreadtoken */
11921 smallint alreadyseen
= tokpushback
;
11924 #if ENABLE_ASH_ALIAS
11933 if (checkkwd
& CHKNL
) {
11940 if (t
!= TWORD
|| quoteflag
) {
11945 * check for keywords
11947 if (checkkwd
& CHKKWD
) {
11948 const char *const *pp
;
11950 pp
= findkwd(wordtext
);
11952 lasttoken
= t
= pp
- tokname_array
;
11953 TRACE(("keyword '%s' recognized\n", tokname_array
[t
] + 1));
11958 if (checkkwd
& CHKALIAS
) {
11959 #if ENABLE_ASH_ALIAS
11961 ap
= lookupalias(wordtext
, 1);
11964 pushstring(ap
->val
, ap
);
11974 TRACE(("token '%s' %s\n", tokname_array
[t
] + 1, t
== TWORD
? wordtext
: ""));
11976 TRACE(("reread token '%s' %s\n", tokname_array
[t
] + 1, t
== TWORD
? wordtext
: ""));
11988 return tokname_array
[t
][0];
11992 * Read and parse a command. Returns NODE_EOF on end of file.
11993 * (NULL is a valid parse tree indicating a blank line.)
11995 static union node
*
11996 parsecmd(int interact
)
12001 doprompt
= interact
;
12002 setprompt_if(doprompt
, doprompt
);
12014 * Input any here documents.
12019 struct heredoc
*here
;
12022 here
= heredoclist
;
12023 heredoclist
= NULL
;
12026 setprompt_if(needprompt
, 2);
12027 readtoken1(pgetc(), here
->here
->type
== NHERE
? SQSYNTAX
: DQSYNTAX
,
12028 here
->eofmark
, here
->striptabs
);
12029 n
= stzalloc(sizeof(struct narg
));
12030 n
->narg
.type
= NARG
;
12031 /*n->narg.next = NULL; - stzalloc did it */
12032 n
->narg
.text
= wordtext
;
12033 n
->narg
.backquote
= backquotelist
;
12034 here
->here
->nhere
.doc
= n
;
12041 * called by editline -- any expansions to the prompt should be added here.
12043 #if ENABLE_ASH_EXPAND_PRMT
12044 static const char *
12045 expandstr(const char *ps
)
12049 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12050 * and token processing _can_ alter it (delete NULs etc). */
12051 setinputstring((char *)ps
);
12052 readtoken1(pgetc(), PSSYNTAX
, nullstr
, 0);
12055 n
.narg
.type
= NARG
;
12056 n
.narg
.next
= NULL
;
12057 n
.narg
.text
= wordtext
;
12058 n
.narg
.backquote
= backquotelist
;
12060 expandarg(&n
, NULL
, 0);
12061 return stackblock();
12066 * Execute a command or commands contained in a string.
12069 evalstring(char *s
, int mask
)
12072 struct stackmark smark
;
12076 setstackmark(&smark
);
12079 while ((n
= parsecmd(0)) != NODE_EOF
) {
12081 popstackmark(&smark
);
12094 * The eval command.
12096 static int FAST_FUNC
12097 evalcmd(int argc UNUSED_PARAM
, char **argv
)
12106 STARTSTACKSTR(concat
);
12108 concat
= stack_putstr(p
, concat
);
12112 STPUTC(' ', concat
);
12114 STPUTC('\0', concat
);
12115 p
= grabstackstr(concat
);
12117 evalstring(p
, ~SKIPEVAL
);
12123 * Read and execute commands.
12124 * "Top" is nonzero for the top level command loop;
12125 * it turns on prompting if the shell is interactive.
12131 struct stackmark smark
;
12135 TRACE(("cmdloop(%d) called\n", top
));
12139 setstackmark(&smark
);
12142 showjobs(stderr
, SHOW_CHANGED
);
12145 if (iflag
&& top
) {
12149 n
= parsecmd(inter
);
12151 if (DEBUG
> 2 && debug
&& (n
!= NODE_EOF
))
12154 if (n
== NODE_EOF
) {
12155 if (!top
|| numeof
>= 50)
12157 if (!stoppedjobs()) {
12160 out2str("\nUse \"exit\" to leave shell.\n");
12163 } else if (nflag
== 0) {
12164 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12169 popstackmark(&smark
);
12174 return skip
& SKIPEVAL
;
12181 * Take commands from a file. To be compatible we should do a path
12182 * search for the file, which is necessary to find sub-commands.
12185 find_dot_file(char *name
)
12188 const char *path
= pathval();
12191 /* don't try this for absolute or relative paths */
12192 if (strchr(name
, '/'))
12195 /* IIRC standards do not say whether . is to be searched.
12196 * And it is even smaller this way, making it unconditional for now:
12198 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12203 while ((fullname
= path_advance(&path
, name
)) != NULL
) {
12205 if ((stat(fullname
, &statb
) == 0) && S_ISREG(statb
.st_mode
)) {
12207 * Don't bother freeing here, since it will
12208 * be freed by the caller.
12212 if (fullname
!= name
)
12213 stunalloc(fullname
);
12216 /* not found in the PATH */
12217 ash_msg_and_raise_error("%s: not found", name
);
12221 static int FAST_FUNC
12222 dotcmd(int argc
, char **argv
)
12225 struct strlist
*sp
;
12226 volatile struct shparam saveparam
;
12228 for (sp
= cmdenviron
; sp
; sp
= sp
->next
)
12229 setvareq(ckstrdup(sp
->text
), VSTRFIXED
| VTEXTFIXED
);
12232 /* bash says: "bash: .: filename argument required" */
12233 return 2; /* bash compat */
12236 /* "false; . empty_file; echo $?" should print 0, not 1: */
12239 fullname
= find_dot_file(argv
[1]);
12243 if (argc
) { /* argc > 0, argv[0] != NULL */
12244 saveparam
= shellparam
;
12245 shellparam
.malloced
= 0;
12246 shellparam
.nparam
= argc
;
12247 shellparam
.p
= argv
;
12250 setinputfile(fullname
, INPUT_PUSH_FILE
);
12251 commandname
= fullname
;
12256 freeparam(&shellparam
);
12257 shellparam
= saveparam
;
12263 static int FAST_FUNC
12264 exitcmd(int argc UNUSED_PARAM
, char **argv
)
12269 exitstatus
= number(argv
[1]);
12270 raise_exception(EXEXIT
);
12275 * Read a file containing shell functions.
12278 readcmdfile(char *name
)
12280 setinputfile(name
, INPUT_PUSH_FILE
);
12286 /* ============ find_command inplementation */
12289 * Resolve a command name. If you change this routine, you may have to
12290 * change the shellexec routine as well.
12293 find_command(char *name
, struct cmdentry
*entry
, int act
, const char *path
)
12295 struct tblentry
*cmdp
;
12302 struct builtincmd
*bcmd
;
12304 /* If name contains a slash, don't use PATH or hash table */
12305 if (strchr(name
, '/') != NULL
) {
12306 entry
->u
.index
= -1;
12307 if (act
& DO_ABS
) {
12308 while (stat(name
, &statb
) < 0) {
12310 if (errno
== EINTR
)
12313 entry
->cmdtype
= CMDUNKNOWN
;
12317 entry
->cmdtype
= CMDNORMAL
;
12321 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12323 updatetbl
= (path
== pathval());
12326 if (strstr(path
, "%builtin") != NULL
)
12327 act
|= DO_ALTBLTIN
;
12330 /* If name is in the table, check answer will be ok */
12331 cmdp
= cmdlookup(name
, 0);
12332 if (cmdp
!= NULL
) {
12335 switch (cmdp
->cmdtype
) {
12353 } else if (cmdp
->rehash
== 0)
12354 /* if not invalidated by cd, we're done */
12358 /* If %builtin not in path, check for builtin next */
12359 bcmd
= find_builtin(name
);
12361 if (IS_BUILTIN_REGULAR(bcmd
))
12362 goto builtin_success
;
12363 if (act
& DO_ALTPATH
) {
12364 if (!(act
& DO_ALTBLTIN
))
12365 goto builtin_success
;
12366 } else if (builtinloc
<= 0) {
12367 goto builtin_success
;
12371 #if ENABLE_FEATURE_SH_STANDALONE
12373 int applet_no
= find_applet_by_name(name
);
12374 if (applet_no
>= 0) {
12375 entry
->cmdtype
= CMDNORMAL
;
12376 entry
->u
.index
= -2 - applet_no
;
12382 /* We have to search path. */
12383 prev
= -1; /* where to start */
12384 if (cmdp
&& cmdp
->rehash
) { /* doing a rehash */
12385 if (cmdp
->cmdtype
== CMDBUILTIN
)
12388 prev
= cmdp
->param
.index
;
12394 while ((fullname
= path_advance(&path
, name
)) != NULL
) {
12395 stunalloc(fullname
);
12396 /* NB: code below will still use fullname
12397 * despite it being "unallocated" */
12400 if (prefix(pathopt
, "builtin")) {
12402 goto builtin_success
;
12405 if ((act
& DO_NOFUNC
)
12406 || !prefix(pathopt
, "func")
12407 ) { /* ignore unimplemented options */
12411 /* if rehash, don't redo absolute path names */
12412 if (fullname
[0] == '/' && idx
<= prev
) {
12415 TRACE(("searchexec \"%s\": no change\n", name
));
12418 while (stat(fullname
, &statb
) < 0) {
12420 if (errno
== EINTR
)
12423 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
12427 e
= EACCES
; /* if we fail, this will be the error */
12428 if (!S_ISREG(statb
.st_mode
))
12430 if (pathopt
) { /* this is a %func directory */
12431 stalloc(strlen(fullname
) + 1);
12432 /* NB: stalloc will return space pointed by fullname
12433 * (because we don't have any intervening allocations
12434 * between stunalloc above and this stalloc) */
12435 readcmdfile(fullname
);
12436 cmdp
= cmdlookup(name
, 0);
12437 if (cmdp
== NULL
|| cmdp
->cmdtype
!= CMDFUNCTION
)
12438 ash_msg_and_raise_error("%s not defined in %s", name
, fullname
);
12439 stunalloc(fullname
);
12442 TRACE(("searchexec \"%s\" returns \"%s\"\n", name
, fullname
));
12444 entry
->cmdtype
= CMDNORMAL
;
12445 entry
->u
.index
= idx
;
12449 cmdp
= cmdlookup(name
, 1);
12450 cmdp
->cmdtype
= CMDNORMAL
;
12451 cmdp
->param
.index
= idx
;
12456 /* We failed. If there was an entry for this command, delete it */
12457 if (cmdp
&& updatetbl
)
12458 delete_cmd_entry();
12460 ash_msg("%s: %s", name
, errmsg(e
, "not found"));
12461 entry
->cmdtype
= CMDUNKNOWN
;
12466 entry
->cmdtype
= CMDBUILTIN
;
12467 entry
->u
.cmd
= bcmd
;
12471 cmdp
= cmdlookup(name
, 1);
12472 cmdp
->cmdtype
= CMDBUILTIN
;
12473 cmdp
->param
.cmd
= bcmd
;
12477 entry
->cmdtype
= cmdp
->cmdtype
;
12478 entry
->u
= cmdp
->param
;
12482 /* ============ trap.c */
12485 * The trap builtin.
12487 static int FAST_FUNC
12488 trapcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12492 int signo
, exitcode
;
12497 for (signo
= 0; signo
< NSIG
; signo
++) {
12498 char *tr
= trap_ptr
[signo
];
12500 /* note: bash adds "SIG", but only if invoked
12501 * as "bash". If called as "sh", or if set -o posix,
12502 * then it prints short signal names.
12503 * We are printing short names: */
12504 out1fmt("trap -- %s %s\n",
12506 get_signame(signo
));
12507 /* trap_ptr != trap only if we are in special-cased `trap` code.
12508 * In this case, we will exit very soon, no need to free(). */
12509 /* if (trap_ptr != trap && tp[0]) */
12514 if (trap_ptr != trap) {
12527 signo
= get_signum(*ap
);
12529 /* Mimic bash message exactly */
12530 ash_msg("%s: invalid signal specification", *ap
);
12536 if (LONE_DASH(action
))
12539 action
= ckstrdup(action
);
12543 may_have_traps
= 1;
12544 trap
[signo
] = action
;
12555 /* ============ Builtins */
12557 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12559 * Lists available builtins
12561 static int FAST_FUNC
12562 helpcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12568 "Built-in commands:\n"
12569 "------------------\n");
12570 for (col
= 0, i
= 0; i
< ARRAY_SIZE(builtintab
); i
++) {
12571 col
+= out1fmt("%c%s", ((col
== 0) ? '\t' : ' '),
12572 builtintab
[i
].name
+ 1);
12578 #if ENABLE_FEATURE_SH_STANDALONE
12580 const char *a
= applet_names
;
12582 col
+= out1fmt("%c%s", ((col
== 0) ? '\t' : ' '), a
);
12587 a
+= strlen(a
) + 1;
12592 return EXIT_SUCCESS
;
12594 #endif /* FEATURE_SH_EXTRA_QUIET */
12597 * The export and readonly commands.
12599 static int FAST_FUNC
12600 exportcmd(int argc UNUSED_PARAM
, char **argv
)
12606 int flag
= argv
[0][0] == 'r' ? VREADONLY
: VEXPORT
;
12609 while ((nopt
= nextopt("np"))) {
12622 p
= strchr(name
, '=');
12626 vp
= *findvar(hashvar(name
), name
);
12633 setvar(name
, p
, flag
);
12634 setvar(name
, p
, flag
& mask
);
12635 } while ((name
= *++aptr
) != NULL
);
12639 showvars(argv
[0], flag
, 0);
12644 * Delete a function if it exists.
12647 unsetfunc(const char *name
)
12649 struct tblentry
*cmdp
;
12651 cmdp
= cmdlookup(name
, 0);
12652 if (cmdp
!= NULL
&& cmdp
->cmdtype
== CMDFUNCTION
)
12653 delete_cmd_entry();
12657 * The unset builtin command. We unset the function before we unset the
12658 * variable to allow a function to be unset when there is a readonly variable
12659 * with the same name.
12661 static int FAST_FUNC
12662 unsetcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12669 while ((i
= nextopt("vf")) != 0) {
12673 for (ap
= argptr
; *ap
; ap
++) {
12686 static const unsigned char timescmd_str
[] ALIGN1
= {
12687 ' ', offsetof(struct tms
, tms_utime
),
12688 '\n', offsetof(struct tms
, tms_stime
),
12689 ' ', offsetof(struct tms
, tms_cutime
),
12690 '\n', offsetof(struct tms
, tms_cstime
),
12693 static int FAST_FUNC
12694 timescmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12696 unsigned long clk_tck
, s
, t
;
12697 const unsigned char *p
;
12700 clk_tck
= sysconf(_SC_CLK_TCK
);
12705 t
= *(clock_t *)(((char *) &buf
) + p
[1]);
12708 out1fmt("%lum%lu.%03lus%c",
12710 (t
* 1000) / clk_tck
,
12718 #if ENABLE_SH_MATH_SUPPORT
12720 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12721 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12723 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12725 static int FAST_FUNC
12726 letcmd(int argc UNUSED_PARAM
, char **argv
)
12732 ash_msg_and_raise_error("expression expected");
12734 i
= ash_arith(*argv
);
12742 * The read builtin. Options:
12743 * -r Do not interpret '\' specially
12744 * -s Turn off echo (tty only)
12745 * -n NCHARS Read NCHARS max
12746 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12747 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12748 * -u FD Read from given FD instead of fd 0
12749 * This uses unbuffered input, which may be avoidable in some cases.
12750 * TODO: bash also has:
12751 * -a ARRAY Read into array[0],[1],etc
12752 * -d DELIM End on DELIM char, not newline
12753 * -e Use line editing (tty only)
12755 static int FAST_FUNC
12756 readcmd(int argc UNUSED_PARAM
, char **argv UNUSED_PARAM
)
12758 char *opt_n
= NULL
;
12759 char *opt_p
= NULL
;
12760 char *opt_t
= NULL
;
12761 char *opt_u
= NULL
;
12762 int read_flags
= 0;
12766 while ((i
= nextopt("p:u:rt:n:s")) != '\0') {
12775 read_flags
|= BUILTIN_READ_SILENT
;
12781 read_flags
|= BUILTIN_READ_RAW
;
12791 r
= shell_builtin_read(setvar2
,
12793 bltinlookup("IFS"), /* can be NULL */
12801 if ((uintptr_t)r
> 1)
12802 ash_msg_and_raise_error(r
);
12804 return (uintptr_t)r
;
12807 static int FAST_FUNC
12808 umaskcmd(int argc UNUSED_PARAM
, char **argv
)
12810 static const char permuser
[3] ALIGN1
= "ugo";
12811 static const char permmode
[3] ALIGN1
= "rwx";
12812 static const short permmask
[] ALIGN2
= {
12813 S_IRUSR
, S_IWUSR
, S_IXUSR
,
12814 S_IRGRP
, S_IWGRP
, S_IXGRP
,
12815 S_IROTH
, S_IWOTH
, S_IXOTH
12818 /* TODO: use bb_parse_mode() instead */
12823 int symbolic_mode
= 0;
12825 while (nextopt("S") != '\0') {
12836 if (symbolic_mode
) {
12840 for (i
= 0; i
< 3; i
++) {
12843 *p
++ = permuser
[i
];
12845 for (j
= 0; j
< 3; j
++) {
12846 if ((mask
& permmask
[3 * i
+ j
]) == 0) {
12847 *p
++ = permmode
[j
];
12855 out1fmt("%.4o\n", mask
);
12858 if (isdigit((unsigned char) *ap
)) {
12861 if (*ap
>= '8' || *ap
< '0')
12862 ash_msg_and_raise_error(msg_illnum
, argv
[1]);
12863 mask
= (mask
<< 3) + (*ap
- '0');
12864 } while (*++ap
!= '\0');
12867 mask
= ~mask
& 0777;
12868 if (!bb_parse_mode(ap
, &mask
)) {
12869 ash_msg_and_raise_error("illegal mode: %s", ap
);
12871 umask(~mask
& 0777);
12877 static int FAST_FUNC
12878 ulimitcmd(int argc UNUSED_PARAM
, char **argv
)
12880 return shell_builtin_ulimit(argv
);
12883 /* ============ main() and helpers */
12886 * Called to exit the shell.
12895 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
12896 save_history(line_input_state
);
12899 status
= exitstatus
;
12900 TRACE(("pid %d, exitshell(%d)\n", getpid(), status
));
12901 if (setjmp(loc
.loc
)) {
12902 if (exception_type
== EXEXIT
)
12903 /* dash bug: it just does _exit(exitstatus) here
12904 * but we have to do setjobctl(0) first!
12905 * (bug is still not fixed in dash-0.5.3 - if you run dash
12906 * under Midnight Commander, on exit from dash MC is backgrounded) */
12907 status
= exitstatus
;
12910 exception_handler
= &loc
;
12917 flush_stdout_stderr();
12927 /* from input.c: */
12928 /* we will never free this */
12929 basepf
.next_to_pgetc
= basepf
.buf
= ckmalloc(IBUFSIZ
);
12932 signal(SIGCHLD
, SIG_DFL
);
12933 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12934 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12936 signal(SIGHUP
, SIG_DFL
);
12942 struct stat st1
, st2
;
12945 for (envp
= environ
; envp
&& *envp
; envp
++) {
12946 if (strchr(*envp
, '=')) {
12947 setvareq(*envp
, VEXPORT
|VTEXTFIXED
);
12951 setvar("PPID", utoa(getppid()), 0);
12953 p
= lookupvar("PWD");
12955 if (*p
!= '/' || stat(p
, &st1
) || stat(".", &st2
)
12956 || st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
12966 //usage:#define ash_trivial_usage
12967 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
12968 //usage:#define ash_full_usage "\n\n"
12969 //usage: "Unix shell interpreter"
12971 //usage:#if ENABLE_FEATURE_SH_IS_ASH
12972 //usage:# define sh_trivial_usage ash_trivial_usage
12973 //usage:# define sh_full_usage ash_full_usage
12975 //usage:#if ENABLE_FEATURE_BASH_IS_ASH
12976 //usage:# define bash_trivial_usage ash_trivial_usage
12977 //usage:# define bash_full_usage ash_full_usage
12981 * Process the shell command line arguments.
12984 procargs(char **argv
)
12987 const char *xminusc
;
12992 /* if (xargv[0]) - mmm, this is always true! */
12994 for (i
= 0; i
< NOPTS
; i
++)
12997 if (options(/*cmdline:*/ 1)) {
12998 /* it already printed err message */
12999 raise_exception(EXERROR
);
13003 if (*xargv
== NULL
) {
13005 ash_msg_and_raise_error(bb_msg_requires_arg
, "-c");
13008 if (iflag
== 2 && sflag
== 1 && isatty(0) && isatty(1))
13012 for (i
= 0; i
< NOPTS
; i
++)
13013 if (optlist
[i
] == 2)
13018 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13023 } else if (!sflag
) {
13024 setinputfile(*xargv
, 0);
13027 commandname
= arg0
;
13030 shellparam
.p
= xargv
;
13031 #if ENABLE_ASH_GETOPTS
13032 shellparam
.optind
= 1;
13033 shellparam
.optoff
= -1;
13035 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13037 shellparam
.nparam
++;
13044 * Read /etc/profile or .profile.
13047 read_profile(const char *name
)
13051 if (setinputfile(name
, INPUT_PUSH_FILE
| INPUT_NOFILE_OK
) < 0)
13060 * This routine is called when an error or an interrupt occurs in an
13061 * interactive shell and control is returned to the main command loop.
13069 /* from input.c: */
13070 g_parsefile
->left_in_buffer
= 0;
13071 g_parsefile
->left_in_line
= 0; /* clear input buffer */
13073 /* from parser.c: */
13076 /* from redir.c: */
13077 clearredir(/*drop:*/ 0);
13081 static short profile_buf
[16384];
13082 extern int etext();
13086 * Main routine. We initialize things, parse the arguments, execute
13087 * profiles if we're a login shell, and then call cmdloop to execute
13088 * commands. The setjmp call sets up the location to jump to when an
13089 * exception occurs. When an exception occurs the variable "state"
13090 * is used to figure out how far we had gotten.
13092 int ash_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
13093 int ash_main(int argc UNUSED_PARAM
, char **argv
)
13095 const char *shinit
;
13096 volatile smallint state
;
13097 struct jmploc jmploc
;
13098 struct stackmark smark
;
13100 /* Initialize global data */
13104 #if ENABLE_ASH_ALIAS
13110 monitor(4, etext
, profile_buf
, sizeof(profile_buf
), 50);
13113 #if ENABLE_FEATURE_EDITING
13114 line_input_state
= new_line_input_t(FOR_SHELL
| WITH_PATH_LOOKUP
);
13117 if (setjmp(jmploc
.loc
)) {
13123 e
= exception_type
;
13127 if (e
== EXEXIT
|| s
== 0 || iflag
== 0 || shlvl
) {
13131 outcslow('\n', stderr
);
13134 popstackmark(&smark
);
13135 FORCE_INT_ON
; /* enable interrupts */
13144 exception_handler
= &jmploc
;
13147 TRACE(("Shell args: "));
13148 trace_puts_args(argv
);
13150 rootpid
= getpid();
13153 setstackmark(&smark
);
13156 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13158 const char *hp
= lookupvar("HISTFILE");
13160 hp
= lookupvar("HOME");
13162 char *defhp
= concat_path_file(hp
, ".ash_history");
13163 setvar("HISTFILE", defhp
, 0);
13169 if (argv
[0] && argv
[0][0] == '-')
13173 read_profile("/etc/profile");
13176 read_profile(".profile");
13182 getuid() == geteuid() && getgid() == getegid() &&
13186 shinit
= lookupvar("ENV");
13187 if (shinit
!= NULL
&& *shinit
!= '\0') {
13188 read_profile(shinit
);
13194 /* evalstring pushes parsefile stack.
13195 * Ensure we don't falsely claim that 0 (stdin)
13196 * is one of stacked source fds.
13197 * Testcase: ash -c 'exec 1>&0' must not complain. */
13198 // if (!sflag) g_parsefile->pf_fd = -1;
13199 // ^^ not necessary since now we special-case fd 0
13200 // in is_hidden_fd() to not be considered "hidden fd"
13201 evalstring(minusc
, 0);
13204 if (sflag
|| minusc
== NULL
) {
13205 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13207 const char *hp
= lookupvar("HISTFILE");
13209 line_input_state
->hist_file
= hp
;
13210 # if ENABLE_FEATURE_SH_HISTFILESIZE
13211 hp
= lookupvar("HISTFILESIZE");
13212 line_input_state
->max_history
= size_from_HISTFILESIZE(hp
);
13216 state4
: /* XXX ??? - why isn't this before the "if" statement */
13224 extern void _mcleanup(void);
13228 TRACE(("End of main reached\n"));
13235 * Copyright (c) 1989, 1991, 1993, 1994
13236 * The Regents of the University of California. All rights reserved.
13238 * This code is derived from software contributed to Berkeley by
13239 * Kenneth Almquist.
13241 * Redistribution and use in source and binary forms, with or without
13242 * modification, are permitted provided that the following conditions
13244 * 1. Redistributions of source code must retain the above copyright
13245 * notice, this list of conditions and the following disclaimer.
13246 * 2. Redistributions in binary form must reproduce the above copyright
13247 * notice, this list of conditions and the following disclaimer in the
13248 * documentation and/or other materials provided with the distribution.
13249 * 3. Neither the name of the University nor the names of its contributors
13250 * may be used to endorse or promote products derived from this software
13251 * without specific prior written permission.
13253 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13254 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13255 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13256 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13257 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13258 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13259 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13260 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13261 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13262 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF