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
39 #include "busybox.h" /* for applet_names */
43 #include <sys/times.h>
45 #include "shell_common.h"
47 #if ENABLE_ASH_RANDOM_SUPPORT
50 # define CLEAR_RANDOM_T(rnd) ((void)0)
53 #include "NUM_APPLETS.h"
55 /* STANDALONE does not make sense, and won't compile */
56 # undef CONFIG_FEATURE_SH_STANDALONE
57 # undef ENABLE_FEATURE_SH_STANDALONE
58 # undef IF_FEATURE_SH_STANDALONE
59 # undef IF_NOT_FEATURE_SH_STANDALONE
60 # define ENABLE_FEATURE_SH_STANDALONE 0
61 # define IF_FEATURE_SH_STANDALONE(...)
62 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
66 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
70 # error "Do not even bother, ash will not run on NOMMU machine"
73 //applet:IF_ASH(APPLET(ash, _BB_DIR_BIN, _BB_SUID_DROP))
74 //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, _BB_DIR_BIN, _BB_SUID_DROP, sh))
75 //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, _BB_DIR_BIN, _BB_SUID_DROP, bash))
77 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
78 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
83 //config: depends on !NOMMU
85 //config: Tha 'ash' shell adds about 60k in the default configuration and is
86 //config: the most complete and most pedantically correct shell included with
87 //config: busybox. This shell is actually a derivative of the Debian 'dash'
88 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
89 //config: (written by Kenneth Almquist) from NetBSD.
91 //config:config ASH_BASH_COMPAT
92 //config: bool "bash-compatible extensions"
94 //config: depends on ASH
96 //config: Enable bash-compatible extensions.
98 //config:config ASH_JOB_CONTROL
99 //config: bool "Job control"
101 //config: depends on ASH
103 //config: Enable job control in the ash shell.
105 //config:config ASH_ALIAS
106 //config: bool "alias support"
108 //config: depends on ASH
110 //config: Enable alias support in the ash shell.
112 //config:config ASH_GETOPTS
113 //config: bool "Builtin getopt to parse positional parameters"
115 //config: depends on ASH
117 //config: Enable getopts builtin in the ash shell.
119 //config:config ASH_BUILTIN_ECHO
120 //config: bool "Builtin version of 'echo'"
122 //config: depends on ASH
124 //config: Enable support for echo, builtin to ash.
126 //config:config ASH_BUILTIN_PRINTF
127 //config: bool "Builtin version of 'printf'"
129 //config: depends on ASH
131 //config: Enable support for printf, builtin to ash.
133 //config:config ASH_BUILTIN_TEST
134 //config: bool "Builtin version of 'test'"
136 //config: depends on ASH
138 //config: Enable support for test, builtin to ash.
140 //config:config ASH_CMDCMD
141 //config: bool "'command' command to override shell builtins"
143 //config: depends on ASH
145 //config: Enable support for the ash 'command' builtin, which allows
146 //config: you to run the specified command with the specified arguments,
147 //config: even when there is an ash builtin command with the same name.
149 //config:config ASH_MAIL
150 //config: bool "Check for new mail on interactive shells"
152 //config: depends on ASH
154 //config: Enable "check for new mail" in the ash shell.
156 //config:config ASH_OPTIMIZE_FOR_SIZE
157 //config: bool "Optimize for size instead of speed"
159 //config: depends on ASH
161 //config: Compile ash for reduced size at the price of speed.
163 //config:config ASH_RANDOM_SUPPORT
164 //config: bool "Pseudorandom generator and $RANDOM variable"
166 //config: depends on ASH
168 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
169 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
170 //config: You can reset the generator by using a specified start value.
171 //config: After "unset RANDOM" the generator will switch off and this
172 //config: variable will no longer have special treatment.
174 //config:config ASH_EXPAND_PRMT
175 //config: bool "Expand prompt string"
177 //config: depends on ASH
179 //config: "PS#" may contain volatile content, such as backquote commands.
180 //config: This option recreates the prompt string from the environment
181 //config: variable each time it is displayed.
184 //usage:#define ash_trivial_usage NOUSAGE_STR
185 //usage:#define ash_full_usage ""
186 //usage:#define sh_trivial_usage NOUSAGE_STR
187 //usage:#define sh_full_usage ""
188 //usage:#define bash_trivial_usage NOUSAGE_STR
189 //usage:#define bash_full_usage ""
192 /* ============ Hash table sizes. Configurable. */
196 #define CMDTABLESIZE 31 /* should be prime */
199 /* ============ Shell options */
201 static const char *const optletters_optnames[] = {
216 #if ENABLE_ASH_BASH_COMPAT
225 #define optletters(n) optletters_optnames[n][0]
226 #define optnames(n) (optletters_optnames[n] + 1)
228 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
231 /* ============ Misc data */
233 #define msg_illnum "Illegal number: %s"
236 * We enclose jmp_buf in a structure so that we can declare pointers to
237 * jump locations. The global variable handler contains the location to
238 * jump to when an exception occurs, and the global variable exception_type
239 * contains a code identifying the exception. To implement nested
240 * exception handlers, the user should save the value of handler on entry
241 * to an inner scope, set handler to point to a jmploc structure for the
242 * inner scope, and restore handler on exit from the scope.
248 struct globals_misc {
249 /* pid of main shell */
251 /* shell level: 0 for the main shell, 1 for its children, and so on */
253 #define rootshell (!shlvl)
254 char *minusc; /* argument to -c option */
256 char *curdir; // = nullstr; /* current working directory */
257 char *physdir; // = nullstr; /* physical working directory */
259 char *arg0; /* value of $0 */
261 struct jmploc *exception_handler;
263 volatile int suppress_int; /* counter */
264 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
265 /* last pending signal */
266 volatile /*sig_atomic_t*/ smallint pending_sig;
267 smallint exception_type; /* kind of exception (0..5) */
269 #define EXINT 0 /* SIGINT received */
270 #define EXERROR 1 /* a generic error */
271 #define EXSHELLPROC 2 /* execute a shell procedure */
272 #define EXEXEC 3 /* command execution failed */
273 #define EXEXIT 4 /* exit the shell */
274 #define EXSIG 5 /* trapped signal in wait(1) */
277 char nullstr[1]; /* zero length string */
280 #define eflag optlist[0]
281 #define fflag optlist[1]
282 #define Iflag optlist[2]
283 #define iflag optlist[3]
284 #define mflag optlist[4]
285 #define nflag optlist[5]
286 #define sflag optlist[6]
287 #define xflag optlist[7]
288 #define vflag optlist[8]
289 #define Cflag optlist[9]
290 #define aflag optlist[10]
291 #define bflag optlist[11]
292 #define uflag optlist[12]
293 #define viflag optlist[13]
294 #if ENABLE_ASH_BASH_COMPAT
295 # define pipefail optlist[14]
300 # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
301 # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
304 /* trap handler commands */
306 * Sigmode records the current value of the signal handlers for the various
307 * modes. A value of zero means that the current handler is not known.
308 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
310 char sigmode[NSIG - 1];
311 #define S_DFL 1 /* default signal handling (SIG_DFL) */
312 #define S_CATCH 2 /* signal is caught */
313 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
314 #define S_HARD_IGN 4 /* signal is ignored permenantly */
316 /* indicates specified signal received */
317 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
318 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
320 char **trap_ptr; /* used only by "trap hack" */
322 /* Rarely referenced stuff */
323 #if ENABLE_ASH_RANDOM_SUPPORT
326 pid_t backgndpid; /* pid of last background process */
327 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
329 extern struct globals_misc *const ash_ptr_to_globals_misc;
330 #define G_misc (*ash_ptr_to_globals_misc)
331 #define rootpid (G_misc.rootpid )
332 #define shlvl (G_misc.shlvl )
333 #define minusc (G_misc.minusc )
334 #define curdir (G_misc.curdir )
335 #define physdir (G_misc.physdir )
336 #define arg0 (G_misc.arg0 )
337 #define exception_handler (G_misc.exception_handler)
338 #define exception_type (G_misc.exception_type )
339 #define suppress_int (G_misc.suppress_int )
340 #define pending_int (G_misc.pending_int )
341 #define pending_sig (G_misc.pending_sig )
342 #define isloginsh (G_misc.isloginsh )
343 #define nullstr (G_misc.nullstr )
344 #define optlist (G_misc.optlist )
345 #define sigmode (G_misc.sigmode )
346 #define gotsig (G_misc.gotsig )
347 #define may_have_traps (G_misc.may_have_traps )
348 #define trap (G_misc.trap )
349 #define trap_ptr (G_misc.trap_ptr )
350 #define random_gen (G_misc.random_gen )
351 #define backgndpid (G_misc.backgndpid )
352 #define job_warning (G_misc.job_warning)
353 #define INIT_G_misc() do { \
354 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
362 /* ============ DEBUG */
364 static void trace_printf(const char *fmt, ...);
365 static void trace_vprintf(const char *fmt, va_list va);
366 # define TRACE(param) trace_printf param
367 # define TRACEV(param) trace_vprintf param
368 # define close(fd) do { \
370 if (close(dfd) < 0) \
371 bb_error_msg("bug on %d: closing %d(0x%x)", \
372 __LINE__, dfd, dfd); \
375 # define TRACE(param)
376 # define TRACEV(param)
380 /* ============ Utility functions */
381 #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
383 static int isdigit_str9(const char *str)
385 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
386 while (--maxlen && isdigit(*str))
388 return (*str == '\0');
391 static const char *var_end(const char *var)
400 /* ============ Interrupts / exceptions */
402 * These macros allow the user to suspend the handling of interrupt signals
403 * over a period of time. This is similar to SIGHOLD or to sigblock, but
404 * much more efficient and portable. (But hacking the kernel is so much
405 * more fun than worrying about efficiency and portability. :-))
407 #define INT_OFF do { \
413 * Called to raise an exception. Since C doesn't include exceptions, we
414 * just do a longjmp to the exception handler. The type of exception is
415 * stored in the global variable "exception_type".
417 static void raise_exception(int) NORETURN;
419 raise_exception(int e)
422 if (exception_handler == NULL)
427 longjmp(exception_handler->loc, 1);
430 #define raise_exception(e) do { \
431 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
432 raise_exception(e); \
437 * Called from trap.c when a SIGINT is received. (If the user specifies
438 * that SIGINT is to be trapped or ignored using the trap builtin, then
439 * this routine is not called.) Suppressint is nonzero when interrupts
440 * are held using the INT_OFF macro. (The test for iflag is just
441 * defensive programming.)
443 static void raise_interrupt(void) NORETURN;
445 raise_interrupt(void)
450 /* Signal is not automatically unmasked after it is raised,
451 * do it ourself - unmask all signals */
452 sigprocmask_allsigs(SIG_UNBLOCK);
453 /* pending_sig = 0; - now done in signal_handler() */
456 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
457 if (!(rootshell && iflag)) {
458 /* Kill ourself with SIGINT */
459 signal(SIGINT, SIG_DFL);
464 raise_exception(ex_type);
468 #define raise_interrupt() do { \
469 TRACE(("raising interrupt on line %d\n", __LINE__)); \
474 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
478 if (--suppress_int == 0 && pending_int) {
482 #define INT_ON int_on()
483 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
491 #define FORCE_INT_ON force_int_on()
493 #define SAVE_INT(v) ((v) = suppress_int)
495 #define RESTORE_INT(v) do { \
497 suppress_int = (v); \
498 if (suppress_int == 0 && pending_int) \
503 /* ============ Stdout/stderr output */
506 outstr(const char *p, FILE *file)
514 flush_stdout_stderr(void)
522 outcslow(int c, FILE *dest)
530 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
532 out1fmt(const char *fmt, ...)
539 r = vprintf(fmt, ap);
545 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
547 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
554 ret = vsnprintf(outbuf, length, fmt, ap);
561 out1str(const char *p)
567 out2str(const char *p)
570 flush_stdout_stderr();
574 /* ============ Parser structures */
576 /* control characters in argument strings */
577 #define CTL_FIRST CTLESC
578 #define CTLESC ((unsigned char)'\201') /* escape next character */
579 #define CTLVAR ((unsigned char)'\202') /* variable defn */
580 #define CTLENDVAR ((unsigned char)'\203')
581 #define CTLBACKQ ((unsigned char)'\204')
582 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
583 /* CTLBACKQ | CTLQUOTE == '\205' */
584 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
585 #define CTLENDARI ((unsigned char)'\207')
586 #define CTLQUOTEMARK ((unsigned char)'\210')
587 #define CTL_LAST CTLQUOTEMARK
589 /* variable substitution byte (follows CTLVAR) */
590 #define VSTYPE 0x0f /* type of variable substitution */
591 #define VSNUL 0x10 /* colon--treat the empty string as unset */
592 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
594 /* values of VSTYPE field */
595 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
596 #define VSMINUS 0x2 /* ${var-text} */
597 #define VSPLUS 0x3 /* ${var+text} */
598 #define VSQUESTION 0x4 /* ${var?message} */
599 #define VSASSIGN 0x5 /* ${var=text} */
600 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
601 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
602 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
603 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
604 #define VSLENGTH 0xa /* ${#var} */
605 #if ENABLE_ASH_BASH_COMPAT
606 #define VSSUBSTR 0xc /* ${var:position:length} */
607 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
608 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
611 static const char dolatstr[] ALIGN1 = {
612 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
632 #if ENABLE_ASH_BASH_COMPAT
649 smallint type; /* Nxxxx */
652 union node *redirect;
657 smallint pipe_backgnd;
658 struct nodelist *cmdlist;
664 union node *redirect;
677 union node *elsepart;
704 struct nodelist *backquote;
707 /* nfile and ndup layout must match!
708 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
709 * that it is actually NTO2 (>&file), and change its type.
726 char *_unused_expfname;
745 struct nredir nredir;
746 struct nbinary nbinary;
750 struct nclist nclist;
759 * NODE_EOF is returned by parsecmd when it encounters an end of file.
760 * It must be distinct from NULL.
762 #define NODE_EOF ((union node *) -1L)
765 struct nodelist *next;
778 freefunc(struct funcnode *f)
780 if (f && --f->count < 0)
785 /* ============ Debugging output */
789 static FILE *tracefile;
792 trace_printf(const char *fmt, ...)
799 fprintf(tracefile, "%u ", (int) time(NULL));
801 fprintf(tracefile, "[%u] ", (int) getpid());
803 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
805 vfprintf(tracefile, fmt, va);
810 trace_vprintf(const char *fmt, va_list va)
815 fprintf(tracefile, "%u ", (int) time(NULL));
817 fprintf(tracefile, "[%u] ", (int) getpid());
819 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
820 vfprintf(tracefile, fmt, va);
824 trace_puts(const char *s)
832 trace_puts_quoted(char *s)
839 putc('"', tracefile);
840 for (p = s; *p; p++) {
841 switch ((unsigned char)*p) {
842 case '\n': c = 'n'; goto backslash;
843 case '\t': c = 't'; goto backslash;
844 case '\r': c = 'r'; goto backslash;
845 case '\"': c = '\"'; goto backslash;
846 case '\\': c = '\\'; goto backslash;
847 case CTLESC: c = 'e'; goto backslash;
848 case CTLVAR: c = 'v'; goto backslash;
849 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
850 case CTLBACKQ: c = 'q'; goto backslash;
851 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
853 putc('\\', tracefile);
857 if (*p >= ' ' && *p <= '~')
860 putc('\\', tracefile);
861 putc((*p >> 6) & 03, tracefile);
862 putc((*p >> 3) & 07, tracefile);
863 putc(*p & 07, tracefile);
868 putc('"', tracefile);
872 trace_puts_args(char **ap)
879 trace_puts_quoted(*ap);
881 putc('\n', tracefile);
884 putc(' ', tracefile);
899 /* leave open because libedit might be using it */
902 strcpy(s, "./trace");
904 if (!freopen(s, "a", tracefile)) {
905 fprintf(stderr, "Can't re-open %s\n", s);
910 tracefile = fopen(s, "a");
911 if (tracefile == NULL) {
912 fprintf(stderr, "Can't open %s\n", s);
918 flags = fcntl(fileno(tracefile), F_GETFL);
920 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
922 setlinebuf(tracefile);
923 fputs("\nTracing started.\n", tracefile);
927 indent(int amount, char *pfx, FILE *fp)
931 for (i = 0; i < amount; i++) {
932 if (pfx && i == amount - 1)
938 /* little circular references here... */
939 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
942 sharg(union node *arg, FILE *fp)
945 struct nodelist *bqlist;
946 unsigned char subtype;
948 if (arg->type != NARG) {
949 out1fmt("<node type %d>\n", arg->type);
952 bqlist = arg->narg.backquote;
953 for (p = arg->narg.text; *p; p++) {
954 switch ((unsigned char)*p) {
962 if (subtype == VSLENGTH)
971 switch (subtype & VSTYPE) {
1004 out1fmt("<subtype %d>", subtype);
1011 case CTLBACKQ|CTLQUOTE:
1014 shtree(bqlist->n, -1, NULL, fp);
1025 shcmd(union node *cmd, FILE *fp)
1033 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1039 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1043 switch (np->nfile.type) {
1044 case NTO: s = ">>"+1; dftfd = 1; break;
1045 case NCLOBBER: s = ">|"; dftfd = 1; break;
1046 case NAPPEND: s = ">>"; dftfd = 1; break;
1047 #if ENABLE_ASH_BASH_COMPAT
1050 case NTOFD: s = ">&"; dftfd = 1; break;
1051 case NFROM: s = "<"; break;
1052 case NFROMFD: s = "<&"; break;
1053 case NFROMTO: s = "<>"; break;
1054 default: s = "*error*"; break;
1056 if (np->nfile.fd != dftfd)
1057 fprintf(fp, "%d", np->nfile.fd);
1059 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1060 fprintf(fp, "%d", np->ndup.dupfd);
1062 sharg(np->nfile.fname, fp);
1069 shtree(union node *n, int ind, char *pfx, FILE *fp)
1071 struct nodelist *lp;
1077 indent(ind, pfx, fp);
1079 if (n == NODE_EOF) {
1094 shtree(n->nbinary.ch1, ind, NULL, fp);
1097 shtree(n->nbinary.ch2, ind, NULL, fp);
1105 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1106 shtree(lp->n, 0, NULL, fp);
1110 if (n->npipe.pipe_backgnd)
1116 fprintf(fp, "<node type %d>", n->type);
1124 showtree(union node *n)
1126 trace_puts("showtree called\n");
1127 shtree(n, 1, NULL, stderr);
1133 /* ============ Parser data */
1136 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1139 struct strlist *next;
1146 struct strpush *prev; /* preceding string on stack */
1148 int prev_left_in_line;
1149 #if ENABLE_ASH_ALIAS
1150 struct alias *ap; /* if push was associated with an alias */
1152 char *string; /* remember the string since it may change */
1156 struct parsefile *prev; /* preceding file on stack */
1157 int linno; /* current line */
1158 int pf_fd; /* file descriptor (or -1 if string) */
1159 int left_in_line; /* number of chars left in this line */
1160 int left_in_buffer; /* number of chars left in this buffer past the line */
1161 char *next_to_pgetc; /* next char in buffer */
1162 char *buf; /* input buffer */
1163 struct strpush *strpush; /* for pushing strings at this level */
1164 struct strpush basestrpush; /* so pushing one is fast */
1167 static struct parsefile basepf; /* top level input file */
1168 static struct parsefile *g_parsefile = &basepf; /* current input file */
1169 static int startlinno; /* line # where last token started */
1170 static char *commandname; /* currently executing command */
1171 static struct strlist *cmdenviron; /* environment for builtin command */
1172 static uint8_t exitstatus; /* exit status of last command */
1175 /* ============ Message printing */
1178 ash_vmsg(const char *msg, va_list ap)
1180 fprintf(stderr, "%s: ", arg0);
1182 if (strcmp(arg0, commandname))
1183 fprintf(stderr, "%s: ", commandname);
1184 if (!iflag || g_parsefile->pf_fd > 0)
1185 fprintf(stderr, "line %d: ", startlinno);
1187 vfprintf(stderr, msg, ap);
1188 outcslow('\n', stderr);
1192 * Exverror is called to raise the error exception. If the second argument
1193 * is not NULL then error prints an error message using printf style
1194 * formatting. It then raises the error exception.
1196 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1198 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1202 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1204 TRACE(("\") pid=%d\n", getpid()));
1206 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1211 flush_stdout_stderr();
1212 raise_exception(cond);
1216 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1218 ash_msg_and_raise_error(const char *msg, ...)
1223 ash_vmsg_and_raise(EXERROR, msg, ap);
1228 static void raise_error_syntax(const char *) NORETURN;
1230 raise_error_syntax(const char *msg)
1232 ash_msg_and_raise_error("syntax error: %s", msg);
1236 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1238 ash_msg_and_raise(int cond, const char *msg, ...)
1243 ash_vmsg_and_raise(cond, msg, ap);
1249 * error/warning routines for external builtins
1252 ash_msg(const char *fmt, ...)
1262 * Return a string describing an error. The returned string may be a
1263 * pointer to a static buffer that will be overwritten on the next call.
1264 * Action describes the operation that got the error.
1267 errmsg(int e, const char *em)
1269 if (e == ENOENT || e == ENOTDIR) {
1276 /* ============ Memory allocation */
1279 /* I consider these wrappers nearly useless:
1280 * ok, they return you to nearest exception handler, but
1281 * how much memory do you leak in the process, making
1282 * memory starvation worse?
1285 ckrealloc(void * p, size_t nbytes)
1287 p = realloc(p, nbytes);
1289 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1294 ckmalloc(size_t nbytes)
1296 return ckrealloc(NULL, nbytes);
1300 ckzalloc(size_t nbytes)
1302 return memset(ckmalloc(nbytes), 0, nbytes);
1306 ckstrdup(const char *s)
1308 char *p = strdup(s);
1310 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1314 /* Using bbox equivalents. They exit if out of memory */
1315 # define ckrealloc xrealloc
1316 # define ckmalloc xmalloc
1317 # define ckzalloc xzalloc
1318 # define ckstrdup xstrdup
1322 * It appears that grabstackstr() will barf with such alignments
1323 * because stalloc() will return a string allocated in a new stackblock.
1325 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1327 /* Most machines require the value returned from malloc to be aligned
1328 * in some way. The following macro will get this right
1329 * on many machines. */
1330 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1331 /* Minimum size of a block */
1332 MINSIZE = SHELL_ALIGN(504),
1335 struct stack_block {
1336 struct stack_block *prev;
1337 char space[MINSIZE];
1341 struct stack_block *stackp;
1344 struct stackmark *marknext;
1348 struct globals_memstack {
1349 struct stack_block *g_stackp; // = &stackbase;
1350 struct stackmark *markp;
1351 char *g_stacknxt; // = stackbase.space;
1352 char *sstrend; // = stackbase.space + MINSIZE;
1353 size_t g_stacknleft; // = MINSIZE;
1354 int herefd; // = -1;
1355 struct stack_block stackbase;
1357 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1358 #define G_memstack (*ash_ptr_to_globals_memstack)
1359 #define g_stackp (G_memstack.g_stackp )
1360 #define markp (G_memstack.markp )
1361 #define g_stacknxt (G_memstack.g_stacknxt )
1362 #define sstrend (G_memstack.sstrend )
1363 #define g_stacknleft (G_memstack.g_stacknleft)
1364 #define herefd (G_memstack.herefd )
1365 #define stackbase (G_memstack.stackbase )
1366 #define INIT_G_memstack() do { \
1367 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1369 g_stackp = &stackbase; \
1370 g_stacknxt = stackbase.space; \
1371 g_stacknleft = MINSIZE; \
1372 sstrend = stackbase.space + MINSIZE; \
1377 #define stackblock() ((void *)g_stacknxt)
1378 #define stackblocksize() g_stacknleft
1381 * Parse trees for commands are allocated in lifo order, so we use a stack
1382 * to make this more efficient, and also to avoid all sorts of exception
1383 * handling code to handle interrupts in the middle of a parse.
1385 * The size 504 was chosen because the Ultrix malloc handles that size
1389 stalloc(size_t nbytes)
1394 aligned = SHELL_ALIGN(nbytes);
1395 if (aligned > g_stacknleft) {
1398 struct stack_block *sp;
1400 blocksize = aligned;
1401 if (blocksize < MINSIZE)
1402 blocksize = MINSIZE;
1403 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1404 if (len < blocksize)
1405 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1408 sp->prev = g_stackp;
1409 g_stacknxt = sp->space;
1410 g_stacknleft = blocksize;
1411 sstrend = g_stacknxt + blocksize;
1416 g_stacknxt += aligned;
1417 g_stacknleft -= aligned;
1422 stzalloc(size_t nbytes)
1424 return memset(stalloc(nbytes), 0, nbytes);
1431 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1432 write(STDERR_FILENO, "stunalloc\n", 10);
1436 g_stacknleft += g_stacknxt - (char *)p;
1441 * Like strdup but works with the ash stack.
1444 ststrdup(const char *p)
1446 size_t len = strlen(p) + 1;
1447 return memcpy(stalloc(len), p, len);
1451 setstackmark(struct stackmark *mark)
1453 mark->stackp = g_stackp;
1454 mark->stacknxt = g_stacknxt;
1455 mark->stacknleft = g_stacknleft;
1456 mark->marknext = markp;
1461 popstackmark(struct stackmark *mark)
1463 struct stack_block *sp;
1469 markp = mark->marknext;
1470 while (g_stackp != mark->stackp) {
1472 g_stackp = sp->prev;
1475 g_stacknxt = mark->stacknxt;
1476 g_stacknleft = mark->stacknleft;
1477 sstrend = mark->stacknxt + mark->stacknleft;
1482 * When the parser reads in a string, it wants to stick the string on the
1483 * stack and only adjust the stack pointer when it knows how big the
1484 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1485 * of space on top of the stack and stackblocklen returns the length of
1486 * this block. Growstackblock will grow this space by at least one byte,
1487 * possibly moving it (like realloc). Grabstackblock actually allocates the
1488 * part of the block that has been used.
1491 growstackblock(void)
1495 newlen = g_stacknleft * 2;
1496 if (newlen < g_stacknleft)
1497 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1501 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1502 struct stack_block *oldstackp;
1503 struct stackmark *xmark;
1504 struct stack_block *sp;
1505 struct stack_block *prevstackp;
1509 oldstackp = g_stackp;
1511 prevstackp = sp->prev;
1512 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1513 sp = ckrealloc(sp, grosslen);
1514 sp->prev = prevstackp;
1516 g_stacknxt = sp->space;
1517 g_stacknleft = newlen;
1518 sstrend = sp->space + newlen;
1521 * Stack marks pointing to the start of the old block
1522 * must be relocated to point to the new block
1525 while (xmark != NULL && xmark->stackp == oldstackp) {
1526 xmark->stackp = g_stackp;
1527 xmark->stacknxt = g_stacknxt;
1528 xmark->stacknleft = g_stacknleft;
1529 xmark = xmark->marknext;
1533 char *oldspace = g_stacknxt;
1534 size_t oldlen = g_stacknleft;
1535 char *p = stalloc(newlen);
1537 /* free the space we just allocated */
1538 g_stacknxt = memcpy(p, oldspace, oldlen);
1539 g_stacknleft += newlen;
1544 grabstackblock(size_t len)
1546 len = SHELL_ALIGN(len);
1548 g_stacknleft -= len;
1552 * The following routines are somewhat easier to use than the above.
1553 * The user declares a variable of type STACKSTR, which may be declared
1554 * to be a register. The macro STARTSTACKSTR initializes things. Then
1555 * the user uses the macro STPUTC to add characters to the string. In
1556 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1557 * grown as necessary. When the user is done, she can just leave the
1558 * string there and refer to it using stackblock(). Or she can allocate
1559 * the space for it using grabstackstr(). If it is necessary to allow
1560 * someone else to use the stack temporarily and then continue to grow
1561 * the string, the user should use grabstack to allocate the space, and
1562 * then call ungrabstr(p) to return to the previous mode of operation.
1564 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1565 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1566 * is space for at least one character.
1571 size_t len = stackblocksize();
1572 if (herefd >= 0 && len >= 1024) {
1573 full_write(herefd, stackblock(), len);
1574 return stackblock();
1577 return (char *)stackblock() + len;
1581 * Called from CHECKSTRSPACE.
1584 makestrspace(size_t newlen, char *p)
1586 size_t len = p - g_stacknxt;
1587 size_t size = stackblocksize();
1592 size = stackblocksize();
1594 if (nleft >= newlen)
1598 return (char *)stackblock() + len;
1602 stack_nputstr(const char *s, size_t n, char *p)
1604 p = makestrspace(n, p);
1605 p = (char *)memcpy(p, s, n) + n;
1610 stack_putstr(const char *s, char *p)
1612 return stack_nputstr(s, strlen(s), p);
1616 _STPUTC(int c, char *p)
1624 #define STARTSTACKSTR(p) ((p) = stackblock())
1625 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1626 #define CHECKSTRSPACE(n, p) do { \
1629 size_t m = sstrend - q; \
1631 (p) = makestrspace(l, q); \
1633 #define USTPUTC(c, p) (*(p)++ = (c))
1634 #define STACKSTRNUL(p) do { \
1635 if ((p) == sstrend) \
1636 (p) = growstackstr(); \
1639 #define STUNPUTC(p) (--(p))
1640 #define STTOPC(p) ((p)[-1])
1641 #define STADJUST(amount, p) ((p) += (amount))
1643 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1644 #define ungrabstackstr(s, p) stunalloc(s)
1645 #define stackstrend() ((void *)sstrend)
1648 /* ============ String helpers */
1651 * prefix -- see if pfx is a prefix of string.
1654 prefix(const char *string, const char *pfx)
1657 if (*pfx++ != *string++)
1660 return (char *) string;
1664 * Check for a valid number. This should be elsewhere.
1667 is_number(const char *p)
1672 } while (*++p != '\0');
1677 * Convert a string of digits to an integer, printing an error message on
1681 number(const char *s)
1684 ash_msg_and_raise_error(msg_illnum, s);
1689 * Produce a possibly single quoted string suitable as input to the shell.
1690 * The return string is allocated on the stack.
1693 single_quote(const char *s)
1703 len = strchrnul(s, '\'') - s;
1705 q = p = makestrspace(len + 3, p);
1708 q = (char *)memcpy(q, s, len) + len;
1717 do len++; while (*++s == '\'');
1719 q = p = makestrspace(len + 3, p);
1722 q = (char *)memcpy(q, s - len, len) + len;
1730 return stackblock();
1734 /* ============ nextopt */
1736 static char **argptr; /* argument list for builtin commands */
1737 static char *optionarg; /* set by nextopt (like getopt) */
1738 static char *optptr; /* used by nextopt */
1741 * XXX - should get rid of. Have all builtins use getopt(3).
1742 * The library getopt must have the BSD extension static variable
1743 * "optreset", otherwise it can't be used within the shell safely.
1745 * Standard option processing (a la getopt) for builtin routines.
1746 * The only argument that is passed to nextopt is the option string;
1747 * the other arguments are unnecessary. It returns the character,
1748 * or '\0' on end of input.
1751 nextopt(const char *optstring)
1758 if (p == NULL || *p == '\0') {
1759 /* We ate entire "-param", take next one */
1765 if (*++p == '\0') /* just "-" ? */
1768 if (LONE_DASH(p)) /* "--" ? */
1770 /* p => next "-param" */
1772 /* p => some option char in the middle of a "-param" */
1774 for (q = optstring; *q != c;) {
1776 ash_msg_and_raise_error("illegal option -%c", c);
1784 ash_msg_and_raise_error("no arg for -%c option", c);
1794 /* ============ Shell variables */
1797 * The parsefile structure pointed to by the global variable parsefile
1798 * contains information about the current file being read.
1801 int nparam; /* # of positional parameters (without $0) */
1802 #if ENABLE_ASH_GETOPTS
1803 int optind; /* next parameter to be processed by getopts */
1804 int optoff; /* used by getopts */
1806 unsigned char malloced; /* if parameter list dynamically allocated */
1807 char **p; /* parameter list */
1811 * Free the list of positional parameters.
1814 freeparam(volatile struct shparam *param)
1816 if (param->malloced) {
1818 ap = ap1 = param->p;
1825 #if ENABLE_ASH_GETOPTS
1826 static void FAST_FUNC getoptsreset(const char *value);
1830 struct var *next; /* next entry in hash list */
1831 int flags; /* flags are defined above */
1832 const char *var_text; /* name=value */
1833 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1834 /* the variable gets set/unset */
1838 struct localvar *next; /* next local variable in list */
1839 struct var *vp; /* the variable that was made local */
1840 int flags; /* saved flags */
1841 const char *text; /* saved text */
1845 #define VEXPORT 0x01 /* variable is exported */
1846 #define VREADONLY 0x02 /* variable cannot be modified */
1847 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1848 #define VTEXTFIXED 0x08 /* text is statically allocated */
1849 #define VSTACK 0x10 /* text is allocated on the stack */
1850 #define VUNSET 0x20 /* the variable is not set */
1851 #define VNOFUNC 0x40 /* don't call the callback function */
1852 #define VNOSET 0x80 /* do not set variable - just readonly test */
1853 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1854 #if ENABLE_ASH_RANDOM_SUPPORT
1855 # define VDYNAMIC 0x200 /* dynamic variable */
1861 /* Need to be before varinit_data[] */
1862 #if ENABLE_LOCALE_SUPPORT
1863 static void FAST_FUNC
1864 change_lc_all(const char *value)
1866 if (value && *value != '\0')
1867 setlocale(LC_ALL, value);
1869 static void FAST_FUNC
1870 change_lc_ctype(const char *value)
1872 if (value && *value != '\0')
1873 setlocale(LC_CTYPE, value);
1877 static void chkmail(void);
1878 static void changemail(const char *) FAST_FUNC;
1880 static void changepath(const char *) FAST_FUNC;
1881 #if ENABLE_ASH_RANDOM_SUPPORT
1882 static void change_random(const char *) FAST_FUNC;
1885 static const struct {
1887 const char *var_text;
1888 void (*var_func)(const char *) FAST_FUNC;
1889 } varinit_data[] = {
1890 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1892 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1893 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1895 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1896 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1897 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1898 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1899 #if ENABLE_ASH_GETOPTS
1900 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
1902 #if ENABLE_ASH_RANDOM_SUPPORT
1903 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1905 #if ENABLE_LOCALE_SUPPORT
1906 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1907 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1909 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1910 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1916 struct globals_var {
1917 struct shparam shellparam; /* $@ current positional parameters */
1918 struct redirtab *redirlist;
1920 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1921 struct var *vartab[VTABSIZE];
1922 struct var varinit[ARRAY_SIZE(varinit_data)];
1924 extern struct globals_var *const ash_ptr_to_globals_var;
1925 #define G_var (*ash_ptr_to_globals_var)
1926 #define shellparam (G_var.shellparam )
1927 //#define redirlist (G_var.redirlist )
1928 #define g_nullredirs (G_var.g_nullredirs )
1929 #define preverrout_fd (G_var.preverrout_fd)
1930 #define vartab (G_var.vartab )
1931 #define varinit (G_var.varinit )
1932 #define INIT_G_var() do { \
1934 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1936 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1937 varinit[i].flags = varinit_data[i].flags; \
1938 varinit[i].var_text = varinit_data[i].var_text; \
1939 varinit[i].var_func = varinit_data[i].var_func; \
1943 #define vifs varinit[0]
1945 # define vmail (&vifs)[1]
1946 # define vmpath (&vmail)[1]
1947 # define vpath (&vmpath)[1]
1949 # define vpath (&vifs)[1]
1951 #define vps1 (&vpath)[1]
1952 #define vps2 (&vps1)[1]
1953 #define vps4 (&vps2)[1]
1954 #if ENABLE_ASH_GETOPTS
1955 # define voptind (&vps4)[1]
1956 # if ENABLE_ASH_RANDOM_SUPPORT
1957 # define vrandom (&voptind)[1]
1960 # if ENABLE_ASH_RANDOM_SUPPORT
1961 # define vrandom (&vps4)[1]
1966 * The following macros access the values of the above variables.
1967 * They have to skip over the name. They return the null string
1968 * for unset variables.
1970 #define ifsval() (vifs.var_text + 4)
1971 #define ifsset() ((vifs.flags & VUNSET) == 0)
1973 # define mailval() (vmail.var_text + 5)
1974 # define mpathval() (vmpath.var_text + 9)
1975 # define mpathset() ((vmpath.flags & VUNSET) == 0)
1977 #define pathval() (vpath.var_text + 5)
1978 #define ps1val() (vps1.var_text + 4)
1979 #define ps2val() (vps2.var_text + 4)
1980 #define ps4val() (vps4.var_text + 4)
1981 #if ENABLE_ASH_GETOPTS
1982 # define optindval() (voptind.var_text + 7)
1986 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1987 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1989 #if ENABLE_ASH_GETOPTS
1990 static void FAST_FUNC
1991 getoptsreset(const char *value)
1993 shellparam.optind = number(value);
1994 shellparam.optoff = -1;
1999 * Return of a legal variable name (a letter or underscore followed by zero or
2000 * more letters, underscores, and digits).
2002 static char* FAST_FUNC
2003 endofname(const char *name)
2011 if (!is_in_name(*p))
2018 * Compares two strings up to the first = or '\0'. The first
2019 * string must be terminated by '='; the second may be terminated by
2020 * either '=' or '\0'.
2023 varcmp(const char *p, const char *q)
2027 while ((c = *p) == (d = *q)) {
2042 * Find the appropriate entry in the hash table from the name.
2044 static struct var **
2045 hashvar(const char *p)
2049 hashval = ((unsigned char) *p) << 4;
2050 while (*p && *p != '=')
2051 hashval += (unsigned char) *p++;
2052 return &vartab[hashval % VTABSIZE];
2056 vpcmp(const void *a, const void *b)
2058 return varcmp(*(const char **)a, *(const char **)b);
2062 * This routine initializes the builtin variables.
2072 * PS1 depends on uid
2074 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2075 vps1.var_text = "PS1=\\w \\$ ";
2078 vps1.var_text = "PS1=# ";
2081 end = vp + ARRAY_SIZE(varinit);
2083 vpp = hashvar(vp->var_text);
2086 } while (++vp < end);
2089 static struct var **
2090 findvar(struct var **vpp, const char *name)
2092 for (; *vpp; vpp = &(*vpp)->next) {
2093 if (varcmp((*vpp)->var_text, name) == 0) {
2101 * Find the value of a variable. Returns NULL if not set.
2103 static const char* FAST_FUNC
2104 lookupvar(const char *name)
2108 v = *findvar(hashvar(name), name);
2110 #if ENABLE_ASH_RANDOM_SUPPORT
2112 * Dynamic variables are implemented roughly the same way they are
2113 * in bash. Namely, they're "special" so long as they aren't unset.
2114 * As soon as they're unset, they're no longer dynamic, and dynamic
2115 * lookup will no longer happen at that point. -- PFM.
2117 if (v->flags & VDYNAMIC)
2120 if (!(v->flags & VUNSET))
2121 return var_end(v->var_text);
2127 * Search the environment of a builtin command.
2130 bltinlookup(const char *name)
2134 for (sp = cmdenviron; sp; sp = sp->next) {
2135 if (varcmp(sp->text, name) == 0)
2136 return var_end(sp->text);
2138 return lookupvar(name);
2142 * Same as setvar except that the variable and value are passed in
2143 * the first argument as name=value. Since the first argument will
2144 * be actually stored in the table, it should not be a string that
2146 * Called with interrupts off.
2149 setvareq(char *s, int flags)
2151 struct var *vp, **vpp;
2154 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2155 vp = *findvar(vpp, s);
2157 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2160 if (flags & VNOSAVE)
2163 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2169 if (vp->var_func && !(flags & VNOFUNC))
2170 vp->var_func(var_end(s));
2172 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2173 free((char*)vp->var_text);
2175 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2177 /* variable s is not found */
2180 vp = ckzalloc(sizeof(*vp));
2182 /*vp->func = NULL; - ckzalloc did it */
2185 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2192 * Set the value of a variable. The flags argument is ored with the
2193 * flags of the variable. If val is NULL, the variable is unset.
2196 setvar(const char *name, const char *val, int flags)
2203 q = endofname(name);
2204 p = strchrnul(q, '=');
2206 if (!namelen || p != q)
2207 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2212 vallen = strlen(val);
2215 nameeq = ckmalloc(namelen + vallen + 2);
2216 p = (char *)memcpy(nameeq, name, namelen) + namelen;
2219 p = (char *)memcpy(p, val, vallen) + vallen;
2222 setvareq(nameeq, flags | VNOSAVE);
2226 static void FAST_FUNC
2227 setvar2(const char *name, const char *val)
2229 setvar(name, val, 0);
2232 #if ENABLE_ASH_GETOPTS
2234 * Safe version of setvar, returns 1 on success 0 on failure.
2237 setvarsafe(const char *name, const char *val, int flags)
2240 volatile int saveint;
2241 struct jmploc *volatile savehandler = exception_handler;
2242 struct jmploc jmploc;
2245 if (setjmp(jmploc.loc))
2248 exception_handler = &jmploc;
2249 setvar(name, val, flags);
2252 exception_handler = savehandler;
2253 RESTORE_INT(saveint);
2259 * Unset the specified variable.
2262 unsetvar(const char *s)
2268 vpp = findvar(hashvar(s), s);
2272 int flags = vp->flags;
2275 if (flags & VREADONLY)
2277 #if ENABLE_ASH_RANDOM_SUPPORT
2278 vp->flags &= ~VDYNAMIC;
2282 if ((flags & VSTRFIXED) == 0) {
2284 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2285 free((char*)vp->var_text);
2291 vp->flags &= ~VEXPORT;
2301 * Process a linked list of variable assignments.
2304 listsetvar(struct strlist *list_set_var, int flags)
2306 struct strlist *lp = list_set_var;
2312 setvareq(lp->text, flags);
2319 * Generate a list of variables satisfying the given conditions.
2322 listvars(int on, int off, char ***end)
2333 for (vp = *vpp; vp; vp = vp->next) {
2334 if ((vp->flags & mask) == on) {
2335 if (ep == stackstrend())
2336 ep = growstackstr();
2337 *ep++ = (char*)vp->var_text;
2340 } while (++vpp < vartab + VTABSIZE);
2341 if (ep == stackstrend())
2342 ep = growstackstr();
2346 return grabstackstr(ep);
2350 /* ============ Path search helper
2352 * The variable path (passed by reference) should be set to the start
2353 * of the path before the first call; path_advance will update
2354 * this value as it proceeds. Successive calls to path_advance will return
2355 * the possible path expansions in sequence. If an option (indicated by
2356 * a percent sign) appears in the path entry then the global variable
2357 * pathopt will be set to point to it; otherwise pathopt will be set to
2360 static const char *pathopt; /* set by path_advance */
2363 path_advance(const char **path, const char *name)
2373 for (p = start; *p && *p != ':' && *p != '%'; p++)
2375 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2376 while (stackblocksize() < len)
2380 memcpy(q, start, p - start);
2388 while (*p && *p != ':')
2395 return stalloc(len);
2399 /* ============ Prompt */
2401 static smallint doprompt; /* if set, prompt the user */
2402 static smallint needprompt; /* true if interactive and at start of line */
2404 #if ENABLE_FEATURE_EDITING
2405 static line_input_t *line_input_state;
2406 static const char *cmdedit_prompt;
2408 putprompt(const char *s)
2410 if (ENABLE_ASH_EXPAND_PRMT) {
2411 free((char*)cmdedit_prompt);
2412 cmdedit_prompt = ckstrdup(s);
2419 putprompt(const char *s)
2425 #if ENABLE_ASH_EXPAND_PRMT
2426 /* expandstr() needs parsing machinery, so it is far away ahead... */
2427 static const char *expandstr(const char *ps);
2429 #define expandstr(s) s
2433 setprompt(int whichprompt)
2436 #if ENABLE_ASH_EXPAND_PRMT
2437 struct stackmark smark;
2442 switch (whichprompt) {
2452 #if ENABLE_ASH_EXPAND_PRMT
2453 setstackmark(&smark);
2454 stalloc(stackblocksize());
2456 putprompt(expandstr(prompt));
2457 #if ENABLE_ASH_EXPAND_PRMT
2458 popstackmark(&smark);
2463 /* ============ The cd and pwd commands */
2465 #define CD_PHYSICAL 1
2475 while ((i = nextopt("LP")) != '\0') {
2477 flags ^= CD_PHYSICAL;
2486 * Update curdir (the name of the current directory) in response to a
2490 updatepwd(const char *dir)
2497 cdcomppath = ststrdup(dir);
2500 if (curdir == nullstr)
2502 new = stack_putstr(curdir, new);
2504 new = makestrspace(strlen(dir) + 2, new);
2505 lim = (char *)stackblock() + 1;
2509 if (new > lim && *lim == '/')
2514 if (dir[1] == '/' && dir[2] != '/') {
2520 p = strtok(cdcomppath, "/");
2524 if (p[1] == '.' && p[2] == '\0') {
2536 new = stack_putstr(p, new);
2544 return stackblock();
2548 * Find out what the current directory is. If we already know the current
2549 * directory, this routine returns immediately.
2554 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2555 return dir ? dir : nullstr;
2559 setpwd(const char *val, int setold)
2563 oldcur = dir = curdir;
2566 setvar("OLDPWD", oldcur, VEXPORT);
2569 if (physdir != nullstr) {
2570 if (physdir != oldcur)
2574 if (oldcur == val || !val) {
2580 dir = ckstrdup(val);
2581 if (oldcur != dir && oldcur != nullstr) {
2586 setvar("PWD", dir, VEXPORT);
2589 static void hashcd(void);
2592 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2593 * know that the current directory has changed.
2596 docd(const char *dest, int flags)
2598 const char *dir = NULL;
2601 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2604 if (!(flags & CD_PHYSICAL)) {
2605 dir = updatepwd(dest);
2619 static int FAST_FUNC
2620 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2632 dest = bltinlookup("HOME");
2633 else if (LONE_DASH(dest)) {
2634 dest = bltinlookup("OLDPWD");
2656 path = bltinlookup("CDPATH");
2665 p = path_advance(&path, dest);
2666 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2670 if (!docd(p, flags))
2675 ash_msg_and_raise_error("can't cd to %s", dest);
2678 if (flags & CD_PRINT)
2679 out1fmt("%s\n", curdir);
2683 static int FAST_FUNC
2684 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2687 const char *dir = curdir;
2691 if (physdir == nullstr)
2695 out1fmt("%s\n", dir);
2700 /* ============ ... */
2703 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2705 /* Syntax classes */
2706 #define CWORD 0 /* character is nothing special */
2707 #define CNL 1 /* newline character */
2708 #define CBACK 2 /* a backslash character */
2709 #define CSQUOTE 3 /* single quote */
2710 #define CDQUOTE 4 /* double quote */
2711 #define CENDQUOTE 5 /* a terminating quote */
2712 #define CBQUOTE 6 /* backwards single quote */
2713 #define CVAR 7 /* a dollar sign */
2714 #define CENDVAR 8 /* a '}' character */
2715 #define CLP 9 /* a left paren in arithmetic */
2716 #define CRP 10 /* a right paren in arithmetic */
2717 #define CENDFILE 11 /* end of file */
2718 #define CCTL 12 /* like CWORD, except it must be escaped */
2719 #define CSPCL 13 /* these terminate a word */
2720 #define CIGN 14 /* character should be ignored */
2723 #if ENABLE_ASH_ALIAS
2727 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2729 #if ENABLE_SH_MATH_SUPPORT
2730 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2732 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2734 static const uint16_t S_I_T[] = {
2735 #if ENABLE_ASH_ALIAS
2736 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2738 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2739 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2740 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2741 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2742 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2743 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2744 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2745 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2746 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2747 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2748 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2749 #if !USE_SIT_FUNCTION
2750 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2751 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2752 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2756 /* Constants below must match table above */
2758 #if ENABLE_ASH_ALIAS
2759 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2761 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2762 CNL_CNL_CNL_CNL , /* 2 */
2763 CWORD_CCTL_CCTL_CWORD , /* 3 */
2764 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2765 CVAR_CVAR_CWORD_CVAR , /* 5 */
2766 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2767 CSPCL_CWORD_CWORD_CLP , /* 7 */
2768 CSPCL_CWORD_CWORD_CRP , /* 8 */
2769 CBACK_CBACK_CCTL_CBACK , /* 9 */
2770 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2771 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2772 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2773 CWORD_CWORD_CWORD_CWORD , /* 13 */
2774 CCTL_CCTL_CCTL_CCTL , /* 14 */
2777 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2778 * caller must ensure proper cast on it if c is *char_ptr!
2780 /* Values for syntax param */
2781 #define BASESYNTAX 0 /* not in quotes */
2782 #define DQSYNTAX 1 /* in double quotes */
2783 #define SQSYNTAX 2 /* in single quotes */
2784 #define ARISYNTAX 3 /* in arithmetic */
2785 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2787 #if USE_SIT_FUNCTION
2790 SIT(int c, int syntax)
2792 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
2793 # if ENABLE_ASH_ALIAS
2794 static const uint8_t syntax_index_table[] ALIGN1 = {
2795 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2796 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2797 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2801 static const uint8_t syntax_index_table[] ALIGN1 = {
2802 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2803 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2804 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2813 # if ENABLE_ASH_ALIAS
2819 /* Cast is purely for paranoia here,
2820 * just in case someone passed signed char to us */
2821 if ((unsigned char)c >= CTL_FIRST
2822 && (unsigned char)c <= CTL_LAST
2826 s = strchrnul(spec_symbls, c);
2829 indx = syntax_index_table[s - spec_symbls];
2831 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2834 #else /* !USE_SIT_FUNCTION */
2836 static const uint8_t syntax_index_table[] = {
2837 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2838 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2848 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2849 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2871 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2872 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2873 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2874 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2875 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2876 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2878 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2879 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2880 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2881 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2882 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2883 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2884 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2885 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2886 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2887 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2888 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2889 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2890 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2891 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2892 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2893 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2894 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2895 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2896 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2897 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2898 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2899 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2900 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2901 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2902 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2904 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2907 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2908 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2909 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2910 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2926 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2931 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2935 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2963 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2964 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2966 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2968 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2969 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2970 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2971 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2972 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2973 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2974 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2975 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2987 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2988 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2989 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2990 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2991 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2992 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2993 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2994 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2995 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2996 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2997 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2998 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2999 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3000 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3001 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3002 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3003 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3004 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3005 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3006 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3007 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3008 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3009 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3010 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3011 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3012 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3014 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3015 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3016 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3017 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3018 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3094 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3095 # if ENABLE_ASH_ALIAS
3096 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3100 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3102 #endif /* !USE_SIT_FUNCTION */
3105 /* ============ Alias handling */
3107 #if ENABLE_ASH_ALIAS
3109 #define ALIASINUSE 1
3120 static struct alias **atab; // [ATABSIZE];
3121 #define INIT_G_alias() do { \
3122 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3126 static struct alias **
3127 __lookupalias(const char *name) {
3128 unsigned int hashval;
3135 ch = (unsigned char)*p;
3139 ch = (unsigned char)*++p;
3141 app = &atab[hashval % ATABSIZE];
3143 for (; *app; app = &(*app)->next) {
3144 if (strcmp(name, (*app)->name) == 0) {
3152 static struct alias *
3153 lookupalias(const char *name, int check)
3155 struct alias *ap = *__lookupalias(name);
3157 if (check && ap && (ap->flag & ALIASINUSE))
3162 static struct alias *
3163 freealias(struct alias *ap)
3167 if (ap->flag & ALIASINUSE) {
3168 ap->flag |= ALIASDEAD;
3180 setalias(const char *name, const char *val)
3182 struct alias *ap, **app;
3184 app = __lookupalias(name);
3188 if (!(ap->flag & ALIASINUSE)) {
3191 ap->val = ckstrdup(val);
3192 ap->flag &= ~ALIASDEAD;
3195 ap = ckzalloc(sizeof(struct alias));
3196 ap->name = ckstrdup(name);
3197 ap->val = ckstrdup(val);
3198 /*ap->flag = 0; - ckzalloc did it */
3199 /*ap->next = NULL;*/
3206 unalias(const char *name)
3210 app = __lookupalias(name);
3214 *app = freealias(*app);
3225 struct alias *ap, **app;
3229 for (i = 0; i < ATABSIZE; i++) {
3231 for (ap = *app; ap; ap = *app) {
3232 *app = freealias(*app);
3242 printalias(const struct alias *ap)
3244 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3248 * TODO - sort output
3250 static int FAST_FUNC
3251 aliascmd(int argc UNUSED_PARAM, char **argv)
3260 for (i = 0; i < ATABSIZE; i++) {
3261 for (ap = atab[i]; ap; ap = ap->next) {
3267 while ((n = *++argv) != NULL) {
3268 v = strchr(n+1, '=');
3269 if (v == NULL) { /* n+1: funny ksh stuff */
3270 ap = *__lookupalias(n);
3272 fprintf(stderr, "%s: %s not found\n", "alias", n);
3285 static int FAST_FUNC
3286 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3290 while ((i = nextopt("a")) != '\0') {
3296 for (i = 0; *argptr; argptr++) {
3297 if (unalias(*argptr)) {
3298 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3306 #endif /* ASH_ALIAS */
3309 /* ============ jobs.c */
3311 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3314 #define FORK_NOJOB 2
3316 /* mode flags for showjob(s) */
3317 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3318 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3319 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3322 * A job structure contains information about a job. A job is either a
3323 * single process or a set of processes contained in a pipeline. In the
3324 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3328 pid_t ps_pid; /* process id */
3329 int ps_status; /* last process status from wait() */
3330 char *ps_cmd; /* text of command being run */
3334 struct procstat ps0; /* status of process */
3335 struct procstat *ps; /* status or processes when more than one */
3337 int stopstatus; /* status of a stopped job */
3340 nprocs: 16, /* number of processes */
3342 #define JOBRUNNING 0 /* at least one proc running */
3343 #define JOBSTOPPED 1 /* all procs are stopped */
3344 #define JOBDONE 2 /* all procs are completed */
3346 sigint: 1, /* job was killed by SIGINT */
3347 jobctl: 1, /* job running under job control */
3349 waited: 1, /* true if this entry has been waited for */
3350 used: 1, /* true if this entry is in used */
3351 changed: 1; /* true if status has changed */
3352 struct job *prev_job; /* previous job */
3355 static struct job *makejob(/*union node *,*/ int);
3356 static int forkshell(struct job *, union node *, int);
3357 static int waitforjob(struct job *);
3360 enum { doing_jobctl = 0 };
3361 #define setjobctl(on) do {} while (0)
3363 static smallint doing_jobctl; //references:8
3364 static void setjobctl(int);
3371 ignoresig(int signo)
3373 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3374 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3375 /* No, need to do it */
3376 signal(signo, SIG_IGN);
3378 sigmode[signo - 1] = S_HARD_IGN;
3382 * Only one usage site - in setsignal()
3385 signal_handler(int signo)
3387 gotsig[signo - 1] = 1;
3389 if (signo == SIGINT && !trap[SIGINT]) {
3390 if (!suppress_int) {
3392 raise_interrupt(); /* does not return */
3396 pending_sig = signo;
3401 * Set the signal handler for the specified signal. The routine figures
3402 * out what it should be set to.
3405 setsignal(int signo)
3408 char cur_act, new_act;
3409 struct sigaction act;
3413 if (t != NULL) { /* trap for this sig is set */
3415 if (t[0] == '\0') /* trap is "": ignore this sig */
3419 if (rootshell && new_act == S_DFL) {
3422 if (iflag || minusc || sflag == 0)
3431 * "In all cases, bash ignores SIGQUIT. Non-builtin
3432 * commands run by bash have signal handlers
3433 * set to the values inherited by the shell
3434 * from its parent". */
3450 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3451 //whereas we have to restore it to what shell got on entry
3452 //from the parent. See comment above
3454 t = &sigmode[signo - 1];
3457 /* current setting is not yet known */
3458 if (sigaction(signo, NULL, &act)) {
3459 /* pretend it worked; maybe we should give a warning,
3460 * but other shells don't. We don't alter sigmode,
3461 * so we retry every time.
3462 * btw, in Linux it never fails. --vda */
3465 if (act.sa_handler == SIG_IGN) {
3466 cur_act = S_HARD_IGN;
3468 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3470 cur_act = S_IGN; /* don't hard ignore these */
3474 if (cur_act == S_HARD_IGN || cur_act == new_act)
3477 act.sa_handler = SIG_DFL;
3480 act.sa_handler = signal_handler;
3481 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3482 sigfillset(&act.sa_mask); /* ditto */
3485 act.sa_handler = SIG_IGN;
3488 sigaction_set(signo, &act);
3493 /* mode flags for set_curjob */
3494 #define CUR_DELETE 2
3495 #define CUR_RUNNING 1
3496 #define CUR_STOPPED 0
3498 /* mode flags for dowait */
3499 #define DOWAIT_NONBLOCK WNOHANG
3500 #define DOWAIT_BLOCK 0
3503 /* pgrp of shell on invocation */
3504 static int initialpgrp; //references:2
3505 static int ttyfd = -1; //5
3508 static struct job *jobtab; //5
3510 static unsigned njobs; //4
3512 static struct job *curjob; //lots
3513 /* number of presumed living untracked jobs */
3514 static int jobless; //4
3517 set_curjob(struct job *jp, unsigned mode)
3520 struct job **jpp, **curp;
3522 /* first remove from list */
3523 jpp = curp = &curjob;
3528 jpp = &jp1->prev_job;
3530 *jpp = jp1->prev_job;
3532 /* Then re-insert in correct position */
3540 /* job being deleted */
3543 /* newly created job or backgrounded job,
3544 put after all stopped jobs. */
3548 if (!jp1 || jp1->state != JOBSTOPPED)
3551 jpp = &jp1->prev_job;
3557 /* newly stopped job - becomes curjob */
3558 jp->prev_job = *jpp;
3566 jobno(const struct job *jp)
3568 return jp - jobtab + 1;
3573 * Convert a job name to a job structure.
3576 #define getjob(name, getctl) getjob(name)
3579 getjob(const char *name, int getctl)
3583 const char *err_msg = "%s: no such job";
3587 char *(*match)(const char *, const char *);
3602 if (c == '+' || c == '%') {
3604 err_msg = "No current job";
3610 err_msg = "No previous job";
3621 jp = jobtab + num - 1;
3636 if (match(jp->ps[0].ps_cmd, p)) {
3640 err_msg = "%s: ambiguous";
3650 err_msg = "job %s not created under job control";
3651 if (getctl && jp->jobctl == 0)
3656 ash_msg_and_raise_error(err_msg, name);
3660 * Mark a job structure as unused.
3663 freejob(struct job *jp)
3665 struct procstat *ps;
3669 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3670 if (ps->ps_cmd != nullstr)
3673 if (jp->ps != &jp->ps0)
3676 set_curjob(jp, CUR_DELETE);
3682 xtcsetpgrp(int fd, pid_t pgrp)
3684 if (tcsetpgrp(fd, pgrp))
3685 ash_msg_and_raise_error("can't set tty process group (%m)");
3689 * Turn job control on and off.
3691 * Note: This code assumes that the third arg to ioctl is a character
3692 * pointer, which is true on Berkeley systems but not System V. Since
3693 * System V doesn't have job control yet, this isn't a problem now.
3695 * Called with interrupts off.
3703 if (on == doing_jobctl || rootshell == 0)
3707 ofd = fd = open(_PATH_TTY, O_RDWR);
3709 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3710 * That sometimes helps to acquire controlling tty.
3711 * Obviously, a workaround for bugs when someone
3712 * failed to provide a controlling tty to bash! :) */
3718 fd = fcntl(fd, F_DUPFD, 10);
3723 /* fd is a tty at this point */
3724 close_on_exec_on(fd);
3725 do { /* while we are in the background */
3726 pgrp = tcgetpgrp(fd);
3729 ash_msg("can't access tty; job control turned off");
3733 if (pgrp == getpgrp())
3744 xtcsetpgrp(fd, pgrp);
3746 /* turning job control off */
3749 /* was xtcsetpgrp, but this can make exiting ash
3750 * loop forever if pty is already deleted */
3751 tcsetpgrp(fd, pgrp);
3765 static int FAST_FUNC
3766 killcmd(int argc, char **argv)
3769 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3771 if (argv[i][0] == '%') {
3772 struct job *jp = getjob(argv[i], 0);
3773 unsigned pid = jp->ps[0].ps_pid;
3774 /* Enough space for ' -NNN<nul>' */
3775 argv[i] = alloca(sizeof(int)*3 + 3);
3776 /* kill_main has matching code to expect
3777 * leading space. Needed to not confuse
3778 * negative pids with "kill -SIGNAL_NO" syntax */
3779 sprintf(argv[i], " -%u", pid);
3781 } while (argv[++i]);
3783 return kill_main(argc, argv);
3787 showpipe(struct job *jp /*, FILE *out*/)
3789 struct procstat *ps;
3790 struct procstat *psend;
3792 psend = jp->ps + jp->nprocs;
3793 for (ps = jp->ps + 1; ps < psend; ps++)
3794 printf(" | %s", ps->ps_cmd);
3795 outcslow('\n', stdout);
3796 flush_stdout_stderr();
3801 restartjob(struct job *jp, int mode)
3803 struct procstat *ps;
3809 if (jp->state == JOBDONE)
3811 jp->state = JOBRUNNING;
3812 pgid = jp->ps[0].ps_pid;
3813 if (mode == FORK_FG)
3814 xtcsetpgrp(ttyfd, pgid);
3815 killpg(pgid, SIGCONT);
3819 if (WIFSTOPPED(ps->ps_status)) {
3825 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3830 static int FAST_FUNC
3831 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
3837 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3841 jp = getjob(*argv, 1);
3842 if (mode == FORK_BG) {
3843 set_curjob(jp, CUR_RUNNING);
3844 printf("[%d] ", jobno(jp));
3846 out1str(jp->ps[0].ps_cmd);
3847 showpipe(jp /*, stdout*/);
3848 retval = restartjob(jp, mode);
3849 } while (*argv && *++argv);
3855 sprint_status(char *s, int status, int sigonly)
3861 if (!WIFEXITED(status)) {
3863 if (WIFSTOPPED(status))
3864 st = WSTOPSIG(status);
3867 st = WTERMSIG(status);
3869 if (st == SIGINT || st == SIGPIPE)
3872 if (WIFSTOPPED(status))
3877 col = fmtstr(s, 32, strsignal(st));
3878 if (WCOREDUMP(status)) {
3879 col += fmtstr(s + col, 16, " (core dumped)");
3881 } else if (!sigonly) {
3882 st = WEXITSTATUS(status);
3884 col = fmtstr(s, 16, "Done(%d)", st);
3886 col = fmtstr(s, 16, "Done");
3893 dowait(int wait_flags, struct job *job)
3898 struct job *thisjob;
3901 TRACE(("dowait(0x%x) called\n", wait_flags));
3903 /* Do a wait system call. If job control is compiled in, we accept
3904 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3905 * NB: _not_ safe_waitpid, we need to detect EINTR */
3907 wait_flags |= WUNTRACED;
3908 pid = waitpid(-1, &status, wait_flags);
3909 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3910 pid, status, errno, strerror(errno)));
3916 for (jp = curjob; jp; jp = jp->prev_job) {
3917 struct procstat *ps;
3918 struct procstat *psend;
3919 if (jp->state == JOBDONE)
3923 psend = ps + jp->nprocs;
3925 if (ps->ps_pid == pid) {
3926 TRACE(("Job %d: changing status of proc %d "
3927 "from 0x%x to 0x%x\n",
3928 jobno(jp), pid, ps->ps_status, status));
3929 ps->ps_status = status;
3932 if (ps->ps_status == -1)
3935 if (state == JOBRUNNING)
3937 if (WIFSTOPPED(ps->ps_status)) {
3938 jp->stopstatus = ps->ps_status;
3942 } while (++ps < psend);
3947 if (!WIFSTOPPED(status))
3953 if (state != JOBRUNNING) {
3954 thisjob->changed = 1;
3956 if (thisjob->state != state) {
3957 TRACE(("Job %d: changing state from %d to %d\n",
3958 jobno(thisjob), thisjob->state, state));
3959 thisjob->state = state;
3961 if (state == JOBSTOPPED) {
3962 set_curjob(thisjob, CUR_STOPPED);
3971 if (thisjob && thisjob == job) {
3975 len = sprint_status(s, status, 1);
3986 blocking_wait_with_raise_on_sig(void)
3988 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
3989 if (pid <= 0 && pending_sig)
3990 raise_exception(EXSIG);
3996 showjob(FILE *out, struct job *jp, int mode)
3998 struct procstat *ps;
3999 struct procstat *psend;
4006 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4007 /* just output process (group) id of pipeline */
4008 fprintf(out, "%d\n", ps->ps_pid);
4012 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4017 else if (curjob && jp == curjob->prev_job)
4020 if (mode & SHOW_PIDS)
4021 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4023 psend = ps + jp->nprocs;
4025 if (jp->state == JOBRUNNING) {
4026 strcpy(s + col, "Running");
4027 col += sizeof("Running") - 1;
4029 int status = psend[-1].ps_status;
4030 if (jp->state == JOBSTOPPED)
4031 status = jp->stopstatus;
4032 col += sprint_status(s + col, status, 0);
4034 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4036 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4037 * or prints several "PID | <cmdN>" lines,
4038 * depending on SHOW_PIDS bit.
4039 * We do not print status of individual processes
4040 * between PID and <cmdN>. bash does it, but not very well:
4041 * first line shows overall job status, not process status,
4042 * making it impossible to know 1st process status.
4046 /* for each process */
4049 if (mode & SHOW_PIDS)
4050 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4052 fprintf(out, "%s%*c%s%s",
4054 33 - col >= 0 ? 33 - col : 0, ' ',
4055 ps == jp->ps ? "" : "| ",
4058 } while (++ps != psend);
4059 outcslow('\n', out);
4063 if (jp->state == JOBDONE) {
4064 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4070 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4071 * statuses have changed since the last call to showjobs.
4074 showjobs(FILE *out, int mode)
4078 TRACE(("showjobs(0x%x) called\n", mode));
4080 /* Handle all finished jobs */
4081 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4084 for (jp = curjob; jp; jp = jp->prev_job) {
4085 if (!(mode & SHOW_CHANGED) || jp->changed) {
4086 showjob(out, jp, mode);
4091 static int FAST_FUNC
4092 jobscmd(int argc UNUSED_PARAM, char **argv)
4097 while ((m = nextopt("lp")) != '\0') {
4101 mode |= SHOW_ONLY_PGID;
4107 showjob(stdout, getjob(*argv, 0), mode);
4110 showjobs(stdout, mode);
4117 /* Called only on finished or stopped jobs (no members are running) */
4119 getstatus(struct job *job)
4123 struct procstat *ps;
4125 /* Fetch last member's status */
4126 ps = job->ps + job->nprocs - 1;
4127 status = ps->ps_status;
4129 /* "set -o pipefail" mode: use last _nonzero_ status */
4130 while (status == 0 && --ps >= job->ps)
4131 status = ps->ps_status;
4134 retval = WEXITSTATUS(status);
4135 if (!WIFEXITED(status)) {
4137 retval = WSTOPSIG(status);
4138 if (!WIFSTOPPED(status))
4141 /* XXX: limits number of signals */
4142 retval = WTERMSIG(status);
4144 if (retval == SIGINT)
4150 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4151 jobno(job), job->nprocs, status, retval));
4155 static int FAST_FUNC
4156 waitcmd(int argc UNUSED_PARAM, char **argv)
4163 raise_exception(EXSIG);
4170 /* wait for all jobs */
4174 if (!jp) /* no running procs */
4176 if (jp->state == JOBRUNNING)
4181 blocking_wait_with_raise_on_sig();
4183 * "When bash is waiting for an asynchronous command via
4184 * the wait builtin, the reception of a signal for which a trap
4185 * has been set will cause the wait builtin to return immediately
4186 * with an exit status greater than 128, immediately after which
4187 * the trap is executed."
4189 * blocking_wait_with_raise_on_sig raises signal handlers
4190 * if it gets no pid (pid < 0). However,
4191 * if child sends us a signal *and immediately exits*,
4192 * blocking_wait_with_raise_on_sig gets pid > 0
4193 * and does not handle pending_sig. Check this case: */
4195 raise_exception(EXSIG);
4201 if (**argv != '%') {
4202 pid_t pid = number(*argv);
4207 if (job->ps[job->nprocs - 1].ps_pid == pid)
4209 job = job->prev_job;
4212 job = getjob(*argv, 0);
4213 /* loop until process terminated or stopped */
4214 while (job->state == JOBRUNNING)
4215 blocking_wait_with_raise_on_sig();
4217 retval = getstatus(job);
4230 struct job *jp, *jq;
4232 len = njobs * sizeof(*jp);
4234 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4236 offset = (char *)jp - (char *)jq;
4238 /* Relocate pointers */
4241 jq = (struct job *)((char *)jq + l);
4245 #define joff(p) ((struct job *)((char *)(p) + l))
4246 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4247 if (joff(jp)->ps == &jq->ps0)
4248 jmove(joff(jp)->ps);
4249 if (joff(jp)->prev_job)
4250 jmove(joff(jp)->prev_job);
4260 jp = (struct job *)((char *)jp + len);
4264 } while (--jq >= jp);
4269 * Return a new job structure.
4270 * Called with interrupts off.
4273 makejob(/*union node *node,*/ int nprocs)
4278 for (i = njobs, jp = jobtab; ; jp++) {
4285 if (jp->state != JOBDONE || !jp->waited)
4294 memset(jp, 0, sizeof(*jp));
4296 /* jp->jobctl is a bitfield.
4297 * "jp->jobctl |= jobctl" likely to give awful code */
4301 jp->prev_job = curjob;
4306 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4308 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4315 * Return a string identifying a command (to be printed by the
4318 static char *cmdnextc;
4321 cmdputs(const char *s)
4323 static const char vstype[VSTYPE + 1][3] = {
4324 "", "}", "-", "+", "?", "=",
4325 "%", "%%", "#", "##"
4326 IF_ASH_BASH_COMPAT(, ":", "/", "//")
4329 const char *p, *str;
4333 unsigned char subtype = 0;
4337 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4339 while ((c = *p++) != '\0') {
4347 if ((subtype & VSTYPE) == VSLENGTH)
4351 if (!(subtype & VSQUOTE) == !(quoted & 1))
4357 str = "\"}" + !(quoted & 1);
4364 case CTLBACKQ+CTLQUOTE:
4367 #if ENABLE_SH_MATH_SUPPORT
4382 if ((subtype & VSTYPE) != VSNORMAL)
4384 str = vstype[subtype & VSTYPE];
4385 if (subtype & VSNUL)
4394 /* These can only happen inside quotes */
4407 while ((c = *str++) != '\0') {
4410 } /* while *p++ not NUL */
4413 USTPUTC('"', nextc);
4419 /* cmdtxt() and cmdlist() call each other */
4420 static void cmdtxt(union node *n);
4423 cmdlist(union node *np, int sep)
4425 for (; np; np = np->narg.next) {
4429 if (sep && np->narg.next)
4435 cmdtxt(union node *n)
4438 struct nodelist *lp;
4449 lp = n->npipe.cmdlist;
4467 cmdtxt(n->nbinary.ch1);
4483 cmdtxt(n->nif.test);
4485 if (n->nif.elsepart) {
4486 cmdtxt(n->nif.ifpart);
4488 n = n->nif.elsepart;
4506 cmdtxt(n->nbinary.ch1);
4516 cmdputs(n->nfor.var);
4518 cmdlist(n->nfor.args, 1);
4523 cmdputs(n->narg.text);
4527 cmdlist(n->ncmd.args, 1);
4528 cmdlist(n->ncmd.redirect, 0);
4541 cmdputs(n->ncase.expr->narg.text);
4543 for (np = n->ncase.cases; np; np = np->nclist.next) {
4544 cmdtxt(np->nclist.pattern);
4546 cmdtxt(np->nclist.body);
4560 #if ENABLE_ASH_BASH_COMPAT
4575 cmdputs(utoa(n->nfile.fd));
4577 if (n->type == NTOFD || n->type == NFROMFD) {
4578 cmdputs(utoa(n->ndup.dupfd));
4587 commandtext(union node *n)
4591 STARTSTACKSTR(cmdnextc);
4593 name = stackblock();
4594 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4595 name, cmdnextc, cmdnextc));
4596 return ckstrdup(name);
4601 * Fork off a subshell. If we are doing job control, give the subshell its
4602 * own process group. Jp is a job structure that the job is to be added to.
4603 * N is the command that will be evaluated by the child. Both jp and n may
4604 * be NULL. The mode parameter can be one of the following:
4605 * FORK_FG - Fork off a foreground process.
4606 * FORK_BG - Fork off a background process.
4607 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4608 * process group even if job control is on.
4610 * When job control is turned off, background processes have their standard
4611 * input redirected to /dev/null (except for the second and later processes
4614 * Called with interrupts off.
4617 * Clear traps on a fork.
4624 for (tp = trap; tp < &trap[NSIG]; tp++) {
4625 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4627 if (trap_ptr == trap)
4629 /* else: it "belongs" to trap_ptr vector, don't free */
4631 if ((tp - trap) != 0)
4632 setsignal(tp - trap);
4639 /* Lives far away from here, needed for forkchild */
4640 static void closescript(void);
4642 /* Called after fork(), in child */
4643 static NOINLINE void
4644 forkchild(struct job *jp, union node *n, int mode)
4648 TRACE(("Child shell %d\n", getpid()));
4652 /* man bash: "Non-builtin commands run by bash have signal handlers
4653 * set to the values inherited by the shell from its parent".
4654 * Do we do it correctly? */
4658 if (mode == FORK_NOJOB /* is it `xxx` ? */
4659 && n && n->type == NCMD /* is it single cmd? */
4660 /* && n->ncmd.args->type == NARG - always true? */
4661 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4662 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4663 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4665 TRACE(("Trap hack\n"));
4666 /* Awful hack for `trap` or $(trap).
4668 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4669 * contains an example where "trap" is executed in a subshell:
4671 * save_traps=$(trap)
4673 * eval "$save_traps"
4675 * Standard does not say that "trap" in subshell shall print
4676 * parent shell's traps. It only says that its output
4677 * must have suitable form, but then, in the above example
4678 * (which is not supposed to be normative), it implies that.
4680 * bash (and probably other shell) does implement it
4681 * (traps are reset to defaults, but "trap" still shows them),
4682 * but as a result, "trap" logic is hopelessly messed up:
4685 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4686 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4687 * # true | trap <--- trap is in subshell - no output (ditto)
4688 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4689 * trap -- 'echo Ho' SIGWINCH
4690 * # echo `(trap)` <--- in subshell in subshell - output
4691 * trap -- 'echo Ho' SIGWINCH
4692 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4693 * trap -- 'echo Ho' SIGWINCH
4695 * The rules when to forget and when to not forget traps
4696 * get really complex and nonsensical.
4698 * Our solution: ONLY bare $(trap) or `trap` is special.
4700 /* Save trap handler strings for trap builtin to print */
4701 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
4702 /* Fall through into clearing traps */
4706 /* do job control only in root shell */
4708 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4711 if (jp->nprocs == 0)
4714 pgrp = jp->ps[0].ps_pid;
4715 /* this can fail because we are doing it in the parent also */
4717 if (mode == FORK_FG)
4718 xtcsetpgrp(ttyfd, pgrp);
4723 if (mode == FORK_BG) {
4724 /* man bash: "When job control is not in effect,
4725 * asynchronous commands ignore SIGINT and SIGQUIT" */
4728 if (jp->nprocs == 0) {
4730 if (open(bb_dev_null, O_RDONLY) != 0)
4731 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4735 if (iflag) { /* why if iflag only? */
4740 * "In all cases, bash ignores SIGQUIT. Non-builtin
4741 * commands run by bash have signal handlers
4742 * set to the values inherited by the shell
4744 * Take care of the second rule: */
4748 if (n && n->type == NCMD
4749 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4751 TRACE(("Job hack\n"));
4752 /* "jobs": we do not want to clear job list for it,
4753 * instead we remove only _its_ own_ job from job list.
4754 * This makes "jobs .... | cat" more useful.
4760 for (jp = curjob; jp; jp = jp->prev_job)
4765 /* Called after fork(), in parent */
4767 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4770 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4772 TRACE(("In parent shell: child = %d\n", pid));
4774 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4780 if (mode != FORK_NOJOB && jp->jobctl) {
4783 if (jp->nprocs == 0)
4786 pgrp = jp->ps[0].ps_pid;
4787 /* This can fail because we are doing it in the child also */
4791 if (mode == FORK_BG) {
4792 backgndpid = pid; /* set $! */
4793 set_curjob(jp, CUR_RUNNING);
4796 struct procstat *ps = &jp->ps[jp->nprocs++];
4799 ps->ps_cmd = nullstr;
4801 if (doing_jobctl && n)
4802 ps->ps_cmd = commandtext(n);
4808 forkshell(struct job *jp, union node *n, int mode)
4812 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4815 TRACE(("Fork failed, errno=%d", errno));
4818 ash_msg_and_raise_error("can't fork");
4821 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
4822 forkchild(jp, n, mode);
4824 forkparent(jp, n, mode, pid);
4830 * Wait for job to finish.
4832 * Under job control we have the problem that while a child process
4833 * is running interrupts generated by the user are sent to the child
4834 * but not to the shell. This means that an infinite loop started by
4835 * an interactive user may be hard to kill. With job control turned off,
4836 * an interactive user may place an interactive program inside a loop.
4837 * If the interactive program catches interrupts, the user doesn't want
4838 * these interrupts to also abort the loop. The approach we take here
4839 * is to have the shell ignore interrupt signals while waiting for a
4840 * foreground process to terminate, and then send itself an interrupt
4841 * signal if the child process was terminated by an interrupt signal.
4842 * Unfortunately, some programs want to do a bit of cleanup and then
4843 * exit on interrupt; unless these processes terminate themselves by
4844 * sending a signal to themselves (instead of calling exit) they will
4845 * confuse this approach.
4847 * Called with interrupts off.
4850 waitforjob(struct job *jp)
4854 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4857 while (jp->state == JOBRUNNING) {
4858 /* In non-interactive shells, we _can_ get
4859 * a keyboard signal here and be EINTRed,
4860 * but we just loop back, waiting for command to complete.
4863 * "If bash is waiting for a command to complete and receives
4864 * a signal for which a trap has been set, the trap
4865 * will not be executed until the command completes."
4867 * Reality is that even if trap is not set, bash
4868 * will not act on the signal until command completes.
4869 * Try this. sleep5intoff.c:
4870 * #include <signal.h>
4871 * #include <unistd.h>
4874 * sigemptyset(&set);
4875 * sigaddset(&set, SIGINT);
4876 * sigaddset(&set, SIGQUIT);
4877 * sigprocmask(SIG_BLOCK, &set, NULL);
4881 * $ bash -c './sleep5intoff; echo hi'
4882 * ^C^C^C^C <--- pressing ^C once a second
4884 * $ bash -c './sleep5intoff; echo hi'
4885 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4888 dowait(DOWAIT_BLOCK, jp);
4895 xtcsetpgrp(ttyfd, rootpid);
4897 * This is truly gross.
4898 * If we're doing job control, then we did a TIOCSPGRP which
4899 * caused us (the shell) to no longer be in the controlling
4900 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4901 * intuit from the subprocess exit status whether a SIGINT
4902 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4904 if (jp->sigint) /* TODO: do the same with all signals */
4905 raise(SIGINT); /* ... by raise(jp->sig) instead? */
4907 if (jp->state == JOBDONE)
4914 * return 1 if there are stopped jobs, otherwise 0
4926 if (jp && jp->state == JOBSTOPPED) {
4927 out2str("You have stopped jobs.\n");
4936 /* ============ redir.c
4938 * Code for dealing with input/output redirection.
4941 #define EMPTY -2 /* marks an unused slot in redirtab */
4942 #define CLOSED -3 /* marks a slot of previously-closed fd */
4945 * Open a file in noclobber mode.
4946 * The code was copied from bash.
4949 noclobberopen(const char *fname)
4952 struct stat finfo, finfo2;
4955 * If the file exists and is a regular file, return an error
4958 r = stat(fname, &finfo);
4959 if (r == 0 && S_ISREG(finfo.st_mode)) {
4965 * If the file was not present (r != 0), make sure we open it
4966 * exclusively so that if it is created before we open it, our open
4967 * will fail. Make sure that we do not truncate an existing file.
4968 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4969 * file was not a regular file, we leave O_EXCL off.
4972 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4973 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4975 /* If the open failed, return the file descriptor right away. */
4980 * OK, the open succeeded, but the file may have been changed from a
4981 * non-regular file to a regular file between the stat and the open.
4982 * We are assuming that the O_EXCL open handles the case where FILENAME
4983 * did not exist and is symlinked to an existing file between the stat
4988 * If we can open it and fstat the file descriptor, and neither check
4989 * revealed that it was a regular file, and the file has not been
4990 * replaced, return the file descriptor.
4992 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4993 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4996 /* The file has been replaced. badness. */
5003 * Handle here documents. Normally we fork off a process to write the
5004 * data to a pipe. If the document is short, we can stuff the data in
5005 * the pipe without forking.
5007 /* openhere needs this forward reference */
5008 static void expandhere(union node *arg, int fd);
5010 openhere(union node *redir)
5016 ash_msg_and_raise_error("pipe call failed");
5017 if (redir->type == NHERE) {
5018 len = strlen(redir->nhere.doc->narg.text);
5019 if (len <= PIPE_BUF) {
5020 full_write(pip[1], redir->nhere.doc->narg.text, len);
5024 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5027 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5028 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5029 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5030 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5031 signal(SIGPIPE, SIG_DFL);
5032 if (redir->type == NHERE)
5033 full_write(pip[1], redir->nhere.doc->narg.text, len);
5035 expandhere(redir->nhere.doc, pip[1]);
5036 _exit(EXIT_SUCCESS);
5044 openredirect(union node *redir)
5049 switch (redir->nfile.type) {
5051 fname = redir->nfile.expfname;
5052 f = open(fname, O_RDONLY);
5057 fname = redir->nfile.expfname;
5058 f = open(fname, O_RDWR|O_CREAT, 0666);
5063 #if ENABLE_ASH_BASH_COMPAT
5066 /* Take care of noclobber mode. */
5068 fname = redir->nfile.expfname;
5069 f = noclobberopen(fname);
5076 fname = redir->nfile.expfname;
5077 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5082 fname = redir->nfile.expfname;
5083 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5091 /* Fall through to eliminate warning. */
5092 /* Our single caller does this itself */
5099 f = openhere(redir);
5105 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5107 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5111 * Copy a file descriptor to be >= to. Returns -1
5112 * if the source file descriptor is closed, EMPTY if there are no unused
5113 * file descriptors left.
5115 /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5116 * old code was doing close(to) prior to copyfd() to achieve the same */
5118 COPYFD_EXACT = (int)~(INT_MAX),
5119 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5122 copyfd(int from, int to)
5126 if (to & COPYFD_EXACT) {
5127 to &= ~COPYFD_EXACT;
5129 newfd = dup2(from, to);
5131 newfd = fcntl(from, F_DUPFD, to);
5134 if (errno == EMFILE)
5136 /* Happens when source fd is not open: try "echo >&99" */
5137 ash_msg_and_raise_error("%d: %m", from);
5142 /* Struct def and variable are moved down to the first usage site */
5147 struct redirtab *next;
5150 struct two_fd_t two_fd[];
5152 #define redirlist (G_var.redirlist)
5154 static int need_to_remember(struct redirtab *rp, int fd)
5158 if (!rp) /* remembering was not requested */
5161 for (i = 0; i < rp->pair_count; i++) {
5162 if (rp->two_fd[i].orig == fd) {
5163 /* already remembered */
5170 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5171 static int is_hidden_fd(struct redirtab *rp, int fd)
5174 struct parsefile *pf;
5178 /* Check open scripts' fds */
5181 /* We skip pf_fd == 0 case because of the following case:
5182 * $ ash # running ash interactively
5184 * and in script.sh: "exec 9>&0".
5185 * Even though top-level pf_fd _is_ 0,
5186 * it's still ok to use it: "read" builtin uses it,
5187 * why should we cripple "exec" builtin?
5189 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5197 /* Check saved fds of redirects */
5198 fd |= COPYFD_RESTORE;
5199 for (i = 0; i < rp->pair_count; i++) {
5200 if (rp->two_fd[i].copy == fd) {
5208 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5209 * old file descriptors are stashed away so that the redirection can be
5210 * undone by calling popredir.
5212 /* flags passed to redirect */
5213 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5214 #define REDIR_SAVEFD2 03 /* set preverrout */
5216 redirect(union node *redir, int flags)
5218 struct redirtab *sv;
5223 int copied_fd2 = -1;
5233 if (flags & REDIR_PUSH) {
5234 union node *tmp = redir;
5237 #if ENABLE_ASH_BASH_COMPAT
5238 if (tmp->nfile.type == NTO2)
5241 tmp = tmp->nfile.next;
5243 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5244 sv->next = redirlist;
5245 sv->pair_count = sv_pos;
5247 sv->nullredirs = g_nullredirs - 1;
5249 while (sv_pos > 0) {
5251 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5257 fd = redir->nfile.fd;
5258 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5259 right_fd = redir->ndup.dupfd;
5260 //bb_error_msg("doing %d > %d", fd, right_fd);
5261 /* redirect from/to same file descriptor? */
5264 /* "echo >&10" and 10 is a fd opened to a sh script? */
5265 if (is_hidden_fd(sv, right_fd)) {
5266 errno = EBADF; /* as if it is closed */
5267 ash_msg_and_raise_error("%d: %m", right_fd);
5271 newfd = openredirect(redir); /* always >= 0 */
5273 /* Descriptor wasn't open before redirect.
5274 * Mark it for close in the future */
5275 if (need_to_remember(sv, fd)) {
5276 goto remember_to_close;
5281 #if ENABLE_ASH_BASH_COMPAT
5284 if (need_to_remember(sv, fd)) {
5285 /* Copy old descriptor */
5286 /* Careful to not accidentally "save"
5287 * to the same fd as right side fd in N>&M */
5288 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5289 i = fcntl(fd, F_DUPFD, minfd);
5290 /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5291 * are closed in popredir() in the child, preventing them from leaking
5292 * into child. (popredir() also cleans up the mess in case of failures)
5297 /* Strange error (e.g. "too many files" EMFILE?) */
5301 ash_msg_and_raise_error("%d: %m", fd);
5304 /* EBADF: it is not open - good, remember to close it */
5307 } else { /* fd is open, save its copy */
5308 /* "exec fd>&-" should not close fds
5309 * which point to script file(s).
5310 * Force them to be restored afterwards */
5311 if (is_hidden_fd(sv, fd))
5312 i |= COPYFD_RESTORE;
5316 sv->two_fd[sv_pos].orig = fd;
5317 sv->two_fd[sv_pos].copy = i;
5321 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5322 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5323 /* Don't want to trigger debugging */
5327 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
5329 } else if (fd != newfd) { /* move newfd to fd */
5330 copyfd(newfd, fd | COPYFD_EXACT);
5331 #if ENABLE_ASH_BASH_COMPAT
5332 if (!(redir->nfile.type == NTO2 && fd == 2))
5336 #if ENABLE_ASH_BASH_COMPAT
5337 if (redir->nfile.type == NTO2 && fd == 1) {
5338 /* We already redirected it to fd 1, now copy it to 2 */
5344 } while ((redir = redir->nfile.next) != NULL);
5347 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5348 preverrout_fd = copied_fd2;
5352 * Undo the effects of the last redirection.
5355 popredir(int drop, int restore)
5357 struct redirtab *rp;
5360 if (--g_nullredirs >= 0)
5364 for (i = 0; i < rp->pair_count; i++) {
5365 int fd = rp->two_fd[i].orig;
5366 int copy = rp->two_fd[i].copy;
5367 if (copy == CLOSED) {
5372 if (copy != EMPTY) {
5373 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5374 copy &= ~COPYFD_RESTORE;
5376 copyfd(copy, fd | COPYFD_EXACT);
5378 close(copy & ~COPYFD_RESTORE);
5381 redirlist = rp->next;
5382 g_nullredirs = rp->nullredirs;
5388 * Undo all redirections. Called on error or interrupt.
5392 * Discard all saved file descriptors.
5395 clearredir(int drop)
5401 popredir(drop, /*restore:*/ 0);
5406 redirectsafe(union node *redir, int flags)
5409 volatile int saveint;
5410 struct jmploc *volatile savehandler = exception_handler;
5411 struct jmploc jmploc;
5414 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5415 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5417 exception_handler = &jmploc;
5418 redirect(redir, flags);
5420 exception_handler = savehandler;
5421 if (err && exception_type != EXERROR)
5422 longjmp(exception_handler->loc, 1);
5423 RESTORE_INT(saveint);
5428 /* ============ Routines to expand arguments to commands
5430 * We have to deal with backquotes, shell variables, and file metacharacters.
5433 #if ENABLE_SH_MATH_SUPPORT
5435 ash_arith(const char *s)
5437 arith_eval_hooks_t math_hooks;
5441 math_hooks.lookupvar = lookupvar;
5442 math_hooks.setvar = setvar2;
5443 math_hooks.endofname = endofname;
5446 result = arith(s, &errcode, &math_hooks);
5449 ash_msg_and_raise_error("exponent less than 0");
5451 ash_msg_and_raise_error("divide by zero");
5453 ash_msg_and_raise_error("expression recursion loop detected");
5454 raise_error_syntax(s);
5465 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5466 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5467 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5468 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5469 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5470 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5471 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5472 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5473 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5477 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5478 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5479 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5480 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5481 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5484 * Structure specifying which parts of the string should be searched
5485 * for IFS characters.
5488 struct ifsregion *next; /* next region in list */
5489 int begoff; /* offset of start of region */
5490 int endoff; /* offset of end of region */
5491 int nulonly; /* search for nul bytes only */
5495 struct strlist *list;
5496 struct strlist **lastp;
5499 /* output of current string */
5500 static char *expdest;
5501 /* list of back quote expressions */
5502 static struct nodelist *argbackq;
5503 /* first struct in list of ifs regions */
5504 static struct ifsregion ifsfirst;
5505 /* last struct in list */
5506 static struct ifsregion *ifslastp;
5507 /* holds expanded arg list */
5508 static struct arglist exparg;
5518 expdest = makestrspace(32, expdest);
5519 len = fmtstr(expdest, 32, arith_t_fmt, num);
5520 STADJUST(len, expdest);
5525 esclen(const char *start, const char *p)
5529 while (p > start && (unsigned char)*--p == CTLESC) {
5536 * Remove any CTLESC characters from a string.
5539 rmescapes(char *str, int flag)
5541 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
5545 unsigned protect_against_glob;
5548 p = strpbrk(str, qchars);
5554 if (flag & RMESCAPE_ALLOC) {
5555 size_t len = p - str;
5556 size_t fulllen = len + strlen(p) + 1;
5558 if (flag & RMESCAPE_GROW) {
5559 int strloc = str - (char *)stackblock();
5560 r = makestrspace(fulllen, expdest);
5561 /* p and str may be invalidated by makestrspace */
5562 str = (char *)stackblock() + strloc;
5564 } else if (flag & RMESCAPE_HEAP) {
5565 r = ckmalloc(fulllen);
5567 r = stalloc(fulllen);
5571 q = (char *)memcpy(q, str, len) + len;
5575 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5576 globbing = flag & RMESCAPE_GLOB;
5577 protect_against_glob = globbing;
5579 if ((unsigned char)*p == CTLQUOTEMARK) {
5580 // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5581 // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5582 // Note: both inquotes and protect_against_glob only affect whether
5583 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5584 inquotes = ~inquotes;
5586 protect_against_glob = globbing;
5590 /* naked back slash */
5591 protect_against_glob = 0;
5594 if ((unsigned char)*p == CTLESC) {
5596 if (protect_against_glob && inquotes && *p != '/') {
5600 protect_against_glob = globbing;
5605 if (flag & RMESCAPE_GROW) {
5607 STADJUST(q - r + 1, expdest);
5611 #define pmatch(a, b) !fnmatch((a), (b), 0)
5614 * Prepare a pattern for a expmeta (internal glob(3)) call.
5616 * Returns an stalloced string.
5619 preglob(const char *pattern, int quoted, int flag)
5621 flag |= RMESCAPE_GLOB;
5623 flag |= RMESCAPE_QUOTED;
5625 return rmescapes((char *)pattern, flag);
5629 * Put a string on the stack.
5632 memtodest(const char *p, size_t len, int syntax, int quotes)
5636 q = makestrspace(quotes ? len * 2 : len, q);
5639 unsigned char c = *p++;
5643 int n = SIT(c, syntax);
5644 if (n == CCTL || n == CBACK)
5654 strtodest(const char *p, int syntax, int quotes)
5656 memtodest(p, strlen(p), syntax, quotes);
5660 * Record the fact that we have to scan this region of the
5661 * string for IFS characters.
5664 recordregion(int start, int end, int nulonly)
5666 struct ifsregion *ifsp;
5668 if (ifslastp == NULL) {
5672 ifsp = ckzalloc(sizeof(*ifsp));
5673 /*ifsp->next = NULL; - ckzalloc did it */
5674 ifslastp->next = ifsp;
5678 ifslastp->begoff = start;
5679 ifslastp->endoff = end;
5680 ifslastp->nulonly = nulonly;
5684 removerecordregions(int endoff)
5686 if (ifslastp == NULL)
5689 if (ifsfirst.endoff > endoff) {
5690 while (ifsfirst.next) {
5691 struct ifsregion *ifsp;
5693 ifsp = ifsfirst.next->next;
5694 free(ifsfirst.next);
5695 ifsfirst.next = ifsp;
5698 if (ifsfirst.begoff > endoff) {
5701 ifslastp = &ifsfirst;
5702 ifsfirst.endoff = endoff;
5707 ifslastp = &ifsfirst;
5708 while (ifslastp->next && ifslastp->next->begoff < endoff)
5709 ifslastp = ifslastp->next;
5710 while (ifslastp->next) {
5711 struct ifsregion *ifsp;
5713 ifsp = ifslastp->next->next;
5714 free(ifslastp->next);
5715 ifslastp->next = ifsp;
5718 if (ifslastp->endoff > endoff)
5719 ifslastp->endoff = endoff;
5723 exptilde(char *startp, char *p, int flags)
5729 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
5734 while ((c = *++p) != '\0') {
5741 if (flags & EXP_VARTILDE)
5751 if (*name == '\0') {
5752 home = lookupvar("HOME");
5754 pw = getpwnam(name);
5759 if (!home || !*home)
5762 startloc = expdest - (char *)stackblock();
5763 strtodest(home, SQSYNTAX, quotes);
5764 recordregion(startloc, expdest - (char *)stackblock(), 0);
5772 * Execute a command inside back quotes. If it's a builtin command, we
5773 * want to save its output in a block obtained from malloc. Otherwise
5774 * we fork off a subprocess and get the output of the command via a pipe.
5775 * Should be called with interrupts off.
5777 struct backcmd { /* result of evalbackcmd */
5778 int fd; /* file descriptor to read from */
5779 int nleft; /* number of chars in buffer */
5780 char *buf; /* buffer */
5781 struct job *jp; /* job structure for command */
5784 /* These forward decls are needed to use "eval" code for backticks handling: */
5785 static uint8_t back_exitstatus; /* exit status of backquoted command */
5786 #define EV_EXIT 01 /* exit after evaluating tree */
5787 static void evaltree(union node *, int);
5789 static void FAST_FUNC
5790 evalbackcmd(union node *n, struct backcmd *result)
5801 saveherefd = herefd;
5809 ash_msg_and_raise_error("pipe call failed");
5810 jp = makejob(/*n,*/ 1);
5811 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5816 copyfd(pip[1], 1 | COPYFD_EXACT);
5820 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5824 result->fd = pip[0];
5827 herefd = saveherefd;
5829 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5830 result->fd, result->buf, result->nleft, result->jp));
5834 * Expand stuff in backwards quotes.
5837 expbackq(union node *cmd, int quoted, int quotes)
5845 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
5846 struct stackmark smark;
5849 setstackmark(&smark);
5851 startloc = dest - (char *)stackblock();
5853 evalbackcmd(cmd, &in);
5854 popstackmark(&smark);
5861 memtodest(p, i, syntax, quotes);
5865 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
5866 TRACE(("expbackq: read returns %d\n", i));
5875 back_exitstatus = waitforjob(in.jp);
5879 /* Eat all trailing newlines */
5881 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5886 recordregion(startloc, dest - (char *)stackblock(), 0);
5887 TRACE(("evalbackq: size:%d:'%.*s'\n",
5888 (int)((dest - (char *)stackblock()) - startloc),
5889 (int)((dest - (char *)stackblock()) - startloc),
5890 stackblock() + startloc));
5893 #if ENABLE_SH_MATH_SUPPORT
5895 * Expand arithmetic expression. Backup to start of expression,
5896 * evaluate, place result in (backed up) result, adjust string position.
5909 * This routine is slightly over-complicated for
5910 * efficiency. Next we scan backwards looking for the
5911 * start of arithmetic.
5913 start = stackblock();
5920 while ((unsigned char)*p != CTLARI) {
5924 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5929 esc = esclen(start, p);
5939 removerecordregions(begoff);
5946 rmescapes(p + 2, 0);
5948 len = cvtnum(ash_arith(p + 2));
5951 recordregion(begoff, begoff + len, 0);
5955 /* argstr needs it */
5956 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
5959 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5960 * characters to allow for further processing. Otherwise treat
5961 * $@ like $* since no splitting will be performed.
5963 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5964 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5965 * for correct expansion of "B=$A" word.
5968 argstr(char *p, int flags, struct strlist *var_str_list)
5970 static const char spclchars[] ALIGN1 = {
5978 CTLBACKQ | CTLQUOTE,
5979 #if ENABLE_SH_MATH_SUPPORT
5984 const char *reject = spclchars;
5985 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5986 int breakall = flags & EXP_WORD;
5991 if (!(flags & EXP_VARTILDE)) {
5993 } else if (flags & EXP_VARTILDE2) {
5998 if (flags & EXP_TILDE) {
6001 flags &= ~EXP_TILDE;
6004 if (*q == CTLESC && (flags & EXP_QWORD))
6007 p = exptilde(p, q, flags);
6010 startloc = expdest - (char *)stackblock();
6014 length += strcspn(p + length, reject);
6018 #if ENABLE_SH_MATH_SUPPORT
6022 /* c == '=' || c == ':' || c == CTLENDARI */
6028 expdest = stack_nputstr(p, length, expdest);
6029 newloc = expdest - (char *)stackblock();
6030 if (breakall && !inquotes && newloc > startloc) {
6031 recordregion(startloc, newloc, 0);
6042 if (flags & EXP_VARTILDE2) {
6046 flags |= EXP_VARTILDE2;
6051 * sort of a hack - expand tildes in variable
6052 * assignments (after the first '=' and after ':'s).
6061 case CTLENDVAR: /* ??? */
6064 /* "$@" syntax adherence hack */
6066 && memcmp(p, dolatstr, 4) == 0
6067 && ( p[4] == CTLQUOTEMARK
6068 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
6071 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
6074 inquotes = !inquotes;
6087 p = evalvar(p, flags, var_str_list);
6091 case CTLBACKQ|CTLQUOTE:
6092 expbackq(argbackq->n, c, quotes);
6093 argbackq = argbackq->next;
6095 #if ENABLE_SH_MATH_SUPPORT
6108 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6109 char *pattern, int quotes, int zero)
6118 const char *s = loc2;
6125 match = pmatch(pattern, s);
6130 if (quotes && (unsigned char)*loc == CTLESC)
6139 scanright(char *startp, char *rmesc, char *rmescend,
6140 char *pattern, int quotes, int match_at_start)
6142 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6143 int try2optimize = match_at_start;
6149 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6150 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6151 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6153 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6154 * and on each iteration they go back two/one char until they reach the beginning.
6155 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6157 /* TODO: document in what other circumstances we are called. */
6159 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6162 const char *s = loc2;
6163 if (match_at_start) {
6167 match = pmatch(pattern, s);
6168 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6172 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6174 /* Maybe we can optimize this:
6175 * if pattern ends with unescaped *, we can avoid checking
6176 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6177 * it wont match truncated "raw_value_of_" strings too.
6179 unsigned plen = strlen(pattern);
6180 /* Does it end with "*"? */
6181 if (plen != 0 && pattern[--plen] == '*') {
6182 /* "xxxx*" is not escaped */
6183 /* "xxx\*" is escaped */
6184 /* "xx\\*" is not escaped */
6185 /* "x\\\*" is escaped */
6187 while (plen != 0 && pattern[--plen] == '\\')
6190 break; /* ends with unescaped "*" */
6198 esc = esclen(startp, loc);
6209 static void varunset(const char *, const char *, const char *, int) NORETURN;
6211 varunset(const char *end, const char *var, const char *umsg, int varflags)
6217 msg = "parameter not set";
6219 if ((unsigned char)*end == CTLENDVAR) {
6220 if (varflags & VSNUL)
6226 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6229 #if ENABLE_ASH_BASH_COMPAT
6231 parse_sub_pattern(char *arg, int varflags)
6233 char *idx, *repl = NULL;
6236 //char *org_arg = arg;
6237 //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
6244 /* Only the first '/' seen is our separator */
6253 * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
6254 * The result is a_\_z_c (not a\_\_z_c)!
6256 * Enable debug prints in this function and you'll see:
6257 * ash: arg:'\\b/_\\_z_' varflags:d
6258 * ash: pattern:'\\b' repl:'_\_z_'
6259 * That is, \\b is interpreted as \\b, but \\_ as \_!
6260 * IOW: search pattern and replace string treat backslashes
6261 * differently! That is the reason why we check repl below:
6263 if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
6264 arg++; /* skip both '\', not just first one */
6267 //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
6271 #endif /* ENABLE_ASH_BASH_COMPAT */
6274 subevalvar(char *p, char *varname, int strloc, int subtype,
6275 int startloc, int varflags, int quotes, struct strlist *var_str_list)
6277 struct nodelist *saveargbackq = argbackq;
6280 char *rmesc, *rmescend;
6282 IF_ASH_BASH_COMPAT(const char *repl = NULL;)
6283 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
6284 int saveherefd = herefd;
6285 int amount, workloc, resetloc;
6287 char *(*scan)(char*, char*, char*, char*, int, int);
6289 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d",
6290 // p, varname, strloc, subtype, startloc, varflags, quotes);
6293 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6295 STPUTC('\0', expdest);
6296 herefd = saveherefd;
6297 argbackq = saveargbackq;
6298 startp = (char *)stackblock() + startloc;
6302 setvar(varname, startp, 0);
6303 amount = startp - expdest;
6304 STADJUST(amount, expdest);
6308 varunset(p, varname, startp, varflags);
6311 #if ENABLE_ASH_BASH_COMPAT
6313 loc = str = stackblock() + strloc;
6314 /* Read POS in ${var:POS:LEN} */
6315 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6316 len = str - startp - 1;
6318 /* *loc != '\0', guaranteed by parser */
6322 /* Adjust the length by the number of escapes */
6323 for (ptr = startp; ptr < (str - 1); ptr++) {
6324 if ((unsigned char)*ptr == CTLESC) {
6332 if (*loc++ == ':') {
6336 /* Skip POS in ${var:POS:LEN} */
6338 while (*loc && *loc != ':') {
6340 * bash complains on: var=qwe; echo ${var:1a:123}
6342 ash_msg_and_raise_error(msg_illnum, str);
6346 if (*loc++ == ':') {
6350 if (pos >= orig_len) {
6354 if (len > (orig_len - pos))
6355 len = orig_len - pos;
6357 for (str = startp; pos; str++, pos--) {
6358 if (quotes && (unsigned char)*str == CTLESC)
6361 for (loc = startp; len; len--) {
6362 if (quotes && (unsigned char)*str == CTLESC)
6367 amount = loc - expdest;
6368 STADJUST(amount, expdest);
6373 resetloc = expdest - (char *)stackblock();
6375 /* We'll comeback here if we grow the stack while handling
6376 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6377 * stack will need rebasing, and we'll need to remove our work
6380 IF_ASH_BASH_COMPAT(restart:)
6382 amount = expdest - ((char *)stackblock() + resetloc);
6383 STADJUST(-amount, expdest);
6384 startp = (char *)stackblock() + startloc;
6387 rmescend = (char *)stackblock() + strloc;
6389 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6390 if (rmesc != startp) {
6392 startp = (char *)stackblock() + startloc;
6396 str = (char *)stackblock() + strloc;
6397 preglob(str, varflags & VSQUOTE, 0);
6398 workloc = expdest - (char *)stackblock();
6400 #if ENABLE_ASH_BASH_COMPAT
6401 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6405 repl = parse_sub_pattern(str, varflags);
6406 //bb_error_msg("repl:'%s'", repl);
6411 /* If there's no pattern to match, return the expansion unmolested */
6420 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6421 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6423 /* No match, advance */
6424 char *restart_detect = stackblock();
6426 STPUTC(*idx, expdest);
6427 if (quotes && (unsigned char)*idx == CTLESC) {
6430 STPUTC(*idx, expdest);
6432 if (stackblock() != restart_detect)
6437 /* continue; - prone to quadratic behavior, smarter code: */
6440 if (str[0] == '*') {
6441 /* Pattern is "*foo". If "*foo" does not match "long_string",
6442 * it would never match "ong_string" etc, no point in trying.
6449 if (subtype == VSREPLACEALL) {
6451 if (quotes && (unsigned char)*idx == CTLESC)
6460 //bb_error_msg("repl:'%s'", repl);
6461 for (loc = (char*)repl; *loc; loc++) {
6462 char *restart_detect = stackblock();
6463 if (quotes && *loc == '\\') {
6464 STPUTC(CTLESC, expdest);
6467 STPUTC(*loc, expdest);
6468 if (stackblock() != restart_detect)
6473 if (subtype == VSREPLACE) {
6474 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6476 char *restart_detect = stackblock();
6477 STPUTC(*idx, expdest);
6478 if (stackblock() != restart_detect)
6487 /* We've put the replaced text into a buffer at workloc, now
6488 * move it to the right place and adjust the stack.
6490 STPUTC('\0', expdest);
6491 startp = (char *)stackblock() + startloc;
6492 memmove(startp, (char *)stackblock() + workloc, len + 1);
6493 //bb_error_msg("startp:'%s'", startp);
6494 amount = expdest - (startp + len);
6495 STADJUST(-amount, expdest);
6498 #endif /* ENABLE_ASH_BASH_COMPAT */
6500 subtype -= VSTRIMRIGHT;
6502 if (subtype < 0 || subtype > 7)
6505 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6506 zero = subtype >> 1;
6507 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6508 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6510 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6513 memmove(startp, loc, str - loc);
6514 loc = startp + (str - loc) - 1;
6517 amount = loc - expdest;
6518 STADJUST(amount, expdest);
6524 * Add the value of a specialized variable to the stack string.
6525 * name parameter (examples):
6526 * ash -c 'echo $1' name:'1='
6527 * ash -c 'echo $qwe' name:'qwe='
6528 * ash -c 'echo $$' name:'$='
6529 * ash -c 'echo ${$}' name:'$='
6530 * ash -c 'echo ${$##q}' name:'$=q'
6531 * ash -c 'echo ${#$}' name:'$='
6532 * note: examples with bad shell syntax:
6533 * ash -c 'echo ${#$1}' name:'$=1'
6534 * ash -c 'echo ${#1#}' name:'1=#'
6536 static NOINLINE ssize_t
6537 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
6544 int subtype = varflags & VSTYPE;
6545 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
6546 int quoted = varflags & VSQUOTE;
6547 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
6557 num = shellparam.nparam;
6565 goto check_1char_name;
6567 expdest = makestrspace(NOPTS, expdest);
6568 for (i = NOPTS - 1; i >= 0; i--) {
6570 USTPUTC(optletters(i), expdest);
6576 /* handles cases similar to ${#$1} */
6577 if (name[2] != '\0')
6578 raise_error_syntax("bad substitution");
6585 if (quoted && (flags & EXP_FULL)) {
6586 /* note: this is not meant as PEOF value */
6587 sep = 1 << CHAR_BIT;
6592 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
6593 i = SIT(sep, syntax);
6594 if (quotes && (i == CCTL || i == CBACK))
6600 while ((p = *ap++) != NULL) {
6603 partlen = strlen(p);
6606 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6607 memtodest(p, partlen, syntax, quotes);
6613 if (subtype == VSPLUS || subtype == VSLENGTH) {
6619 /* note: may put NUL despite sep != 0
6620 * (see sep = 1 << CHAR_BIT above) */
6626 } /* case '@' and '*' */
6637 num = atoi(name); /* number(name) fails on ${N#str} etc */
6638 if (num < 0 || num > shellparam.nparam)
6640 p = num ? shellparam.p[num - 1] : arg0;
6643 /* NB: name has form "VAR=..." */
6645 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6646 * which should be considered before we check variables. */
6648 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6652 str = var_str_list->text;
6653 eq = strchr(str, '=');
6654 if (!eq) /* stop at first non-assignment */
6657 if (name_len == (unsigned)(eq - str)
6658 && strncmp(str, name, name_len) == 0
6661 /* goto value; - WRONG! */
6662 /* think "A=1 A=2 B=$A" */
6664 var_str_list = var_str_list->next;
6665 } while (var_str_list);
6669 p = lookupvar(name);
6675 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6676 memtodest(p, len, syntax, quotes);
6680 if (subtype == VSPLUS || subtype == VSLENGTH)
6681 STADJUST(-len, expdest);
6686 * Expand a variable, and return a pointer to the next character in the
6690 evalvar(char *p, int flags, struct strlist *var_str_list)
6701 varflags = (unsigned char) *p++;
6702 subtype = varflags & VSTYPE;
6703 quoted = varflags & VSQUOTE;
6705 easy = (!quoted || (*var == '@' && shellparam.nparam));
6706 startloc = expdest - (char *)stackblock();
6707 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
6710 varlen = varvalue(var, varflags, flags, var_str_list);
6711 if (varflags & VSNUL)
6714 if (subtype == VSPLUS) {
6715 varlen = -1 - varlen;
6719 if (subtype == VSMINUS) {
6723 p, flags | EXP_TILDE |
6724 (quoted ? EXP_QWORD : EXP_WORD),
6734 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6736 if (subevalvar(p, var, /* strloc: */ 0,
6737 subtype, startloc, varflags,
6743 * Remove any recorded regions beyond
6746 removerecordregions(startloc);
6756 if (varlen < 0 && uflag)
6757 varunset(p, var, 0, 0);
6759 if (subtype == VSLENGTH) {
6760 cvtnum(varlen > 0 ? varlen : 0);
6764 if (subtype == VSNORMAL) {
6775 case VSTRIMRIGHTMAX:
6776 #if ENABLE_ASH_BASH_COMPAT
6789 * Terminate the string and start recording the pattern
6792 STPUTC('\0', expdest);
6793 patloc = expdest - (char *)stackblock();
6794 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
6796 //TODO: | EXP_REDIR too? All other such places do it too
6797 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
6800 int amount = expdest - (
6801 (char *)stackblock() + patloc - 1
6803 STADJUST(-amount, expdest);
6805 /* Remove any recorded regions beyond start of variable */
6806 removerecordregions(startloc);
6808 recordregion(startloc, expdest - (char *)stackblock(), quoted);
6812 if (subtype != VSNORMAL) { /* skip to end of alternative */
6815 unsigned char c = *p++;
6818 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6820 argbackq = argbackq->next;
6821 } else if (c == CTLVAR) {
6822 if ((*p++ & VSTYPE) != VSNORMAL)
6824 } else if (c == CTLENDVAR) {
6834 * Break the argument string into pieces based upon IFS and add the
6835 * strings to the argument list. The regions of the string to be
6836 * searched for IFS characters have been stored by recordregion.
6839 ifsbreakup(char *string, struct arglist *arglist)
6841 struct ifsregion *ifsp;
6846 const char *ifs, *realifs;
6851 if (ifslastp != NULL) {
6854 realifs = ifsset() ? ifsval() : defifs;
6857 p = string + ifsp->begoff;
6858 nulonly = ifsp->nulonly;
6859 ifs = nulonly ? nullstr : realifs;
6861 while (p < string + ifsp->endoff) {
6863 if ((unsigned char)*p == CTLESC)
6865 if (!strchr(ifs, *p)) {
6870 ifsspc = (strchr(defifs, *p) != NULL);
6871 /* Ignore IFS whitespace at start */
6872 if (q == start && ifsspc) {
6878 sp = stzalloc(sizeof(*sp));
6880 *arglist->lastp = sp;
6881 arglist->lastp = &sp->next;
6885 if (p >= string + ifsp->endoff) {
6889 if ((unsigned char)*p == CTLESC)
6891 if (strchr(ifs, *p) == NULL) {
6895 if (strchr(defifs, *p) == NULL) {
6910 } while (ifsp != NULL);
6919 sp = stzalloc(sizeof(*sp));
6921 *arglist->lastp = sp;
6922 arglist->lastp = &sp->next;
6928 struct ifsregion *p;
6933 struct ifsregion *ifsp;
6939 ifsfirst.next = NULL;
6944 * Add a file name to the list.
6947 addfname(const char *name)
6951 sp = stzalloc(sizeof(*sp));
6952 sp->text = ststrdup(name);
6954 exparg.lastp = &sp->next;
6958 * Do metacharacter (i.e. *, ?, [...]) expansion.
6961 expmeta(char *expdir, char *enddir, char *name)
6976 for (p = name; *p; p++) {
6977 if (*p == '*' || *p == '?')
6979 else if (*p == '[') {
6986 if (*q == '/' || *q == '\0')
6993 } else if (*p == '\\')
6995 else if (*p == '/') {
7002 if (metaflag == 0) { /* we've reached the end of the file name */
7003 if (enddir != expdir)
7011 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7022 } while (p < start);
7024 if (enddir == expdir) {
7026 } else if (enddir == expdir + 1 && *expdir == '/') {
7035 if (enddir != expdir)
7037 if (*endname == 0) {
7049 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7050 if (dp->d_name[0] == '.' && !matchdot)
7052 if (pmatch(start, dp->d_name)) {
7054 strcpy(enddir, dp->d_name);
7057 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7060 expmeta(expdir, p, endname);
7069 static struct strlist *
7070 msort(struct strlist *list, int len)
7072 struct strlist *p, *q = NULL;
7073 struct strlist **lpp;
7081 for (n = half; --n >= 0;) {
7085 q->next = NULL; /* terminate first half of list */
7086 q = msort(list, half); /* sort first half of list */
7087 p = msort(p, len - half); /* sort second half */
7090 #if ENABLE_LOCALE_SUPPORT
7091 if (strcoll(p->text, q->text) < 0)
7093 if (strcmp(p->text, q->text) < 0)
7117 * Sort the results of file name expansion. It calculates the number of
7118 * strings to sort and then calls msort (short for merge sort) to do the
7121 static struct strlist *
7122 expsort(struct strlist *str)
7128 for (sp = str; sp; sp = sp->next)
7130 return msort(str, len);
7134 expandmeta(struct strlist *str /*, int flag*/)
7136 static const char metachars[] ALIGN1 = {
7139 /* TODO - EXP_REDIR */
7143 struct strlist **savelastp;
7149 if (!strpbrk(str->text, metachars))
7151 savelastp = exparg.lastp;
7154 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7156 int i = strlen(str->text);
7157 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7159 expmeta(expdir, expdir, p);
7164 if (exparg.lastp == savelastp) {
7169 *exparg.lastp = str;
7170 rmescapes(str->text, 0);
7171 exparg.lastp = &str->next;
7173 *exparg.lastp = NULL;
7174 *savelastp = sp = expsort(*savelastp);
7175 while (sp->next != NULL)
7177 exparg.lastp = &sp->next;
7184 * Perform variable substitution and command substitution on an argument,
7185 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7186 * perform splitting and file name expansion. When arglist is NULL, perform
7187 * here document expansion.
7190 expandarg(union node *arg, struct arglist *arglist, int flag)
7195 argbackq = arg->narg.backquote;
7196 STARTSTACKSTR(expdest);
7197 ifsfirst.next = NULL;
7199 argstr(arg->narg.text, flag,
7200 /* var_str_list: */ arglist ? arglist->list : NULL);
7201 p = _STPUTC('\0', expdest);
7203 if (arglist == NULL) {
7204 return; /* here document expanded */
7206 p = grabstackstr(p);
7207 exparg.lastp = &exparg.list;
7211 if (flag & EXP_FULL) {
7212 ifsbreakup(p, &exparg);
7213 *exparg.lastp = NULL;
7214 exparg.lastp = &exparg.list;
7215 expandmeta(exparg.list /*, flag*/);
7217 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
7219 sp = stzalloc(sizeof(*sp));
7222 exparg.lastp = &sp->next;
7226 *exparg.lastp = NULL;
7228 *arglist->lastp = exparg.list;
7229 arglist->lastp = exparg.lastp;
7234 * Expand shell variables and backquotes inside a here document.
7237 expandhere(union node *arg, int fd)
7240 expandarg(arg, (struct arglist *)NULL, 0);
7241 full_write(fd, stackblock(), expdest - (char *)stackblock());
7245 * Returns true if the pattern matches the string.
7248 patmatch(char *pattern, const char *string)
7250 return pmatch(preglob(pattern, 0, 0), string);
7254 * See if a pattern matches in a case statement.
7257 casematch(union node *pattern, char *val)
7259 struct stackmark smark;
7262 setstackmark(&smark);
7263 argbackq = pattern->narg.backquote;
7264 STARTSTACKSTR(expdest);
7266 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7267 /* var_str_list: */ NULL);
7268 STACKSTRNUL(expdest);
7269 result = patmatch(stackblock(), val);
7270 popstackmark(&smark);
7275 /* ============ find_command */
7279 int (*builtin)(int, char **) FAST_FUNC;
7280 /* unsigned flags; */
7282 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7283 /* "regular" builtins always take precedence over commands,
7284 * regardless of PATH=....%builtin... position */
7285 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7286 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7289 smallint cmdtype; /* CMDxxx */
7292 /* index >= 0 for commands without path (slashes) */
7293 /* (TODO: what exactly does the value mean? PATH position?) */
7294 /* index == -1 for commands with slashes */
7295 /* index == (-2 - applet_no) for NOFORK applets */
7296 const struct builtincmd *cmd;
7297 struct funcnode *func;
7300 /* values of cmdtype */
7301 #define CMDUNKNOWN -1 /* no entry in table for command */
7302 #define CMDNORMAL 0 /* command is an executable program */
7303 #define CMDFUNCTION 1 /* command is a shell function */
7304 #define CMDBUILTIN 2 /* command is a shell builtin */
7306 /* action to find_command() */
7307 #define DO_ERR 0x01 /* prints errors */
7308 #define DO_ABS 0x02 /* checks absolute paths */
7309 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7310 #define DO_ALTPATH 0x08 /* using alternate path */
7311 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7313 static void find_command(char *, struct cmdentry *, int, const char *);
7316 /* ============ Hashing commands */
7319 * When commands are first encountered, they are entered in a hash table.
7320 * This ensures that a full path search will not have to be done for them
7321 * on each invocation.
7323 * We should investigate converting to a linear search, even though that
7324 * would make the command name "hash" a misnomer.
7328 struct tblentry *next; /* next entry in hash chain */
7329 union param param; /* definition of builtin function */
7330 smallint cmdtype; /* CMDxxx */
7331 char rehash; /* if set, cd done since entry created */
7332 char cmdname[1]; /* name of command */
7335 static struct tblentry **cmdtable;
7336 #define INIT_G_cmdtable() do { \
7337 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7340 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7344 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7348 #if ENABLE_FEATURE_SH_STANDALONE
7349 if (applet_no >= 0) {
7350 if (APPLET_IS_NOEXEC(applet_no)) {
7354 run_applet_no_and_exit(applet_no, argv);
7356 /* re-exec ourselves with the new arguments */
7357 execve(bb_busybox_exec_path, argv, envp);
7358 /* If they called chroot or otherwise made the binary no longer
7359 * executable, fall through */
7366 execve(cmd, argv, envp);
7367 } while (errno == EINTR);
7369 execve(cmd, argv, envp);
7375 if (errno == ENOEXEC) {
7379 for (ap = argv; *ap; ap++)
7381 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
7383 ap[0] = cmd = (char *)DEFAULT_SHELL;
7386 while ((*ap++ = *argv++) != NULL)
7395 * Exec a program. Never returns. If you change this routine, you may
7396 * have to change the find_command routine as well.
7398 static void shellexec(char **, const char *, int) NORETURN;
7400 shellexec(char **argv, const char *path, int idx)
7406 #if ENABLE_FEATURE_SH_STANDALONE
7410 clearredir(/*drop:*/ 1);
7411 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7412 if (strchr(argv[0], '/') != NULL
7413 #if ENABLE_FEATURE_SH_STANDALONE
7414 || (applet_no = find_applet_by_name(argv[0])) >= 0
7417 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
7421 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
7422 if (--idx < 0 && pathopt == NULL) {
7423 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7424 if (errno != ENOENT && errno != ENOTDIR)
7431 /* Map to POSIX errors */
7443 exitstatus = exerrno;
7444 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7445 argv[0], e, suppress_int));
7446 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7451 printentry(struct tblentry *cmdp)
7457 idx = cmdp->param.index;
7460 name = path_advance(&path, cmdp->cmdname);
7462 } while (--idx >= 0);
7463 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7467 * Clear out command entries. The argument specifies the first entry in
7468 * PATH which has changed.
7471 clearcmdentry(int firstchange)
7473 struct tblentry **tblp;
7474 struct tblentry **pp;
7475 struct tblentry *cmdp;
7478 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7480 while ((cmdp = *pp) != NULL) {
7481 if ((cmdp->cmdtype == CMDNORMAL &&
7482 cmdp->param.index >= firstchange)
7483 || (cmdp->cmdtype == CMDBUILTIN &&
7484 builtinloc >= firstchange)
7497 * Locate a command in the command hash table. If "add" is nonzero,
7498 * add the command to the table if it is not already present. The
7499 * variable "lastcmdentry" is set to point to the address of the link
7500 * pointing to the entry, so that delete_cmd_entry can delete the
7503 * Interrupts must be off if called with add != 0.
7505 static struct tblentry **lastcmdentry;
7507 static struct tblentry *
7508 cmdlookup(const char *name, int add)
7510 unsigned int hashval;
7512 struct tblentry *cmdp;
7513 struct tblentry **pp;
7516 hashval = (unsigned char)*p << 4;
7518 hashval += (unsigned char)*p++;
7520 pp = &cmdtable[hashval % CMDTABLESIZE];
7521 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7522 if (strcmp(cmdp->cmdname, name) == 0)
7526 if (add && cmdp == NULL) {
7527 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7529 /* + 1 - already done because
7530 * tblentry::cmdname is char[1] */);
7531 /*cmdp->next = NULL; - ckzalloc did it */
7532 cmdp->cmdtype = CMDUNKNOWN;
7533 strcpy(cmdp->cmdname, name);
7540 * Delete the command entry returned on the last lookup.
7543 delete_cmd_entry(void)
7545 struct tblentry *cmdp;
7548 cmdp = *lastcmdentry;
7549 *lastcmdentry = cmdp->next;
7550 if (cmdp->cmdtype == CMDFUNCTION)
7551 freefunc(cmdp->param.func);
7557 * Add a new command entry, replacing any existing command entry for
7558 * the same name - except special builtins.
7561 addcmdentry(char *name, struct cmdentry *entry)
7563 struct tblentry *cmdp;
7565 cmdp = cmdlookup(name, 1);
7566 if (cmdp->cmdtype == CMDFUNCTION) {
7567 freefunc(cmdp->param.func);
7569 cmdp->cmdtype = entry->cmdtype;
7570 cmdp->param = entry->u;
7574 static int FAST_FUNC
7575 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7577 struct tblentry **pp;
7578 struct tblentry *cmdp;
7580 struct cmdentry entry;
7583 if (nextopt("r") != '\0') {
7588 if (*argptr == NULL) {
7589 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7590 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7591 if (cmdp->cmdtype == CMDNORMAL)
7599 while ((name = *argptr) != NULL) {
7600 cmdp = cmdlookup(name, 0);
7602 && (cmdp->cmdtype == CMDNORMAL
7603 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7607 find_command(name, &entry, DO_ERR, pathval());
7608 if (entry.cmdtype == CMDUNKNOWN)
7616 * Called when a cd is done. Marks all commands so the next time they
7617 * are executed they will be rehashed.
7622 struct tblentry **pp;
7623 struct tblentry *cmdp;
7625 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7626 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7627 if (cmdp->cmdtype == CMDNORMAL
7628 || (cmdp->cmdtype == CMDBUILTIN
7629 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7639 * Fix command hash table when PATH changed.
7640 * Called before PATH is changed. The argument is the new value of PATH;
7641 * pathval() still returns the old value at this point.
7642 * Called with interrupts off.
7644 static void FAST_FUNC
7645 changepath(const char *new)
7653 firstchange = 9999; /* assume no change */
7659 if ((*old == '\0' && *new == ':')
7660 || (*old == ':' && *new == '\0')
7664 old = new; /* ignore subsequent differences */
7668 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7675 if (builtinloc < 0 && idx_bltin >= 0)
7676 builtinloc = idx_bltin; /* zap builtins */
7677 if (builtinloc >= 0 && idx_bltin < 0)
7679 clearcmdentry(firstchange);
7680 builtinloc = idx_bltin;
7695 #define TENDBQUOTE 12
7712 typedef smallint token_id_t;
7714 /* first char is indicating which tokens mark the end of a list */
7715 static const char *const tokname_array[] = {
7729 #define KWDOFFSET 13
7730 /* the following are keywords */
7749 /* Wrapper around strcmp for qsort/bsearch/... */
7751 pstrcmp(const void *a, const void *b)
7753 return strcmp((char*) a, (*(char**) b) + 1);
7756 static const char *const *
7757 findkwd(const char *s)
7759 return bsearch(s, tokname_array + KWDOFFSET,
7760 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7761 sizeof(tokname_array[0]), pstrcmp);
7765 * Locate and print what a word is...
7768 describe_command(char *command, int describe_command_verbose)
7770 struct cmdentry entry;
7771 struct tblentry *cmdp;
7772 #if ENABLE_ASH_ALIAS
7773 const struct alias *ap;
7775 const char *path = pathval();
7777 if (describe_command_verbose) {
7781 /* First look at the keywords */
7782 if (findkwd(command)) {
7783 out1str(describe_command_verbose ? " is a shell keyword" : command);
7787 #if ENABLE_ASH_ALIAS
7788 /* Then look at the aliases */
7789 ap = lookupalias(command, 0);
7791 if (!describe_command_verbose) {
7796 out1fmt(" is an alias for %s", ap->val);
7800 /* Then check if it is a tracked alias */
7801 cmdp = cmdlookup(command, 0);
7803 entry.cmdtype = cmdp->cmdtype;
7804 entry.u = cmdp->param;
7806 /* Finally use brute force */
7807 find_command(command, &entry, DO_ABS, path);
7810 switch (entry.cmdtype) {
7812 int j = entry.u.index;
7818 p = path_advance(&path, command);
7822 if (describe_command_verbose) {
7824 (cmdp ? " a tracked alias for" : nullstr), p
7833 if (describe_command_verbose) {
7834 out1str(" is a shell function");
7841 if (describe_command_verbose) {
7842 out1fmt(" is a %sshell builtin",
7843 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7844 "special " : nullstr
7852 if (describe_command_verbose) {
7853 out1str(": not found\n");
7862 static int FAST_FUNC
7863 typecmd(int argc UNUSED_PARAM, char **argv)
7869 /* type -p ... ? (we don't bother checking for 'p') */
7870 if (argv[1] && argv[1][0] == '-') {
7875 err |= describe_command(argv[i++], verbose);
7880 #if ENABLE_ASH_CMDCMD
7881 static int FAST_FUNC
7882 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7890 while ((c = nextopt("pvV")) != '\0')
7892 verify |= VERIFY_VERBOSE;
7894 verify |= VERIFY_BRIEF;
7899 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7900 if (verify && (*argptr != NULL)) {
7901 return describe_command(*argptr, verify - VERIFY_BRIEF);
7909 /* ============ eval.c */
7911 static int funcblocksize; /* size of structures in function */
7912 static int funcstringsize; /* size of strings in node */
7913 static void *funcblock; /* block to allocate function from */
7914 static char *funcstring; /* block to allocate strings from */
7916 /* flags in argument to evaltree */
7917 #define EV_EXIT 01 /* exit after evaluating tree */
7918 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7919 #define EV_BACKCMD 04 /* command executing within back quotes */
7921 static const uint8_t nodesize[N_NUMBER] = {
7922 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7923 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7924 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7925 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7926 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7927 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7928 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7929 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7930 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7931 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7932 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7933 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7934 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7935 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7936 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7937 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7938 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7939 #if ENABLE_ASH_BASH_COMPAT
7940 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
7942 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7943 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7944 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7945 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7946 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7947 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7948 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7949 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7950 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
7953 static void calcsize(union node *n);
7956 sizenodelist(struct nodelist *lp)
7959 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7966 calcsize(union node *n)
7970 funcblocksize += nodesize[n->type];
7973 calcsize(n->ncmd.redirect);
7974 calcsize(n->ncmd.args);
7975 calcsize(n->ncmd.assign);
7978 sizenodelist(n->npipe.cmdlist);
7983 calcsize(n->nredir.redirect);
7984 calcsize(n->nredir.n);
7991 calcsize(n->nbinary.ch2);
7992 calcsize(n->nbinary.ch1);
7995 calcsize(n->nif.elsepart);
7996 calcsize(n->nif.ifpart);
7997 calcsize(n->nif.test);
8000 funcstringsize += strlen(n->nfor.var) + 1;
8001 calcsize(n->nfor.body);
8002 calcsize(n->nfor.args);
8005 calcsize(n->ncase.cases);
8006 calcsize(n->ncase.expr);
8009 calcsize(n->nclist.body);
8010 calcsize(n->nclist.pattern);
8011 calcsize(n->nclist.next);
8015 sizenodelist(n->narg.backquote);
8016 funcstringsize += strlen(n->narg.text) + 1;
8017 calcsize(n->narg.next);
8020 #if ENABLE_ASH_BASH_COMPAT
8027 calcsize(n->nfile.fname);
8028 calcsize(n->nfile.next);
8032 calcsize(n->ndup.vname);
8033 calcsize(n->ndup.next);
8037 calcsize(n->nhere.doc);
8038 calcsize(n->nhere.next);
8041 calcsize(n->nnot.com);
8047 nodeckstrdup(char *s)
8049 char *rtn = funcstring;
8051 strcpy(funcstring, s);
8052 funcstring += strlen(s) + 1;
8056 static union node *copynode(union node *);
8058 static struct nodelist *
8059 copynodelist(struct nodelist *lp)
8061 struct nodelist *start;
8062 struct nodelist **lpp;
8067 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8068 (*lpp)->n = copynode(lp->n);
8070 lpp = &(*lpp)->next;
8077 copynode(union node *n)
8084 funcblock = (char *) funcblock + nodesize[n->type];
8088 new->ncmd.redirect = copynode(n->ncmd.redirect);
8089 new->ncmd.args = copynode(n->ncmd.args);
8090 new->ncmd.assign = copynode(n->ncmd.assign);
8093 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8094 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8099 new->nredir.redirect = copynode(n->nredir.redirect);
8100 new->nredir.n = copynode(n->nredir.n);
8107 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8108 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8111 new->nif.elsepart = copynode(n->nif.elsepart);
8112 new->nif.ifpart = copynode(n->nif.ifpart);
8113 new->nif.test = copynode(n->nif.test);
8116 new->nfor.var = nodeckstrdup(n->nfor.var);
8117 new->nfor.body = copynode(n->nfor.body);
8118 new->nfor.args = copynode(n->nfor.args);
8121 new->ncase.cases = copynode(n->ncase.cases);
8122 new->ncase.expr = copynode(n->ncase.expr);
8125 new->nclist.body = copynode(n->nclist.body);
8126 new->nclist.pattern = copynode(n->nclist.pattern);
8127 new->nclist.next = copynode(n->nclist.next);
8131 new->narg.backquote = copynodelist(n->narg.backquote);
8132 new->narg.text = nodeckstrdup(n->narg.text);
8133 new->narg.next = copynode(n->narg.next);
8136 #if ENABLE_ASH_BASH_COMPAT
8143 new->nfile.fname = copynode(n->nfile.fname);
8144 new->nfile.fd = n->nfile.fd;
8145 new->nfile.next = copynode(n->nfile.next);
8149 new->ndup.vname = copynode(n->ndup.vname);
8150 new->ndup.dupfd = n->ndup.dupfd;
8151 new->ndup.fd = n->ndup.fd;
8152 new->ndup.next = copynode(n->ndup.next);
8156 new->nhere.doc = copynode(n->nhere.doc);
8157 new->nhere.fd = n->nhere.fd;
8158 new->nhere.next = copynode(n->nhere.next);
8161 new->nnot.com = copynode(n->nnot.com);
8164 new->type = n->type;
8169 * Make a copy of a parse tree.
8171 static struct funcnode *
8172 copyfunc(union node *n)
8177 funcblocksize = offsetof(struct funcnode, n);
8180 blocksize = funcblocksize;
8181 f = ckmalloc(blocksize + funcstringsize);
8182 funcblock = (char *) f + offsetof(struct funcnode, n);
8183 funcstring = (char *) f + blocksize;
8190 * Define a shell function.
8193 defun(char *name, union node *func)
8195 struct cmdentry entry;
8198 entry.cmdtype = CMDFUNCTION;
8199 entry.u.func = copyfunc(func);
8200 addcmdentry(name, &entry);
8204 /* Reasons for skipping commands (see comment on breakcmd routine) */
8205 #define SKIPBREAK (1 << 0)
8206 #define SKIPCONT (1 << 1)
8207 #define SKIPFUNC (1 << 2)
8208 #define SKIPFILE (1 << 3)
8209 #define SKIPEVAL (1 << 4)
8210 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8211 static int skipcount; /* number of levels to skip */
8212 static int funcnest; /* depth of function calls */
8213 static int loopnest; /* current loop nesting level */
8215 /* Forward decl way out to parsing code - dotrap needs it */
8216 static int evalstring(char *s, int mask);
8218 /* Called to execute a trap.
8219 * Single callsite - at the end of evaltree().
8220 * If we return non-zero, exaltree raises EXEXIT exception.
8222 * Perhaps we should avoid entering new trap handlers
8223 * while we are executing a trap handler. [is it a TODO?]
8232 savestatus = exitstatus;
8236 TRACE(("dotrap entered\n"));
8237 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8244 /* non-trapped SIGINT is handled separately by raise_interrupt,
8245 * don't upset it by resetting gotsig[SIGINT-1] */
8246 if (sig == SIGINT && !t)
8249 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
8253 want_exexit = evalstring(t, SKIPEVAL);
8254 exitstatus = savestatus;
8256 TRACE(("dotrap returns %d\n", want_exexit));
8261 TRACE(("dotrap returns 0\n"));
8265 /* forward declarations - evaluation is fairly recursive business... */
8266 static void evalloop(union node *, int);
8267 static void evalfor(union node *, int);
8268 static void evalcase(union node *, int);
8269 static void evalsubshell(union node *, int);
8270 static void expredir(union node *);
8271 static void evalpipe(union node *, int);
8272 static void evalcommand(union node *, int);
8273 static int evalbltin(const struct builtincmd *, int, char **);
8274 static void prehash(union node *);
8277 * Evaluate a parse tree. The value is left in the global variable
8281 evaltree(union node *n, int flags)
8283 struct jmploc *volatile savehandler = exception_handler;
8284 struct jmploc jmploc;
8286 void (*evalfn)(union node *, int);
8290 SAVE_INT(int_level);
8293 TRACE(("evaltree(NULL) called\n"));
8296 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8298 exception_handler = &jmploc;
8300 int err = setjmp(jmploc.loc);
8302 /* if it was a signal, check for trap handlers */
8303 if (exception_type == EXSIG) {
8304 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8305 exception_type, err));
8308 /* continue on the way out */
8309 TRACE(("exception %d in evaltree, propagating err=%d\n",
8310 exception_type, err));
8311 exception_handler = savehandler;
8312 longjmp(exception_handler->loc, err);
8319 out1fmt("Node type = %d\n", n->type);
8324 evaltree(n->nnot.com, EV_TESTED);
8325 status = !exitstatus;
8328 expredir(n->nredir.redirect);
8329 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8331 evaltree(n->nredir.n, flags & EV_TESTED);
8332 status = exitstatus;
8334 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8337 evalfn = evalcommand;
8339 if (eflag && !(flags & EV_TESTED))
8351 evalfn = evalsubshell;
8364 #error NAND + 1 != NOR
8366 #if NOR + 1 != NSEMI
8367 #error NOR + 1 != NSEMI
8369 unsigned is_or = n->type - NAND;
8372 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8374 if (!exitstatus == is_or)
8387 evaltree(n->nif.test, EV_TESTED);
8390 if (exitstatus == 0) {
8394 if (n->nif.elsepart) {
8395 n = n->nif.elsepart;
8400 defun(n->narg.text, n->narg.next);
8404 exitstatus = status;
8409 exception_handler = savehandler;
8411 if (checkexit & exitstatus)
8412 evalskip |= SKIPEVAL;
8413 else if (pending_sig && dotrap())
8416 if (flags & EV_EXIT) {
8418 raise_exception(EXEXIT);
8421 RESTORE_INT(int_level);
8422 TRACE(("leaving evaltree (no interrupts)\n"));
8425 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8428 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8431 evalloop(union node *n, int flags)
8441 evaltree(n->nbinary.ch1, EV_TESTED);
8444 if (evalskip == SKIPCONT && --skipcount <= 0) {
8448 if (evalskip == SKIPBREAK && --skipcount <= 0)
8453 if (n->type != NWHILE)
8457 evaltree(n->nbinary.ch2, flags);
8458 status = exitstatus;
8463 exitstatus = status;
8467 evalfor(union node *n, int flags)
8469 struct arglist arglist;
8472 struct stackmark smark;
8474 setstackmark(&smark);
8475 arglist.list = NULL;
8476 arglist.lastp = &arglist.list;
8477 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8478 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
8483 *arglist.lastp = NULL;
8488 for (sp = arglist.list; sp; sp = sp->next) {
8489 setvar(n->nfor.var, sp->text, 0);
8490 evaltree(n->nfor.body, flags);
8492 if (evalskip == SKIPCONT && --skipcount <= 0) {
8496 if (evalskip == SKIPBREAK && --skipcount <= 0)
8503 popstackmark(&smark);
8507 evalcase(union node *n, int flags)
8511 struct arglist arglist;
8512 struct stackmark smark;
8514 setstackmark(&smark);
8515 arglist.list = NULL;
8516 arglist.lastp = &arglist.list;
8517 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8519 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8520 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8521 if (casematch(patp, arglist.list->text)) {
8522 if (evalskip == 0) {
8523 evaltree(cp->nclist.body, flags);
8530 popstackmark(&smark);
8534 * Kick off a subshell to evaluate a tree.
8537 evalsubshell(union node *n, int flags)
8540 int backgnd = (n->type == NBACKGND);
8543 expredir(n->nredir.redirect);
8544 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8547 jp = makejob(/*n,*/ 1);
8548 if (forkshell(jp, n, backgnd) == 0) {
8553 flags &= ~EV_TESTED;
8555 redirect(n->nredir.redirect, 0);
8556 evaltreenr(n->nredir.n, flags);
8561 status = waitforjob(jp);
8562 exitstatus = status;
8567 * Compute the names of the files in a redirection list.
8569 static void fixredir(union node *, const char *, int);
8571 expredir(union node *n)
8575 for (redir = n; redir; redir = redir->nfile.next) {
8579 fn.lastp = &fn.list;
8580 switch (redir->type) {
8584 #if ENABLE_ASH_BASH_COMPAT
8589 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8590 #if ENABLE_ASH_BASH_COMPAT
8593 redir->nfile.expfname = fn.list->text;
8596 case NTOFD: /* >& */
8597 if (redir->ndup.vname) {
8598 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
8599 if (fn.list == NULL)
8600 ash_msg_and_raise_error("redir error");
8601 #if ENABLE_ASH_BASH_COMPAT
8602 //FIXME: we used expandarg with different args!
8603 if (!isdigit_str9(fn.list->text)) {
8604 /* >&file, not >&fd */
8605 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8606 ash_msg_and_raise_error("redir error");
8608 goto store_expfname;
8611 fixredir(redir, fn.list->text, 1);
8619 * Evaluate a pipeline. All the processes in the pipeline are children
8620 * of the process creating the pipeline. (This differs from some versions
8621 * of the shell, which make the last process in a pipeline the parent
8625 evalpipe(union node *n, int flags)
8628 struct nodelist *lp;
8633 TRACE(("evalpipe(0x%lx) called\n", (long)n));
8635 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
8639 jp = makejob(/*n,*/ pipelen);
8641 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
8645 if (pipe(pip) < 0) {
8647 ash_msg_and_raise_error("pipe call failed");
8650 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
8663 evaltreenr(lp->n, flags);
8669 /* Don't want to trigger debugging */
8673 if (n->npipe.pipe_backgnd == 0) {
8674 exitstatus = waitforjob(jp);
8675 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
8681 * Controls whether the shell is interactive or not.
8684 setinteractive(int on)
8686 static smallint is_interactive;
8688 if (++on == is_interactive)
8690 is_interactive = on;
8694 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8695 if (is_interactive > 1) {
8696 /* Looks like they want an interactive shell */
8697 static smallint did_banner;
8700 /* note: ash and hush share this string */
8701 out1fmt("\n\n%s %s\n"
8702 "Enter 'help' for a list of built-in commands."
8705 "built-in shell (ash)"
8719 setinteractive(iflag);
8721 #if ENABLE_FEATURE_EDITING_VI
8723 line_input_state->flags |= VI_MODE;
8725 line_input_state->flags &= ~VI_MODE;
8727 viflag = 0; /* forcibly keep the option off */
8731 static struct localvar *localvars;
8734 * Called after a function returns.
8735 * Interrupts must be off.
8740 struct localvar *lvp;
8743 while ((lvp = localvars) != NULL) {
8744 localvars = lvp->next;
8746 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
8747 if (vp == NULL) { /* $- saved */
8748 memcpy(optlist, lvp->text, sizeof(optlist));
8749 free((char*)lvp->text);
8751 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8752 unsetvar(vp->var_text);
8755 vp->var_func(var_end(lvp->text));
8756 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8757 free((char*)vp->var_text);
8758 vp->flags = lvp->flags;
8759 vp->var_text = lvp->text;
8766 evalfun(struct funcnode *func, int argc, char **argv, int flags)
8768 volatile struct shparam saveparam;
8769 struct localvar *volatile savelocalvars;
8770 struct jmploc *volatile savehandler;
8771 struct jmploc jmploc;
8774 saveparam = shellparam;
8775 savelocalvars = localvars;
8776 e = setjmp(jmploc.loc);
8781 savehandler = exception_handler;
8782 exception_handler = &jmploc;
8784 shellparam.malloced = 0;
8788 shellparam.nparam = argc - 1;
8789 shellparam.p = argv + 1;
8790 #if ENABLE_ASH_GETOPTS
8791 shellparam.optind = 1;
8792 shellparam.optoff = -1;
8794 evaltree(&func->n, flags & EV_TESTED);
8800 localvars = savelocalvars;
8801 freeparam(&shellparam);
8802 shellparam = saveparam;
8803 exception_handler = savehandler;
8805 evalskip &= ~SKIPFUNC;
8809 #if ENABLE_ASH_CMDCMD
8811 parse_command_args(char **argv, const char **path)
8824 if (c == '-' && !*cp) {
8831 *path = bb_default_path;
8834 /* run 'typecmd' for other options */
8845 * Make a variable a local variable. When a variable is made local, it's
8846 * value and flags are saved in a localvar structure. The saved values
8847 * will be restored when the shell function returns. We handle the name
8848 * "-" as a special case.
8853 struct localvar *lvp;
8858 lvp = ckzalloc(sizeof(struct localvar));
8859 if (LONE_DASH(name)) {
8861 p = ckmalloc(sizeof(optlist));
8862 lvp->text = memcpy(p, optlist, sizeof(optlist));
8867 vpp = hashvar(name);
8868 vp = *findvar(vpp, name);
8869 eq = strchr(name, '=');
8872 setvareq(name, VSTRFIXED);
8874 setvar(name, NULL, VSTRFIXED);
8875 vp = *vpp; /* the new variable */
8876 lvp->flags = VUNSET;
8878 lvp->text = vp->var_text;
8879 lvp->flags = vp->flags;
8880 vp->flags |= VSTRFIXED|VTEXTFIXED;
8886 lvp->next = localvars;
8892 * The "local" command.
8894 static int FAST_FUNC
8895 localcmd(int argc UNUSED_PARAM, char **argv)
8900 while ((name = *argv++) != NULL) {
8906 static int FAST_FUNC
8907 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8912 static int FAST_FUNC
8913 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8918 static int FAST_FUNC
8919 execcmd(int argc UNUSED_PARAM, char **argv)
8922 iflag = 0; /* exit on error */
8925 shellexec(argv + 1, pathval(), 0);
8931 * The return command.
8933 static int FAST_FUNC
8934 returncmd(int argc UNUSED_PARAM, char **argv)
8937 * If called outside a function, do what ksh does;
8938 * skip the rest of the file.
8940 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8941 return argv[1] ? number(argv[1]) : exitstatus;
8944 /* Forward declarations for builtintab[] */
8945 static int breakcmd(int, char **) FAST_FUNC;
8946 static int dotcmd(int, char **) FAST_FUNC;
8947 static int evalcmd(int, char **) FAST_FUNC;
8948 static int exitcmd(int, char **) FAST_FUNC;
8949 static int exportcmd(int, char **) FAST_FUNC;
8950 #if ENABLE_ASH_GETOPTS
8951 static int getoptscmd(int, char **) FAST_FUNC;
8953 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
8954 static int helpcmd(int, char **) FAST_FUNC;
8956 #if ENABLE_SH_MATH_SUPPORT
8957 static int letcmd(int, char **) FAST_FUNC;
8959 static int readcmd(int, char **) FAST_FUNC;
8960 static int setcmd(int, char **) FAST_FUNC;
8961 static int shiftcmd(int, char **) FAST_FUNC;
8962 static int timescmd(int, char **) FAST_FUNC;
8963 static int trapcmd(int, char **) FAST_FUNC;
8964 static int umaskcmd(int, char **) FAST_FUNC;
8965 static int unsetcmd(int, char **) FAST_FUNC;
8966 static int ulimitcmd(int, char **) FAST_FUNC;
8968 #define BUILTIN_NOSPEC "0"
8969 #define BUILTIN_SPECIAL "1"
8970 #define BUILTIN_REGULAR "2"
8971 #define BUILTIN_SPEC_REG "3"
8972 #define BUILTIN_ASSIGN "4"
8973 #define BUILTIN_SPEC_ASSG "5"
8974 #define BUILTIN_REG_ASSG "6"
8975 #define BUILTIN_SPEC_REG_ASSG "7"
8977 /* Stubs for calling non-FAST_FUNC's */
8978 #if ENABLE_ASH_BUILTIN_ECHO
8979 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
8981 #if ENABLE_ASH_BUILTIN_PRINTF
8982 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
8984 #if ENABLE_ASH_BUILTIN_TEST
8985 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
8988 /* Keep these in proper order since it is searched via bsearch() */
8989 static const struct builtincmd builtintab[] = {
8990 { BUILTIN_SPEC_REG "." , dotcmd },
8991 { BUILTIN_SPEC_REG ":" , truecmd },
8992 #if ENABLE_ASH_BUILTIN_TEST
8993 { BUILTIN_REGULAR "[" , testcmd },
8994 #if ENABLE_ASH_BASH_COMPAT
8995 { BUILTIN_REGULAR "[[" , testcmd },
8998 #if ENABLE_ASH_ALIAS
8999 { BUILTIN_REG_ASSG "alias" , aliascmd },
9002 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9004 { BUILTIN_SPEC_REG "break" , breakcmd },
9005 { BUILTIN_REGULAR "cd" , cdcmd },
9006 { BUILTIN_NOSPEC "chdir" , cdcmd },
9007 #if ENABLE_ASH_CMDCMD
9008 { BUILTIN_REGULAR "command" , commandcmd },
9010 { BUILTIN_SPEC_REG "continue", breakcmd },
9011 #if ENABLE_ASH_BUILTIN_ECHO
9012 { BUILTIN_REGULAR "echo" , echocmd },
9014 { BUILTIN_SPEC_REG "eval" , evalcmd },
9015 { BUILTIN_SPEC_REG "exec" , execcmd },
9016 { BUILTIN_SPEC_REG "exit" , exitcmd },
9017 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9018 { BUILTIN_REGULAR "false" , falsecmd },
9020 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9022 #if ENABLE_ASH_GETOPTS
9023 { BUILTIN_REGULAR "getopts" , getoptscmd },
9025 { BUILTIN_NOSPEC "hash" , hashcmd },
9026 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9027 { BUILTIN_NOSPEC "help" , helpcmd },
9030 { BUILTIN_REGULAR "jobs" , jobscmd },
9031 { BUILTIN_REGULAR "kill" , killcmd },
9033 #if ENABLE_SH_MATH_SUPPORT
9034 { BUILTIN_NOSPEC "let" , letcmd },
9036 { BUILTIN_ASSIGN "local" , localcmd },
9037 #if ENABLE_ASH_BUILTIN_PRINTF
9038 { BUILTIN_REGULAR "printf" , printfcmd },
9040 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9041 { BUILTIN_REGULAR "read" , readcmd },
9042 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9043 { BUILTIN_SPEC_REG "return" , returncmd },
9044 { BUILTIN_SPEC_REG "set" , setcmd },
9045 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9046 #if ENABLE_ASH_BASH_COMPAT
9047 { BUILTIN_SPEC_REG "source" , dotcmd },
9049 #if ENABLE_ASH_BUILTIN_TEST
9050 { BUILTIN_REGULAR "test" , testcmd },
9052 { BUILTIN_SPEC_REG "times" , timescmd },
9053 { BUILTIN_SPEC_REG "trap" , trapcmd },
9054 { BUILTIN_REGULAR "true" , truecmd },
9055 { BUILTIN_NOSPEC "type" , typecmd },
9056 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9057 { BUILTIN_REGULAR "umask" , umaskcmd },
9058 #if ENABLE_ASH_ALIAS
9059 { BUILTIN_REGULAR "unalias" , unaliascmd },
9061 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9062 { BUILTIN_REGULAR "wait" , waitcmd },
9065 /* Should match the above table! */
9066 #define COMMANDCMD (builtintab + \
9068 1 * ENABLE_ASH_BUILTIN_TEST + \
9069 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9070 1 * ENABLE_ASH_ALIAS + \
9071 1 * ENABLE_ASH_JOB_CONTROL + \
9073 #define EXECCMD (builtintab + \
9075 1 * ENABLE_ASH_BUILTIN_TEST + \
9076 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
9077 1 * ENABLE_ASH_ALIAS + \
9078 1 * ENABLE_ASH_JOB_CONTROL + \
9080 1 * ENABLE_ASH_CMDCMD + \
9082 ENABLE_ASH_BUILTIN_ECHO + \
9086 * Search the table of builtin commands.
9088 static struct builtincmd *
9089 find_builtin(const char *name)
9091 struct builtincmd *bp;
9094 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9101 * Execute a simple command.
9104 isassignment(const char *p)
9106 const char *q = endofname(p);
9111 static int FAST_FUNC
9112 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9114 /* Preserve exitstatus of a previous possible redirection
9115 * as POSIX mandates */
9116 return back_exitstatus;
9119 evalcommand(union node *cmd, int flags)
9121 static const struct builtincmd null_bltin = {
9122 "\0\0", bltincmd /* why three NULs? */
9124 struct stackmark smark;
9126 struct arglist arglist;
9127 struct arglist varlist;
9130 const struct strlist *sp;
9131 struct cmdentry cmdentry;
9138 struct builtincmd *bcmd;
9139 smallint cmd_is_exec;
9140 smallint pseudovarflag = 0;
9142 /* First expand the arguments. */
9143 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9144 setstackmark(&smark);
9145 back_exitstatus = 0;
9147 cmdentry.cmdtype = CMDBUILTIN;
9148 cmdentry.u.cmd = &null_bltin;
9149 varlist.lastp = &varlist.list;
9150 *varlist.lastp = NULL;
9151 arglist.lastp = &arglist.list;
9152 *arglist.lastp = NULL;
9155 if (cmd->ncmd.args) {
9156 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9157 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9160 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9161 struct strlist **spp;
9163 spp = arglist.lastp;
9164 if (pseudovarflag && isassignment(argp->narg.text))
9165 expandarg(argp, &arglist, EXP_VARTILDE);
9167 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9169 for (sp = *spp; sp; sp = sp->next)
9173 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
9174 for (sp = arglist.list; sp; sp = sp->next) {
9175 TRACE(("evalcommand arg: %s\n", sp->text));
9176 *nargv++ = sp->text;
9181 if (iflag && funcnest == 0 && argc > 0)
9182 lastarg = nargv[-1];
9185 expredir(cmd->ncmd.redirect);
9186 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9188 path = vpath.var_text;
9189 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9190 struct strlist **spp;
9193 spp = varlist.lastp;
9194 expandarg(argp, &varlist, EXP_VARTILDE);
9197 * Modify the command lookup path, if a PATH= assignment
9201 if (varcmp(p, path) == 0)
9205 /* Print the command if xflag is set. */
9208 const char *p = " %s" + 1;
9210 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9212 for (n = 0; n < 2; n++) {
9214 fdprintf(preverrout_fd, p, sp->text);
9220 safe_write(preverrout_fd, "\n", 1);
9226 /* Now locate the command. */
9228 const char *oldpath;
9229 int cmd_flag = DO_ERR;
9234 find_command(argv[0], &cmdentry, cmd_flag, path);
9235 if (cmdentry.cmdtype == CMDUNKNOWN) {
9236 flush_stdout_stderr();
9241 /* implement bltin and command here */
9242 if (cmdentry.cmdtype != CMDBUILTIN)
9245 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9246 if (cmdentry.u.cmd == EXECCMD)
9248 #if ENABLE_ASH_CMDCMD
9249 if (cmdentry.u.cmd == COMMANDCMD) {
9251 nargv = parse_command_args(argv, &path);
9254 argc -= nargv - argv;
9256 cmd_flag |= DO_NOFUNC;
9264 /* We have a redirection error. */
9266 raise_exception(EXERROR);
9268 exitstatus = status;
9272 /* Execute the command. */
9273 switch (cmdentry.cmdtype) {
9276 #if ENABLE_FEATURE_SH_NOFORK
9277 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9278 * around run_nofork_applet() call.
9279 * (2) Should this check also be done in forkshell()?
9280 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9282 /* find_command() encodes applet_no as (-2 - applet_no) */
9283 int applet_no = (- cmdentry.u.index - 2);
9284 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9285 listsetvar(varlist.list, VEXPORT|VSTACK);
9286 /* run <applet>_main() */
9287 exitstatus = run_nofork_applet(applet_no, argv);
9291 /* Can we avoid forking off? For example, very last command
9292 * in a script or a subshell does not need forking,
9293 * we can just exec it.
9295 if (!(flags & EV_EXIT) || may_have_traps) {
9296 /* No, forking off a child is necessary */
9298 jp = makejob(/*cmd,*/ 1);
9299 if (forkshell(jp, cmd, FORK_FG) != 0) {
9301 exitstatus = waitforjob(jp);
9303 TRACE(("forked child exited with %d\n", exitstatus));
9308 /* fall through to exec'ing external program */
9310 listsetvar(varlist.list, VEXPORT|VSTACK);
9311 shellexec(argv, path, cmdentry.u.index);
9315 cmdenviron = varlist.list;
9317 struct strlist *list = cmdenviron;
9319 if (spclbltin > 0 || argc == 0) {
9321 if (cmd_is_exec && argc > 1)
9324 listsetvar(list, i);
9326 /* Tight loop with builtins only:
9327 * "while kill -0 $child; do true; done"
9328 * will never exit even if $child died, unless we do this
9329 * to reap the zombie and make kill detect that it's gone: */
9330 dowait(DOWAIT_NONBLOCK, NULL);
9332 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9334 int i = exception_type;
9339 exit_status = 128 + SIGINT;
9341 exit_status = 128 + pending_sig;
9342 exitstatus = exit_status;
9343 if (i == EXINT || spclbltin > 0) {
9345 longjmp(exception_handler->loc, 1);
9352 listsetvar(varlist.list, 0);
9353 /* See above for the rationale */
9354 dowait(DOWAIT_NONBLOCK, NULL);
9355 if (evalfun(cmdentry.u.func, argc, argv, flags))
9362 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9364 /* dsl: I think this is intended to be used to support
9365 * '_' in 'vi' command mode during line editing...
9366 * However I implemented that within libedit itself.
9368 setvar("_", lastarg, 0);
9370 popstackmark(&smark);
9374 evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9376 char *volatile savecmdname;
9377 struct jmploc *volatile savehandler;
9378 struct jmploc jmploc;
9381 savecmdname = commandname;
9382 i = setjmp(jmploc.loc);
9385 savehandler = exception_handler;
9386 exception_handler = &jmploc;
9387 commandname = argv[0];
9389 optptr = NULL; /* initialize nextopt */
9390 exitstatus = (*cmd->builtin)(argc, argv);
9391 flush_stdout_stderr();
9393 exitstatus |= ferror(stdout);
9395 commandname = savecmdname;
9396 exception_handler = savehandler;
9402 goodname(const char *p)
9404 return !*endofname(p);
9409 * Search for a command. This is called before we fork so that the
9410 * location of the command will be available in the parent as well as
9411 * the child. The check for "goodname" is an overly conservative
9412 * check that the name will not be subject to expansion.
9415 prehash(union node *n)
9417 struct cmdentry entry;
9419 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9420 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9424 /* ============ Builtin commands
9426 * Builtin commands whose functions are closely tied to evaluation
9427 * are implemented here.
9431 * Handle break and continue commands. Break, continue, and return are
9432 * all handled by setting the evalskip flag. The evaluation routines
9433 * above all check this flag, and if it is set they start skipping
9434 * commands rather than executing them. The variable skipcount is
9435 * the number of loops to break/continue, or the number of function
9436 * levels to return. (The latter is always 1.) It should probably
9437 * be an error to break out of more loops than exist, but it isn't
9438 * in the standard shell so we don't make it one here.
9440 static int FAST_FUNC
9441 breakcmd(int argc UNUSED_PARAM, char **argv)
9443 int n = argv[1] ? number(argv[1]) : 1;
9446 ash_msg_and_raise_error(msg_illnum, argv[1]);
9450 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9457 /* ============ input.c
9459 * This implements the input routines used by the parser.
9463 INPUT_PUSH_FILE = 1,
9464 INPUT_NOFILE_OK = 2,
9467 static smallint checkkwd;
9468 /* values of checkkwd variable */
9469 #define CHKALIAS 0x1
9474 * Push a string back onto the input at this current parsefile level.
9475 * We handle aliases this way.
9477 #if !ENABLE_ASH_ALIAS
9478 #define pushstring(s, ap) pushstring(s)
9481 pushstring(char *s, struct alias *ap)
9488 if (g_parsefile->strpush) {
9489 sp = ckzalloc(sizeof(*sp));
9490 sp->prev = g_parsefile->strpush;
9492 sp = &(g_parsefile->basestrpush);
9494 g_parsefile->strpush = sp;
9495 sp->prev_string = g_parsefile->next_to_pgetc;
9496 sp->prev_left_in_line = g_parsefile->left_in_line;
9497 #if ENABLE_ASH_ALIAS
9500 ap->flag |= ALIASINUSE;
9504 g_parsefile->next_to_pgetc = s;
9505 g_parsefile->left_in_line = len;
9512 struct strpush *sp = g_parsefile->strpush;
9515 #if ENABLE_ASH_ALIAS
9517 if (g_parsefile->next_to_pgetc[-1] == ' '
9518 || g_parsefile->next_to_pgetc[-1] == '\t'
9520 checkkwd |= CHKALIAS;
9522 if (sp->string != sp->ap->val) {
9525 sp->ap->flag &= ~ALIASINUSE;
9526 if (sp->ap->flag & ALIASDEAD) {
9527 unalias(sp->ap->name);
9531 g_parsefile->next_to_pgetc = sp->prev_string;
9532 g_parsefile->left_in_line = sp->prev_left_in_line;
9533 g_parsefile->strpush = sp->prev;
9534 if (sp != &(g_parsefile->basestrpush))
9539 //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9540 //it peeks whether it is &>, and then pushes back both chars.
9541 //This function needs to save last *next_to_pgetc to buf[0]
9542 //to make two pungetc() reliable. Currently,
9543 // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
9548 char *buf = g_parsefile->buf;
9550 g_parsefile->next_to_pgetc = buf;
9551 #if ENABLE_FEATURE_EDITING
9553 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9554 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9556 #if ENABLE_FEATURE_TAB_COMPLETION
9557 line_input_state->path_lookup = pathval();
9559 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
9561 /* Ctrl+C pressed */
9570 if (nr < 0 && errno == 0) {
9571 /* Ctrl+D pressed */
9576 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
9580 /* nonblock_safe_read() handles this problem */
9582 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
9583 int flags = fcntl(0, F_GETFL);
9584 if (flags >= 0 && (flags & O_NONBLOCK)) {
9585 flags &= ~O_NONBLOCK;
9586 if (fcntl(0, F_SETFL, flags) >= 0) {
9587 out2str("sh: turning off NDELAY mode\n");
9598 * Refill the input buffer and return the next input character:
9600 * 1) If a string was pushed back on the input, pop it;
9601 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9602 * or we are reading from a string so we can't refill the buffer,
9604 * 3) If there is more stuff in this buffer, use it else call read to fill it.
9605 * 4) Process input up to the next newline, deleting nul characters.
9607 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9608 #define pgetc_debug(...) ((void)0)
9615 while (g_parsefile->strpush) {
9616 #if ENABLE_ASH_ALIAS
9617 if (g_parsefile->left_in_line == -1
9618 && g_parsefile->strpush->ap
9619 && g_parsefile->next_to_pgetc[-1] != ' '
9620 && g_parsefile->next_to_pgetc[-1] != '\t'
9622 pgetc_debug("preadbuffer PEOA");
9627 /* try "pgetc" now: */
9628 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9629 g_parsefile->left_in_line,
9630 g_parsefile->next_to_pgetc,
9631 g_parsefile->next_to_pgetc);
9632 if (--g_parsefile->left_in_line >= 0)
9633 return (unsigned char)(*g_parsefile->next_to_pgetc++);
9635 /* on both branches above g_parsefile->left_in_line < 0.
9636 * "pgetc" needs refilling.
9639 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
9640 * pungetc() may increment it a few times.
9641 * Assuming it won't increment it to less than -90.
9643 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
9644 pgetc_debug("preadbuffer PEOF1");
9645 /* even in failure keep left_in_line and next_to_pgetc
9646 * in lock step, for correct multi-layer pungetc.
9647 * left_in_line was decremented before preadbuffer(),
9648 * must inc next_to_pgetc: */
9649 g_parsefile->next_to_pgetc++;
9653 more = g_parsefile->left_in_buffer;
9655 flush_stdout_stderr();
9659 /* don't try reading again */
9660 g_parsefile->left_in_line = -99;
9661 pgetc_debug("preadbuffer PEOF2");
9662 g_parsefile->next_to_pgetc++;
9667 /* Find out where's the end of line.
9668 * Set g_parsefile->left_in_line
9669 * and g_parsefile->left_in_buffer acordingly.
9670 * NUL chars are deleted.
9672 q = g_parsefile->next_to_pgetc;
9680 memmove(q, q + 1, more);
9684 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9690 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9691 if (g_parsefile->left_in_line < 0)
9696 g_parsefile->left_in_buffer = more;
9701 out2str(g_parsefile->next_to_pgetc);
9705 pgetc_debug("preadbuffer at %d:%p'%s'",
9706 g_parsefile->left_in_line,
9707 g_parsefile->next_to_pgetc,
9708 g_parsefile->next_to_pgetc);
9709 return (unsigned char)*g_parsefile->next_to_pgetc++;
9712 #define pgetc_as_macro() \
9713 (--g_parsefile->left_in_line >= 0 \
9714 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
9721 pgetc_debug("pgetc_fast at %d:%p'%s'",
9722 g_parsefile->left_in_line,
9723 g_parsefile->next_to_pgetc,
9724 g_parsefile->next_to_pgetc);
9725 return pgetc_as_macro();
9728 #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9729 # define pgetc_fast() pgetc()
9731 # define pgetc_fast() pgetc_as_macro()
9734 #if ENABLE_ASH_ALIAS
9736 pgetc_without_PEOA(void)
9740 pgetc_debug("pgetc_fast at %d:%p'%s'",
9741 g_parsefile->left_in_line,
9742 g_parsefile->next_to_pgetc,
9743 g_parsefile->next_to_pgetc);
9745 } while (c == PEOA);
9749 # define pgetc_without_PEOA() pgetc()
9753 * Read a line from the script.
9756 pfgets(char *line, int len)
9762 while (--nleft > 0) {
9763 c = pgetc_without_PEOA();
9778 * Undo the last call to pgetc. Only one character may be pushed back.
9779 * PEOF may be pushed back.
9784 g_parsefile->left_in_line++;
9785 g_parsefile->next_to_pgetc--;
9786 pgetc_debug("pushed back to %d:%p'%s'",
9787 g_parsefile->left_in_line,
9788 g_parsefile->next_to_pgetc,
9789 g_parsefile->next_to_pgetc);
9793 * To handle the "." command, a stack of input files is used. Pushfile
9794 * adds a new entry to the stack and popfile restores the previous level.
9799 struct parsefile *pf;
9801 pf = ckzalloc(sizeof(*pf));
9802 pf->prev = g_parsefile;
9804 /*pf->strpush = NULL; - ckzalloc did it */
9805 /*pf->basestrpush.prev = NULL;*/
9812 struct parsefile *pf = g_parsefile;
9820 g_parsefile = pf->prev;
9826 * Return to top level.
9831 while (g_parsefile != &basepf)
9836 * Close the file(s) that the shell is reading commands from. Called
9837 * after a fork is done.
9843 if (g_parsefile->pf_fd > 0) {
9844 close(g_parsefile->pf_fd);
9845 g_parsefile->pf_fd = 0;
9850 * Like setinputfile, but takes an open file descriptor. Call this with
9854 setinputfd(int fd, int push)
9856 close_on_exec_on(fd);
9859 g_parsefile->buf = NULL;
9861 g_parsefile->pf_fd = fd;
9862 if (g_parsefile->buf == NULL)
9863 g_parsefile->buf = ckmalloc(IBUFSIZ);
9864 g_parsefile->left_in_buffer = 0;
9865 g_parsefile->left_in_line = 0;
9866 g_parsefile->linno = 1;
9870 * Set the input to take input from a file. If push is set, push the
9871 * old input onto the stack first.
9874 setinputfile(const char *fname, int flags)
9880 fd = open(fname, O_RDONLY);
9882 if (flags & INPUT_NOFILE_OK)
9884 ash_msg_and_raise_error("can't open '%s'", fname);
9887 fd2 = copyfd(fd, 10);
9890 ash_msg_and_raise_error("out of file descriptors");
9893 setinputfd(fd, flags & INPUT_PUSH_FILE);
9900 * Like setinputfile, but takes input from a string.
9903 setinputstring(char *string)
9907 g_parsefile->next_to_pgetc = string;
9908 g_parsefile->left_in_line = strlen(string);
9909 g_parsefile->buf = NULL;
9910 g_parsefile->linno = 1;
9915 /* ============ mail.c
9917 * Routines to check for mail.
9922 #define MAXMBOXES 10
9924 /* times of mailboxes */
9925 static time_t mailtime[MAXMBOXES];
9926 /* Set if MAIL or MAILPATH is changed. */
9927 static smallint mail_var_path_changed;
9930 * Print appropriate message(s) if mail has arrived.
9931 * If mail_var_path_changed is set,
9932 * then the value of MAIL has mail_var_path_changed,
9933 * so we just update the values.
9942 struct stackmark smark;
9945 setstackmark(&smark);
9946 mpath = mpathset() ? mpathval() : mailval();
9947 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
9948 p = path_advance(&mpath, nullstr);
9953 for (q = p; *q; q++)
9959 q[-1] = '\0'; /* delete trailing '/' */
9960 if (stat(p, &statb) < 0) {
9964 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9967 pathopt ? pathopt : "you have mail"
9970 *mtp = statb.st_mtime;
9972 mail_var_path_changed = 0;
9973 popstackmark(&smark);
9976 static void FAST_FUNC
9977 changemail(const char *val UNUSED_PARAM)
9979 mail_var_path_changed = 1;
9982 #endif /* ASH_MAIL */
9985 /* ============ ??? */
9988 * Set the shell parameters.
9991 setparam(char **argv)
9997 for (nparam = 0; argv[nparam]; nparam++)
9999 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10001 *ap++ = ckstrdup(*argv++);
10004 freeparam(&shellparam);
10005 shellparam.malloced = 1;
10006 shellparam.nparam = nparam;
10007 shellparam.p = newparam;
10008 #if ENABLE_ASH_GETOPTS
10009 shellparam.optind = 1;
10010 shellparam.optoff = -1;
10015 * Process shell options. The global variable argptr contains a pointer
10016 * to the argument list; we advance it past the options.
10018 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10019 * For a non-interactive shell, an error condition encountered
10020 * by a special built-in ... shall cause the shell to write a diagnostic message
10021 * to standard error and exit as shown in the following table:
10022 * Error Special Built-In
10024 * Utility syntax error (option or operand error) Shall exit
10026 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10027 * we see that bash does not do that (set "finishes" with error code 1 instead,
10028 * and shell continues), and people rely on this behavior!
10030 * set -o barfoo 2>/dev/null
10033 * Oh well. Let's mimic that.
10036 plus_minus_o(char *name, int val)
10041 for (i = 0; i < NOPTS; i++) {
10042 if (strcmp(name, optnames(i)) == 0) {
10047 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10050 for (i = 0; i < NOPTS; i++) {
10052 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10054 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10060 setoption(int flag, int val)
10064 for (i = 0; i < NOPTS; i++) {
10065 if (optletters(i) == flag) {
10070 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10074 options(int cmdline)
10082 while ((p = *argptr) != NULL) {
10084 if (c != '-' && c != '+')
10087 val = 0; /* val = 0 if c == '+' */
10090 if (p[0] == '\0' || LONE_DASH(p)) {
10092 /* "-" means turn off -x and -v */
10095 /* "--" means reset params */
10096 else if (*argptr == NULL)
10099 break; /* "-" or "--" terminates options */
10102 /* first char was + or - */
10103 while ((c = *p++) != '\0') {
10104 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10105 if (c == 'c' && cmdline) {
10106 minusc = p; /* command is after shell args */
10107 } else if (c == 'o') {
10108 if (plus_minus_o(*argptr, val)) {
10109 /* it already printed err message */
10110 return 1; /* error */
10114 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10116 /* bash does not accept +-login, we also won't */
10117 } else if (cmdline && val && (c == '-')) { /* long options */
10118 if (strcmp(p, "login") == 0)
10130 * The shift builtin command.
10132 static int FAST_FUNC
10133 shiftcmd(int argc UNUSED_PARAM, char **argv)
10140 n = number(argv[1]);
10141 if (n > shellparam.nparam)
10142 n = 0; /* bash compat, was = shellparam.nparam; */
10144 shellparam.nparam -= n;
10145 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10146 if (shellparam.malloced)
10149 ap2 = shellparam.p;
10150 while ((*ap2++ = *ap1++) != NULL)
10152 #if ENABLE_ASH_GETOPTS
10153 shellparam.optind = 1;
10154 shellparam.optoff = -1;
10161 * POSIX requires that 'set' (but not export or readonly) output the
10162 * variables in lexicographic order - by the locale's collating order (sigh).
10163 * Maybe we could keep them in an ordered balanced binary tree
10164 * instead of hashed lists.
10165 * For now just roll 'em through qsort for printing...
10168 showvars(const char *sep_prefix, int on, int off)
10171 char **ep, **epend;
10173 ep = listvars(on, off, &epend);
10174 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10176 sep = *sep_prefix ? " " : sep_prefix;
10178 for (; ep < epend; ep++) {
10182 p = strchrnul(*ep, '=');
10185 q = single_quote(++p);
10186 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10192 * The set command builtin.
10194 static int FAST_FUNC
10195 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10200 return showvars(nullstr, 0, VUNSET);
10203 if (!options(0)) { /* if no parse error... */
10206 if (*argptr != NULL) {
10214 #if ENABLE_ASH_RANDOM_SUPPORT
10215 static void FAST_FUNC
10216 change_random(const char *value)
10220 if (value == NULL) {
10221 /* "get", generate */
10222 t = next_random(&random_gen);
10223 /* set without recursion */
10224 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10225 vrandom.flags &= ~VNOFUNC;
10228 t = strtoul(value, NULL, 10);
10229 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10234 #if ENABLE_ASH_GETOPTS
10236 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
10245 if (*param_optind < 1)
10247 optnext = optfirst + *param_optind - 1;
10249 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
10252 p = optnext[-1] + *optoff;
10253 if (p == NULL || *p == '\0') {
10254 /* Current word is done, advance */
10256 if (p == NULL || *p != '-' || *++p == '\0') {
10263 if (LONE_DASH(p)) /* check for "--" */
10268 for (q = optstr; *q != c;) {
10270 if (optstr[0] == ':') {
10273 err |= setvarsafe("OPTARG", s, 0);
10275 fprintf(stderr, "Illegal option -%c\n", c);
10276 unsetvar("OPTARG");
10286 if (*p == '\0' && (p = *optnext) == NULL) {
10287 if (optstr[0] == ':') {
10290 err |= setvarsafe("OPTARG", s, 0);
10293 fprintf(stderr, "No arg for -%c option\n", c);
10294 unsetvar("OPTARG");
10302 err |= setvarsafe("OPTARG", p, 0);
10305 err |= setvarsafe("OPTARG", nullstr, 0);
10307 *optoff = p ? p - *(optnext - 1) : -1;
10308 *param_optind = optnext - optfirst + 1;
10309 fmtstr(s, sizeof(s), "%d", *param_optind);
10310 err |= setvarsafe("OPTIND", s, VNOFUNC);
10313 err |= setvarsafe(optvar, s, 0);
10317 flush_stdout_stderr();
10318 raise_exception(EXERROR);
10324 * The getopts builtin. Shellparam.optnext points to the next argument
10325 * to be processed. Shellparam.optptr points to the next character to
10326 * be processed in the current argument. If shellparam.optnext is NULL,
10327 * then it's the first time getopts has been called.
10329 static int FAST_FUNC
10330 getoptscmd(int argc, char **argv)
10335 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10337 optbase = shellparam.p;
10338 if (shellparam.optind > shellparam.nparam + 1) {
10339 shellparam.optind = 1;
10340 shellparam.optoff = -1;
10343 optbase = &argv[3];
10344 if (shellparam.optind > argc - 2) {
10345 shellparam.optind = 1;
10346 shellparam.optoff = -1;
10350 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
10351 &shellparam.optoff);
10353 #endif /* ASH_GETOPTS */
10356 /* ============ Shell parser */
10359 struct heredoc *next; /* next here document in list */
10360 union node *here; /* redirection node */
10361 char *eofmark; /* string indicating end of input */
10362 smallint striptabs; /* if set, strip leading tabs */
10365 static smallint tokpushback; /* last token pushed back */
10366 static smallint parsebackquote; /* nonzero if we are inside backquotes */
10367 static smallint quoteflag; /* set if (part of) last token was quoted */
10368 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10369 static struct heredoc *heredoclist; /* list of here documents to read */
10370 static char *wordtext; /* text of last word returned by readtoken */
10371 static struct nodelist *backquotelist;
10372 static union node *redirnode;
10373 static struct heredoc *heredoc;
10375 static const char *
10376 tokname(char *buf, int tok)
10379 return tokname_array[tok] + 1;
10380 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10384 /* raise_error_unexpected_syntax:
10385 * Called when an unexpected token is read during the parse. The argument
10386 * is the token that is expected, or -1 if more than one type of token can
10387 * occur at this point.
10389 static void raise_error_unexpected_syntax(int) NORETURN;
10391 raise_error_unexpected_syntax(int token)
10397 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10399 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10400 raise_error_syntax(msg);
10404 #define EOFMARKLEN 79
10406 /* parsing is heavily cross-recursive, need these forward decls */
10407 static union node *andor(void);
10408 static union node *pipeline(void);
10409 static union node *parse_command(void);
10410 static void parseheredoc(void);
10411 static char peektoken(void);
10412 static int readtoken(void);
10414 static union node *
10417 union node *n1, *n2, *n3;
10420 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10421 if (nlflag == 2 && peektoken())
10427 if (tok == TBACKGND) {
10428 if (n2->type == NPIPE) {
10429 n2->npipe.pipe_backgnd = 1;
10431 if (n2->type != NREDIR) {
10432 n3 = stzalloc(sizeof(struct nredir));
10434 /*n3->nredir.redirect = NULL; - stzalloc did it */
10437 n2->type = NBACKGND;
10443 n3 = stzalloc(sizeof(struct nbinary));
10445 n3->nbinary.ch1 = n1;
10446 n3->nbinary.ch2 = n2;
10462 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10470 pungetc(); /* push back EOF on input */
10474 raise_error_unexpected_syntax(-1);
10481 static union node *
10484 union node *n1, *n2, *n3;
10492 } else if (t == TOR) {
10498 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10500 n3 = stzalloc(sizeof(struct nbinary));
10502 n3->nbinary.ch1 = n1;
10503 n3->nbinary.ch2 = n2;
10508 static union node *
10511 union node *n1, *n2, *pipenode;
10512 struct nodelist *lp, *prev;
10516 TRACE(("pipeline: entered\n"));
10517 if (readtoken() == TNOT) {
10519 checkkwd = CHKKWD | CHKALIAS;
10522 n1 = parse_command();
10523 if (readtoken() == TPIPE) {
10524 pipenode = stzalloc(sizeof(struct npipe));
10525 pipenode->type = NPIPE;
10526 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
10527 lp = stzalloc(sizeof(struct nodelist));
10528 pipenode->npipe.cmdlist = lp;
10532 lp = stzalloc(sizeof(struct nodelist));
10533 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10534 lp->n = parse_command();
10536 } while (readtoken() == TPIPE);
10542 n2 = stzalloc(sizeof(struct nnot));
10550 static union node *
10555 n = stzalloc(sizeof(struct narg));
10557 /*n->narg.next = NULL; - stzalloc did it */
10558 n->narg.text = wordtext;
10559 n->narg.backquote = backquotelist;
10564 fixredir(union node *n, const char *text, int err)
10568 TRACE(("Fix redir %s %d\n", text, err));
10570 n->ndup.vname = NULL;
10572 fd = bb_strtou(text, NULL, 10);
10573 if (!errno && fd >= 0)
10574 n->ndup.dupfd = fd;
10575 else if (LONE_DASH(text))
10576 n->ndup.dupfd = -1;
10579 raise_error_syntax("bad fd number");
10580 n->ndup.vname = makename();
10585 * Returns true if the text contains nothing to expand (no dollar signs
10589 noexpand(const char *text)
10593 while ((c = *text++) != '\0') {
10594 if (c == CTLQUOTEMARK)
10598 else if (SIT(c, BASESYNTAX) == CCTL)
10607 union node *n = redirnode;
10609 if (readtoken() != TWORD)
10610 raise_error_unexpected_syntax(-1);
10611 if (n->type == NHERE) {
10612 struct heredoc *here = heredoc;
10616 if (quoteflag == 0)
10618 TRACE(("Here document %d\n", n->type));
10619 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10620 raise_error_syntax("illegal eof marker for << redirection");
10621 rmescapes(wordtext, 0);
10622 here->eofmark = wordtext;
10624 if (heredoclist == NULL)
10625 heredoclist = here;
10627 for (p = heredoclist; p->next; p = p->next)
10631 } else if (n->type == NTOFD || n->type == NFROMFD) {
10632 fixredir(n, wordtext, 0);
10634 n->nfile.fname = makename();
10638 static union node *
10641 union node *args, **app;
10642 union node *n = NULL;
10643 union node *vars, **vpp;
10644 union node **rpp, *redir;
10646 #if ENABLE_ASH_BASH_COMPAT
10647 smallint double_brackets_flag = 0;
10657 savecheckkwd = CHKALIAS;
10660 checkkwd = savecheckkwd;
10663 #if ENABLE_ASH_BASH_COMPAT
10664 case TAND: /* "&&" */
10665 case TOR: /* "||" */
10666 if (!double_brackets_flag) {
10670 wordtext = (char *) (t == TAND ? "-a" : "-o");
10673 n = stzalloc(sizeof(struct narg));
10675 /*n->narg.next = NULL; - stzalloc did it */
10676 n->narg.text = wordtext;
10677 #if ENABLE_ASH_BASH_COMPAT
10678 if (strcmp("[[", wordtext) == 0)
10679 double_brackets_flag = 1;
10680 else if (strcmp("]]", wordtext) == 0)
10681 double_brackets_flag = 0;
10683 n->narg.backquote = backquotelist;
10684 if (savecheckkwd && isassignment(wordtext)) {
10686 vpp = &n->narg.next;
10689 app = &n->narg.next;
10694 *rpp = n = redirnode;
10695 rpp = &n->nfile.next;
10696 parsefname(); /* read name of redirection file */
10699 if (args && app == &args->narg.next
10702 struct builtincmd *bcmd;
10705 /* We have a function */
10706 if (readtoken() != TRP)
10707 raise_error_unexpected_syntax(TRP);
10708 name = n->narg.text;
10709 if (!goodname(name)
10710 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10712 raise_error_syntax("bad function name");
10715 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10716 n->narg.next = parse_command();
10729 n = stzalloc(sizeof(struct ncmd));
10731 n->ncmd.args = args;
10732 n->ncmd.assign = vars;
10733 n->ncmd.redirect = redir;
10737 static union node *
10738 parse_command(void)
10740 union node *n1, *n2;
10741 union node *ap, **app;
10742 union node *cp, **cpp;
10743 union node *redir, **rpp;
10750 switch (readtoken()) {
10752 raise_error_unexpected_syntax(-1);
10755 n1 = stzalloc(sizeof(struct nif));
10757 n1->nif.test = list(0);
10758 if (readtoken() != TTHEN)
10759 raise_error_unexpected_syntax(TTHEN);
10760 n1->nif.ifpart = list(0);
10762 while (readtoken() == TELIF) {
10763 n2->nif.elsepart = stzalloc(sizeof(struct nif));
10764 n2 = n2->nif.elsepart;
10766 n2->nif.test = list(0);
10767 if (readtoken() != TTHEN)
10768 raise_error_unexpected_syntax(TTHEN);
10769 n2->nif.ifpart = list(0);
10771 if (lasttoken == TELSE)
10772 n2->nif.elsepart = list(0);
10774 n2->nif.elsepart = NULL;
10782 n1 = stzalloc(sizeof(struct nbinary));
10783 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
10784 n1->nbinary.ch1 = list(0);
10787 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
10788 got == TWORD ? wordtext : ""));
10789 raise_error_unexpected_syntax(TDO);
10791 n1->nbinary.ch2 = list(0);
10796 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
10797 raise_error_syntax("bad for loop variable");
10798 n1 = stzalloc(sizeof(struct nfor));
10800 n1->nfor.var = wordtext;
10801 checkkwd = CHKKWD | CHKALIAS;
10802 if (readtoken() == TIN) {
10804 while (readtoken() == TWORD) {
10805 n2 = stzalloc(sizeof(struct narg));
10807 /*n2->narg.next = NULL; - stzalloc did it */
10808 n2->narg.text = wordtext;
10809 n2->narg.backquote = backquotelist;
10811 app = &n2->narg.next;
10814 n1->nfor.args = ap;
10815 if (lasttoken != TNL && lasttoken != TSEMI)
10816 raise_error_unexpected_syntax(-1);
10818 n2 = stzalloc(sizeof(struct narg));
10820 /*n2->narg.next = NULL; - stzalloc did it */
10821 n2->narg.text = (char *)dolatstr;
10822 /*n2->narg.backquote = NULL;*/
10823 n1->nfor.args = n2;
10825 * Newline or semicolon here is optional (but note
10826 * that the original Bourne shell only allowed NL).
10828 if (lasttoken != TNL && lasttoken != TSEMI)
10831 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10832 if (readtoken() != TDO)
10833 raise_error_unexpected_syntax(TDO);
10834 n1->nfor.body = list(0);
10838 n1 = stzalloc(sizeof(struct ncase));
10840 if (readtoken() != TWORD)
10841 raise_error_unexpected_syntax(TWORD);
10842 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
10844 /*n2->narg.next = NULL; - stzalloc did it */
10845 n2->narg.text = wordtext;
10846 n2->narg.backquote = backquotelist;
10848 checkkwd = CHKKWD | CHKALIAS;
10849 } while (readtoken() == TNL);
10850 if (lasttoken != TIN)
10851 raise_error_unexpected_syntax(TIN);
10852 cpp = &n1->ncase.cases;
10854 checkkwd = CHKNL | CHKKWD;
10856 while (t != TESAC) {
10857 if (lasttoken == TLP)
10859 *cpp = cp = stzalloc(sizeof(struct nclist));
10861 app = &cp->nclist.pattern;
10863 *app = ap = stzalloc(sizeof(struct narg));
10865 /*ap->narg.next = NULL; - stzalloc did it */
10866 ap->narg.text = wordtext;
10867 ap->narg.backquote = backquotelist;
10868 if (readtoken() != TPIPE)
10870 app = &ap->narg.next;
10873 //ap->narg.next = NULL;
10874 if (lasttoken != TRP)
10875 raise_error_unexpected_syntax(TRP);
10876 cp->nclist.body = list(2);
10878 cpp = &cp->nclist.next;
10880 checkkwd = CHKNL | CHKKWD;
10884 raise_error_unexpected_syntax(TENDCASE);
10891 n1 = stzalloc(sizeof(struct nredir));
10892 n1->type = NSUBSHELL;
10893 n1->nredir.n = list(0);
10894 /*n1->nredir.redirect = NULL; - stzalloc did it */
10904 return simplecmd();
10907 if (readtoken() != t)
10908 raise_error_unexpected_syntax(t);
10911 /* Now check for redirection which may follow command */
10912 checkkwd = CHKKWD | CHKALIAS;
10914 while (readtoken() == TREDIR) {
10915 *rpp = n2 = redirnode;
10916 rpp = &n2->nfile.next;
10922 if (n1->type != NSUBSHELL) {
10923 n2 = stzalloc(sizeof(struct nredir));
10928 n1->nredir.redirect = redir;
10933 #if ENABLE_ASH_BASH_COMPAT
10934 static int decode_dollar_squote(void)
10936 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10942 p = strchr(C_escapes, c);
10947 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10951 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10953 } else if (c == 'x') { /* \xHH */
10957 } while (isxdigit(c) && --cnt);
10959 if (cnt == 3) { /* \x but next char is "bad" */
10963 } else { /* simple seq like \\ or \t */
10968 c = bb_process_escape_sequence((void*)&p);
10969 } else { /* unrecognized "\z": print both chars unless ' or " */
10970 if (c != '\'' && c != '"') {
10972 c |= 0x100; /* "please encode \, then me" */
10980 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10981 * is not NULL, read a here document. In the latter case, eofmark is the
10982 * word which marks the end of the document and striptabs is true if
10983 * leading tabs should be stripped from the document. The argument c
10984 * is the first character of the input token or document.
10986 * Because C does not have internal subroutines, I have simulated them
10987 * using goto's to implement the subroutine linkage. The following macros
10988 * will run code that appears at the end of readtoken1.
10990 #define CHECKEND() {goto checkend; checkend_return:;}
10991 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10992 #define PARSESUB() {goto parsesub; parsesub_return:;}
10993 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10994 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10995 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10997 readtoken1(int c, int syntax, char *eofmark, int striptabs)
10999 /* NB: syntax parameter fits into smallint */
11000 /* c parameter is an unsigned char or PEOF or PEOA */
11003 char line[EOFMARKLEN + 1];
11004 struct nodelist *bqlist;
11008 smallint prevsyntax; /* syntax before arithmetic */
11009 #if ENABLE_ASH_EXPAND_PRMT
11010 smallint pssyntax; /* we are expanding a prompt string */
11012 int varnest; /* levels of variables expansion */
11013 int arinest; /* levels of arithmetic expansion */
11014 int parenlevel; /* levels of parens in arithmetic */
11015 int dqvarnest; /* levels of variables expansion within double quotes */
11017 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
11020 /* Avoid longjmp clobbering */
11026 (void) &parenlevel;
11029 (void) &prevsyntax;
11032 startlinno = g_parsefile->linno;
11037 #if ENABLE_ASH_EXPAND_PRMT
11038 pssyntax = (syntax == PSSYNTAX);
11042 dblquote = (syntax == DQSYNTAX);
11048 STARTSTACKSTR(out);
11050 /* For each line, until end of word */
11052 CHECKEND(); /* set c to PEOF if at end of here document */
11053 for (;;) { /* until end of line or end of word */
11054 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11055 switch (SIT(c, syntax)) {
11056 case CNL: /* '\n' */
11057 if (syntax == BASESYNTAX)
11058 goto endword; /* exit outer loop */
11060 g_parsefile->linno++;
11064 goto loop; /* continue outer loop */
11069 if (eofmark == NULL || dblquote)
11070 USTPUTC(CTLESC, out);
11071 #if ENABLE_ASH_BASH_COMPAT
11072 if (c == '\\' && bash_dollar_squote) {
11073 c = decode_dollar_squote();
11075 USTPUTC('\\', out);
11076 c = (unsigned char)c;
11082 case CBACK: /* backslash */
11083 c = pgetc_without_PEOA();
11085 USTPUTC(CTLESC, out);
11086 USTPUTC('\\', out);
11088 } else if (c == '\n') {
11092 #if ENABLE_ASH_EXPAND_PRMT
11093 if (c == '$' && pssyntax) {
11094 USTPUTC(CTLESC, out);
11095 USTPUTC('\\', out);
11098 /* Backslash is retained if we are in "str" and next char isn't special */
11103 && (c != '"' || eofmark != NULL)
11105 USTPUTC(CTLESC, out);
11106 USTPUTC('\\', out);
11108 if (SIT(c, SQSYNTAX) == CCTL)
11109 USTPUTC(CTLESC, out);
11117 if (eofmark == NULL) {
11118 USTPUTC(CTLQUOTEMARK, out);
11126 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
11127 if (eofmark != NULL && arinest == 0
11132 if (dqvarnest == 0) {
11133 syntax = BASESYNTAX;
11140 case CVAR: /* '$' */
11141 PARSESUB(); /* parse substitution */
11143 case CENDVAR: /* '}' */
11146 if (dqvarnest > 0) {
11153 #if ENABLE_SH_MATH_SUPPORT
11154 case CLP: /* '(' in arithmetic */
11158 case CRP: /* ')' in arithmetic */
11159 if (parenlevel > 0) {
11162 if (pgetc() == ')') {
11163 if (--arinest == 0) {
11164 syntax = prevsyntax;
11165 dblquote = (syntax == DQSYNTAX);
11170 * unbalanced parens
11171 * (don't 2nd guess - no error)
11179 case CBQUOTE: /* '`' */
11183 goto endword; /* exit outer loop */
11187 if (varnest == 0) {
11188 #if ENABLE_ASH_BASH_COMPAT
11190 if (pgetc() == '>')
11191 c = 0x100 + '>'; /* flag &> */
11195 goto endword; /* exit outer loop */
11197 IF_ASH_ALIAS(if (c != PEOA))
11204 #if ENABLE_SH_MATH_SUPPORT
11205 if (syntax == ARISYNTAX)
11206 raise_error_syntax("missing '))'");
11208 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
11209 raise_error_syntax("unterminated quoted string");
11210 if (varnest != 0) {
11211 startlinno = g_parsefile->linno;
11213 raise_error_syntax("missing '}'");
11215 USTPUTC('\0', out);
11216 len = out - (char *)stackblock();
11217 out = stackblock();
11218 if (eofmark == NULL) {
11219 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
11222 if (isdigit_str9(out)) {
11223 PARSEREDIR(); /* passed as params: out, c */
11224 lasttoken = TREDIR;
11227 /* else: non-number X seen, interpret it
11228 * as "NNNX>file" = "NNNX >file" */
11232 quoteflag = quotef;
11233 backquotelist = bqlist;
11234 grabstackblock(len);
11238 /* end of readtoken routine */
11241 * Check to see whether we are at the end of the here document. When this
11242 * is called, c is set to the first character of the next input line. If
11243 * we are at the end of the here document, this routine sets the c to PEOF.
11247 #if ENABLE_ASH_ALIAS
11249 c = pgetc_without_PEOA();
11252 while (c == '\t') {
11253 c = pgetc_without_PEOA();
11256 if (c == *eofmark) {
11257 if (pfgets(line, sizeof(line)) != NULL) {
11261 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11263 if (*p == '\n' && *q == '\0') {
11265 g_parsefile->linno++;
11266 needprompt = doprompt;
11268 pushstring(line, NULL);
11273 goto checkend_return;
11277 * Parse a redirection operator. The variable "out" points to a string
11278 * specifying the fd to be redirected. The variable "c" contains the
11279 * first character of the redirection operator.
11282 /* out is already checked to be a valid number or "" */
11283 int fd = (*out == '\0' ? -1 : atoi(out));
11286 np = stzalloc(sizeof(struct nfile));
11291 np->type = NAPPEND;
11293 np->type = NCLOBBER;
11296 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11302 #if ENABLE_ASH_BASH_COMPAT
11303 else if (c == 0x100 + '>') { /* this flags &> redirection */
11305 pgetc(); /* this is '>', no need to check */
11309 else { /* c == '<' */
11310 /*np->nfile.fd = 0; - stzalloc did it */
11314 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11315 np = stzalloc(sizeof(struct nhere));
11316 /*np->nfile.fd = 0; - stzalloc did it */
11319 heredoc = stzalloc(sizeof(struct heredoc));
11320 heredoc->here = np;
11323 heredoc->striptabs = 1;
11325 /*heredoc->striptabs = 0; - stzalloc did it */
11331 np->type = NFROMFD;
11335 np->type = NFROMTO;
11347 goto parseredir_return;
11351 * Parse a substitution. At this point, we have read the dollar sign
11352 * and nothing else.
11355 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11356 * (assuming ascii char codes, as the original implementation did) */
11357 #define is_special(c) \
11358 (((unsigned)(c) - 33 < 32) \
11359 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11361 unsigned char subtype;
11366 if (c > 255 /* PEOA or PEOF */
11367 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11369 #if ENABLE_ASH_BASH_COMPAT
11371 bash_dollar_squote = 1;
11376 } else if (c == '(') {
11377 /* $(command) or $((arith)) */
11378 if (pgetc() == '(') {
11379 #if ENABLE_SH_MATH_SUPPORT
11382 raise_error_syntax("you disabled math support for $((arith)) syntax");
11389 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11390 USTPUTC(CTLVAR, out);
11391 typeloc = out - (char *)stackblock();
11392 USTPUTC(VSNORMAL, out);
11393 subtype = VSNORMAL;
11399 c = '#'; /* ${#} - same as $# */
11401 subtype = VSLENGTH; /* ${#VAR} */
11406 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
11407 /* $[{[#]]NAME[}] */
11411 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
11412 } else if (isdigit(c)) {
11413 /* $[{[#]]NUM[}] */
11417 } while (isdigit(c));
11418 } else if (is_special(c)) {
11419 /* $[{[#]]<specialchar>[}] */
11424 raise_error_syntax("bad substitution");
11426 if (c != '}' && subtype == VSLENGTH) {
11427 /* ${#VAR didn't end with } */
11433 if (subtype == 0) {
11434 /* ${VAR...} but not $VAR or ${#VAR} */
11435 /* c == first char after VAR */
11439 #if ENABLE_ASH_BASH_COMPAT
11440 if (c == ':' || c == '$' || isdigit(c)) {
11441 subtype = VSSUBSTR;
11443 break; /* "goto do_pungetc" is bigger (!) */
11449 static const char types[] ALIGN1 = "}-+?=";
11450 const char *p = strchr(types, c);
11453 subtype = p - types + VSNORMAL;
11459 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
11466 #if ENABLE_ASH_BASH_COMPAT
11468 subtype = VSREPLACE;
11472 subtype++; /* VSREPLACEALL */
11480 if (dblquote || arinest)
11482 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
11483 if (subtype != VSNORMAL) {
11485 if (dblquote || arinest) {
11490 goto parsesub_return;
11494 * Called to parse command substitutions. Newstyle is set if the command
11495 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11496 * list of commands (passed by reference), and savelen is the number of
11497 * characters on the top of the stack which must be preserved.
11500 struct nodelist **nlpp;
11503 char *volatile str;
11504 struct jmploc jmploc;
11505 struct jmploc *volatile savehandler;
11507 smallint saveprompt = 0;
11510 (void) &saveprompt;
11512 savepbq = parsebackquote;
11513 if (setjmp(jmploc.loc)) {
11515 parsebackquote = 0;
11516 exception_handler = savehandler;
11517 longjmp(exception_handler->loc, 1);
11521 savelen = out - (char *)stackblock();
11523 str = ckmalloc(savelen);
11524 memcpy(str, stackblock(), savelen);
11526 savehandler = exception_handler;
11527 exception_handler = &jmploc;
11530 /* We must read until the closing backquote, giving special
11531 treatment to some slashes, and then push the string and
11532 reread it as input, interpreting it normally. */
11539 STARTSTACKSTR(pout);
11552 g_parsefile->linno++;
11556 * If eating a newline, avoid putting
11557 * the newline into the new character
11558 * stream (via the STPUTC after the
11563 if (pc != '\\' && pc != '`' && pc != '$'
11564 && (!dblquote || pc != '"')
11566 STPUTC('\\', pout);
11568 if (pc <= 255 /* not PEOA or PEOF */) {
11574 IF_ASH_ALIAS(case PEOA:)
11575 startlinno = g_parsefile->linno;
11576 raise_error_syntax("EOF in backquote substitution");
11579 g_parsefile->linno++;
11580 needprompt = doprompt;
11589 STPUTC('\0', pout);
11590 psavelen = pout - (char *)stackblock();
11591 if (psavelen > 0) {
11592 pstr = grabstackstr(pout);
11593 setinputstring(pstr);
11598 nlpp = &(*nlpp)->next;
11599 *nlpp = stzalloc(sizeof(**nlpp));
11600 /* (*nlpp)->next = NULL; - stzalloc did it */
11601 parsebackquote = oldstyle;
11604 saveprompt = doprompt;
11611 doprompt = saveprompt;
11612 else if (readtoken() != TRP)
11613 raise_error_unexpected_syntax(TRP);
11618 * Start reading from old file again, ignoring any pushed back
11619 * tokens left from the backquote parsing
11624 while (stackblocksize() <= savelen)
11626 STARTSTACKSTR(out);
11628 memcpy(out, str, savelen);
11629 STADJUST(savelen, out);
11635 parsebackquote = savepbq;
11636 exception_handler = savehandler;
11637 if (arinest || dblquote)
11638 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11640 USTPUTC(CTLBACKQ, out);
11642 goto parsebackq_oldreturn;
11643 goto parsebackq_newreturn;
11646 #if ENABLE_SH_MATH_SUPPORT
11648 * Parse an arithmetic expansion (indicate start of one and set state)
11651 if (++arinest == 1) {
11652 prevsyntax = syntax;
11653 syntax = ARISYNTAX;
11654 USTPUTC(CTLARI, out);
11661 * we collapse embedded arithmetic expansion to
11662 * parenthesis, which should be equivalent
11666 goto parsearith_return;
11670 } /* end of readtoken */
11673 * Read the next input token.
11674 * If the token is a word, we set backquotelist to the list of cmds in
11675 * backquotes. We set quoteflag to true if any part of the word was
11677 * If the token is TREDIR, then we set redirnode to a structure containing
11679 * In all cases, the variable startlinno is set to the number of the line
11680 * on which the token starts.
11682 * [Change comment: here documents and internal procedures]
11683 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11684 * word parsing code into a separate routine. In this case, readtoken
11685 * doesn't need to have any internal procedures, but parseword does.
11686 * We could also make parseoperator in essence the main routine, and
11687 * have parseword (readtoken1?) handle both words and redirection.]
11689 #define NEW_xxreadtoken
11690 #ifdef NEW_xxreadtoken
11691 /* singles must be first! */
11692 static const char xxreadtoken_chars[7] ALIGN1 = {
11693 '\n', '(', ')', /* singles */
11694 '&', '|', ';', /* doubles */
11698 #define xxreadtoken_singles 3
11699 #define xxreadtoken_doubles 3
11701 static const char xxreadtoken_tokens[] ALIGN1 = {
11702 TNL, TLP, TRP, /* only single occurrence allowed */
11703 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11704 TEOF, /* corresponds to trailing nul */
11705 TAND, TOR, TENDCASE /* if double occurrence */
11720 startlinno = g_parsefile->linno;
11721 for (;;) { /* until token or start of word found */
11723 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
11727 while ((c = pgetc()) != '\n' && c != PEOF)
11730 } else if (c == '\\') {
11731 if (pgetc() != '\n') {
11733 break; /* return readtoken1(...) */
11735 startlinno = ++g_parsefile->linno;
11741 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11744 g_parsefile->linno++;
11745 needprompt = doprompt;
11748 p = strchr(xxreadtoken_chars, c);
11750 break; /* return readtoken1(...) */
11752 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11754 if (cc == c) { /* double occurrence? */
11755 p += xxreadtoken_doubles + 1;
11758 #if ENABLE_ASH_BASH_COMPAT
11759 if (c == '&' && cc == '>') /* &> */
11760 break; /* return readtoken1(...) */
11765 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11770 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11772 #else /* old xxreadtoken */
11773 #define RETURN(token) return lasttoken = token
11786 startlinno = g_parsefile->linno;
11787 for (;;) { /* until token or start of word found */
11790 case ' ': case '\t':
11791 IF_ASH_ALIAS(case PEOA:)
11794 while ((c = pgetc()) != '\n' && c != PEOF)
11799 if (pgetc() == '\n') {
11800 startlinno = ++g_parsefile->linno;
11808 g_parsefile->linno++;
11809 needprompt = doprompt;
11814 if (pgetc() == '&')
11819 if (pgetc() == '|')
11824 if (pgetc() == ';')
11837 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11840 #endif /* old xxreadtoken */
11847 smallint alreadyseen = tokpushback;
11850 #if ENABLE_ASH_ALIAS
11859 if (checkkwd & CHKNL) {
11866 if (t != TWORD || quoteflag) {
11871 * check for keywords
11873 if (checkkwd & CHKKWD) {
11874 const char *const *pp;
11876 pp = findkwd(wordtext);
11878 lasttoken = t = pp - tokname_array;
11879 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
11884 if (checkkwd & CHKALIAS) {
11885 #if ENABLE_ASH_ALIAS
11887 ap = lookupalias(wordtext, 1);
11890 pushstring(ap->val, ap);
11900 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11902 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
11914 return tokname_array[t][0];
11918 * Read and parse a command. Returns NODE_EOF on end of file.
11919 * (NULL is a valid parse tree indicating a blank line.)
11921 static union node *
11922 parsecmd(int interact)
11927 doprompt = interact;
11929 setprompt(doprompt);
11941 * Input any here documents.
11946 struct heredoc *here;
11949 here = heredoclist;
11950 heredoclist = NULL;
11956 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11957 here->eofmark, here->striptabs);
11958 n = stzalloc(sizeof(struct narg));
11959 n->narg.type = NARG;
11960 /*n->narg.next = NULL; - stzalloc did it */
11961 n->narg.text = wordtext;
11962 n->narg.backquote = backquotelist;
11963 here->here->nhere.doc = n;
11970 * called by editline -- any expansions to the prompt should be added here.
11972 #if ENABLE_ASH_EXPAND_PRMT
11973 static const char *
11974 expandstr(const char *ps)
11978 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11979 * and token processing _can_ alter it (delete NULs etc). */
11980 setinputstring((char *)ps);
11981 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
11984 n.narg.type = NARG;
11985 n.narg.next = NULL;
11986 n.narg.text = wordtext;
11987 n.narg.backquote = backquotelist;
11989 expandarg(&n, NULL, 0);
11990 return stackblock();
11995 * Execute a command or commands contained in a string.
11998 evalstring(char *s, int mask)
12001 struct stackmark smark;
12005 setstackmark(&smark);
12008 while ((n = parsecmd(0)) != NODE_EOF) {
12010 popstackmark(&smark);
12023 * The eval command.
12025 static int FAST_FUNC
12026 evalcmd(int argc UNUSED_PARAM, char **argv)
12035 STARTSTACKSTR(concat);
12037 concat = stack_putstr(p, concat);
12041 STPUTC(' ', concat);
12043 STPUTC('\0', concat);
12044 p = grabstackstr(concat);
12046 evalstring(p, ~SKIPEVAL);
12052 * Read and execute commands.
12053 * "Top" is nonzero for the top level command loop;
12054 * it turns on prompting if the shell is interactive.
12060 struct stackmark smark;
12064 TRACE(("cmdloop(%d) called\n", top));
12068 setstackmark(&smark);
12071 showjobs(stderr, SHOW_CHANGED);
12074 if (iflag && top) {
12076 #if ENABLE_ASH_MAIL
12080 n = parsecmd(inter);
12082 if (DEBUG > 2 && debug && (n != NODE_EOF))
12085 if (n == NODE_EOF) {
12086 if (!top || numeof >= 50)
12088 if (!stoppedjobs()) {
12091 out2str("\nUse \"exit\" to leave shell.\n");
12094 } else if (nflag == 0) {
12095 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12100 popstackmark(&smark);
12105 return skip & SKIPEVAL;
12112 * Take commands from a file. To be compatible we should do a path
12113 * search for the file, which is necessary to find sub-commands.
12116 find_dot_file(char *name)
12119 const char *path = pathval();
12122 /* don't try this for absolute or relative paths */
12123 if (strchr(name, '/'))
12126 /* IIRC standards do not say whether . is to be searched.
12127 * And it is even smaller this way, making it unconditional for now:
12129 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12134 while ((fullname = path_advance(&path, name)) != NULL) {
12136 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12138 * Don't bother freeing here, since it will
12139 * be freed by the caller.
12143 if (fullname != name)
12144 stunalloc(fullname);
12147 /* not found in the PATH */
12148 ash_msg_and_raise_error("%s: not found", name);
12152 static int FAST_FUNC
12153 dotcmd(int argc, char **argv)
12156 struct strlist *sp;
12157 volatile struct shparam saveparam;
12159 for (sp = cmdenviron; sp; sp = sp->next)
12160 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12163 /* bash says: "bash: .: filename argument required" */
12164 return 2; /* bash compat */
12167 /* "false; . empty_file; echo $?" should print 0, not 1: */
12170 fullname = find_dot_file(argv[1]);
12174 if (argc) { /* argc > 0, argv[0] != NULL */
12175 saveparam = shellparam;
12176 shellparam.malloced = 0;
12177 shellparam.nparam = argc;
12178 shellparam.p = argv;
12181 setinputfile(fullname, INPUT_PUSH_FILE);
12182 commandname = fullname;
12187 freeparam(&shellparam);
12188 shellparam = saveparam;
12194 static int FAST_FUNC
12195 exitcmd(int argc UNUSED_PARAM, char **argv)
12200 exitstatus = number(argv[1]);
12201 raise_exception(EXEXIT);
12206 * Read a file containing shell functions.
12209 readcmdfile(char *name)
12211 setinputfile(name, INPUT_PUSH_FILE);
12217 /* ============ find_command inplementation */
12220 * Resolve a command name. If you change this routine, you may have to
12221 * change the shellexec routine as well.
12224 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12226 struct tblentry *cmdp;
12233 struct builtincmd *bcmd;
12235 /* If name contains a slash, don't use PATH or hash table */
12236 if (strchr(name, '/') != NULL) {
12237 entry->u.index = -1;
12238 if (act & DO_ABS) {
12239 while (stat(name, &statb) < 0) {
12241 if (errno == EINTR)
12244 entry->cmdtype = CMDUNKNOWN;
12248 entry->cmdtype = CMDNORMAL;
12252 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12254 updatetbl = (path == pathval());
12257 if (strstr(path, "%builtin") != NULL)
12258 act |= DO_ALTBLTIN;
12261 /* If name is in the table, check answer will be ok */
12262 cmdp = cmdlookup(name, 0);
12263 if (cmdp != NULL) {
12266 switch (cmdp->cmdtype) {
12284 } else if (cmdp->rehash == 0)
12285 /* if not invalidated by cd, we're done */
12289 /* If %builtin not in path, check for builtin next */
12290 bcmd = find_builtin(name);
12292 if (IS_BUILTIN_REGULAR(bcmd))
12293 goto builtin_success;
12294 if (act & DO_ALTPATH) {
12295 if (!(act & DO_ALTBLTIN))
12296 goto builtin_success;
12297 } else if (builtinloc <= 0) {
12298 goto builtin_success;
12302 #if ENABLE_FEATURE_SH_STANDALONE
12304 int applet_no = find_applet_by_name(name);
12305 if (applet_no >= 0) {
12306 entry->cmdtype = CMDNORMAL;
12307 entry->u.index = -2 - applet_no;
12313 /* We have to search path. */
12314 prev = -1; /* where to start */
12315 if (cmdp && cmdp->rehash) { /* doing a rehash */
12316 if (cmdp->cmdtype == CMDBUILTIN)
12319 prev = cmdp->param.index;
12325 while ((fullname = path_advance(&path, name)) != NULL) {
12326 stunalloc(fullname);
12327 /* NB: code below will still use fullname
12328 * despite it being "unallocated" */
12331 if (prefix(pathopt, "builtin")) {
12333 goto builtin_success;
12336 if ((act & DO_NOFUNC)
12337 || !prefix(pathopt, "func")
12338 ) { /* ignore unimplemented options */
12342 /* if rehash, don't redo absolute path names */
12343 if (fullname[0] == '/' && idx <= prev) {
12346 TRACE(("searchexec \"%s\": no change\n", name));
12349 while (stat(fullname, &statb) < 0) {
12351 if (errno == EINTR)
12354 if (errno != ENOENT && errno != ENOTDIR)
12358 e = EACCES; /* if we fail, this will be the error */
12359 if (!S_ISREG(statb.st_mode))
12361 if (pathopt) { /* this is a %func directory */
12362 stalloc(strlen(fullname) + 1);
12363 /* NB: stalloc will return space pointed by fullname
12364 * (because we don't have any intervening allocations
12365 * between stunalloc above and this stalloc) */
12366 readcmdfile(fullname);
12367 cmdp = cmdlookup(name, 0);
12368 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12369 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12370 stunalloc(fullname);
12373 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12375 entry->cmdtype = CMDNORMAL;
12376 entry->u.index = idx;
12380 cmdp = cmdlookup(name, 1);
12381 cmdp->cmdtype = CMDNORMAL;
12382 cmdp->param.index = idx;
12387 /* We failed. If there was an entry for this command, delete it */
12388 if (cmdp && updatetbl)
12389 delete_cmd_entry();
12391 ash_msg("%s: %s", name, errmsg(e, "not found"));
12392 entry->cmdtype = CMDUNKNOWN;
12397 entry->cmdtype = CMDBUILTIN;
12398 entry->u.cmd = bcmd;
12402 cmdp = cmdlookup(name, 1);
12403 cmdp->cmdtype = CMDBUILTIN;
12404 cmdp->param.cmd = bcmd;
12408 entry->cmdtype = cmdp->cmdtype;
12409 entry->u = cmdp->param;
12413 /* ============ trap.c */
12416 * The trap builtin.
12418 static int FAST_FUNC
12419 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12423 int signo, exitcode;
12428 for (signo = 0; signo < NSIG; signo++) {
12429 char *tr = trap_ptr[signo];
12431 /* note: bash adds "SIG", but only if invoked
12432 * as "bash". If called as "sh", or if set -o posix,
12433 * then it prints short signal names.
12434 * We are printing short names: */
12435 out1fmt("trap -- %s %s\n",
12437 get_signame(signo));
12438 /* trap_ptr != trap only if we are in special-cased `trap` code.
12439 * In this case, we will exit very soon, no need to free(). */
12440 /* if (trap_ptr != trap && tp[0]) */
12445 if (trap_ptr != trap) {
12458 signo = get_signum(*ap);
12460 /* Mimic bash message exactly */
12461 ash_msg("%s: invalid signal specification", *ap);
12467 if (LONE_DASH(action))
12470 action = ckstrdup(action);
12474 may_have_traps = 1;
12475 trap[signo] = action;
12486 /* ============ Builtins */
12488 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
12490 * Lists available builtins
12492 static int FAST_FUNC
12493 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12499 "Built-in commands:\n"
12500 "------------------\n");
12501 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
12502 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
12503 builtintab[i].name + 1);
12509 #if ENABLE_FEATURE_SH_STANDALONE
12511 const char *a = applet_names;
12513 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12518 a += strlen(a) + 1;
12523 return EXIT_SUCCESS;
12525 #endif /* FEATURE_SH_EXTRA_QUIET */
12528 * The export and readonly commands.
12530 static int FAST_FUNC
12531 exportcmd(int argc UNUSED_PARAM, char **argv)
12537 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12539 if (nextopt("p") != 'p') {
12544 p = strchr(name, '=');
12548 vp = *findvar(hashvar(name), name);
12554 setvar(name, p, flag);
12555 } while ((name = *++aptr) != NULL);
12559 showvars(argv[0], flag, 0);
12564 * Delete a function if it exists.
12567 unsetfunc(const char *name)
12569 struct tblentry *cmdp;
12571 cmdp = cmdlookup(name, 0);
12572 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
12573 delete_cmd_entry();
12577 * The unset builtin command. We unset the function before we unset the
12578 * variable to allow a function to be unset when there is a readonly variable
12579 * with the same name.
12581 static int FAST_FUNC
12582 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12589 while ((i = nextopt("vf")) != 0) {
12593 for (ap = argptr; *ap; ap++) {
12606 static const unsigned char timescmd_str[] ALIGN1 = {
12607 ' ', offsetof(struct tms, tms_utime),
12608 '\n', offsetof(struct tms, tms_stime),
12609 ' ', offsetof(struct tms, tms_cutime),
12610 '\n', offsetof(struct tms, tms_cstime),
12613 static int FAST_FUNC
12614 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12616 unsigned long clk_tck, s, t;
12617 const unsigned char *p;
12620 clk_tck = sysconf(_SC_CLK_TCK);
12625 t = *(clock_t *)(((char *) &buf) + p[1]);
12628 out1fmt("%lum%lu.%03lus%c",
12630 (t * 1000) / clk_tck,
12638 #if ENABLE_SH_MATH_SUPPORT
12640 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
12641 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12643 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12645 static int FAST_FUNC
12646 letcmd(int argc UNUSED_PARAM, char **argv)
12652 ash_msg_and_raise_error("expression expected");
12654 i = ash_arith(*argv);
12662 * The read builtin. Options:
12663 * -r Do not interpret '\' specially
12664 * -s Turn off echo (tty only)
12665 * -n NCHARS Read NCHARS max
12666 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12667 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12668 * -u FD Read from given FD instead of fd 0
12669 * This uses unbuffered input, which may be avoidable in some cases.
12670 * TODO: bash also has:
12671 * -a ARRAY Read into array[0],[1],etc
12672 * -d DELIM End on DELIM char, not newline
12673 * -e Use line editing (tty only)
12675 static int FAST_FUNC
12676 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12678 char *opt_n = NULL;
12679 char *opt_p = NULL;
12680 char *opt_t = NULL;
12681 char *opt_u = NULL;
12682 int read_flags = 0;
12686 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
12695 read_flags |= BUILTIN_READ_SILENT;
12701 read_flags |= BUILTIN_READ_RAW;
12711 r = shell_builtin_read(setvar2,
12713 bltinlookup("IFS"), /* can be NULL */
12721 if ((uintptr_t)r > 1)
12722 ash_msg_and_raise_error(r);
12724 return (uintptr_t)r;
12727 static int FAST_FUNC
12728 umaskcmd(int argc UNUSED_PARAM, char **argv)
12730 static const char permuser[3] ALIGN1 = "ugo";
12731 static const char permmode[3] ALIGN1 = "rwx";
12732 static const short permmask[] ALIGN2 = {
12733 S_IRUSR, S_IWUSR, S_IXUSR,
12734 S_IRGRP, S_IWGRP, S_IXGRP,
12735 S_IROTH, S_IWOTH, S_IXOTH
12738 /* TODO: use bb_parse_mode() instead */
12743 int symbolic_mode = 0;
12745 while (nextopt("S") != '\0') {
12756 if (symbolic_mode) {
12760 for (i = 0; i < 3; i++) {
12763 *p++ = permuser[i];
12765 for (j = 0; j < 3; j++) {
12766 if ((mask & permmask[3 * i + j]) == 0) {
12767 *p++ = permmode[j];
12775 out1fmt("%.4o\n", mask);
12778 if (isdigit((unsigned char) *ap)) {
12781 if (*ap >= '8' || *ap < '0')
12782 ash_msg_and_raise_error(msg_illnum, argv[1]);
12783 mask = (mask << 3) + (*ap - '0');
12784 } while (*++ap != '\0');
12787 mask = ~mask & 0777;
12788 if (!bb_parse_mode(ap, &mask)) {
12789 ash_msg_and_raise_error("illegal mode: %s", ap);
12791 umask(~mask & 0777);
12797 static int FAST_FUNC
12798 ulimitcmd(int argc UNUSED_PARAM, char **argv)
12800 return shell_builtin_ulimit(argv);
12803 /* ============ main() and helpers */
12806 * Called to exit the shell.
12808 static void exitshell(void) NORETURN;
12816 status = exitstatus;
12817 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12818 if (setjmp(loc.loc)) {
12819 if (exception_type == EXEXIT)
12820 /* dash bug: it just does _exit(exitstatus) here
12821 * but we have to do setjobctl(0) first!
12822 * (bug is still not fixed in dash-0.5.3 - if you run dash
12823 * under Midnight Commander, on exit from dash MC is backgrounded) */
12824 status = exitstatus;
12827 exception_handler = &loc;
12834 flush_stdout_stderr();
12844 /* from input.c: */
12845 /* we will never free this */
12846 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
12849 signal(SIGCHLD, SIG_DFL);
12850 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12851 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12853 signal(SIGHUP, SIG_DFL);
12859 struct stat st1, st2;
12862 for (envp = environ; envp && *envp; envp++) {
12863 if (strchr(*envp, '=')) {
12864 setvareq(*envp, VEXPORT|VTEXTFIXED);
12868 setvar("PPID", utoa(getppid()), 0);
12870 p = lookupvar("PWD");
12872 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12873 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12880 * Process the shell command line arguments.
12883 procargs(char **argv)
12886 const char *xminusc;
12891 /* if (xargv[0]) - mmm, this is always true! */
12893 for (i = 0; i < NOPTS; i++)
12897 /* it already printed err message */
12898 raise_exception(EXERROR);
12902 if (*xargv == NULL) {
12904 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12907 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12911 for (i = 0; i < NOPTS; i++)
12912 if (optlist[i] == 2)
12917 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12922 } else if (!sflag) {
12923 setinputfile(*xargv, 0);
12926 commandname = arg0;
12929 shellparam.p = xargv;
12930 #if ENABLE_ASH_GETOPTS
12931 shellparam.optind = 1;
12932 shellparam.optoff = -1;
12934 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
12936 shellparam.nparam++;
12943 * Read /etc/profile or .profile.
12946 read_profile(const char *name)
12950 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12959 * This routine is called when an error or an interrupt occurs in an
12960 * interactive shell and control is returned to the main command loop.
12968 /* from input.c: */
12969 g_parsefile->left_in_buffer = 0;
12970 g_parsefile->left_in_line = 0; /* clear input buffer */
12972 /* from parser.c: */
12975 /* from redir.c: */
12976 clearredir(/*drop:*/ 0);
12980 static short profile_buf[16384];
12981 extern int etext();
12985 * Main routine. We initialize things, parse the arguments, execute
12986 * profiles if we're a login shell, and then call cmdloop to execute
12987 * commands. The setjmp call sets up the location to jump to when an
12988 * exception occurs. When an exception occurs the variable "state"
12989 * is used to figure out how far we had gotten.
12991 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
12992 int ash_main(int argc UNUSED_PARAM, char **argv)
12994 const char *shinit;
12995 volatile smallint state;
12996 struct jmploc jmploc;
12997 struct stackmark smark;
12999 /* Initialize global data */
13003 #if ENABLE_ASH_ALIAS
13009 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13012 #if ENABLE_FEATURE_EDITING
13013 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13016 if (setjmp(jmploc.loc)) {
13022 e = exception_type;
13026 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13029 outcslow('\n', stderr);
13031 popstackmark(&smark);
13032 FORCE_INT_ON; /* enable interrupts */
13041 exception_handler = &jmploc;
13044 TRACE(("Shell args: "));
13045 trace_puts_args(argv);
13047 rootpid = getpid();
13050 setstackmark(&smark);
13053 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
13055 const char *hp = lookupvar("HISTFILE");
13058 hp = lookupvar("HOME");
13060 char *defhp = concat_path_file(hp, ".ash_history");
13061 setvar("HISTFILE", defhp, 0);
13067 if (/* argv[0] && */ argv[0][0] == '-')
13071 read_profile("/etc/profile");
13074 read_profile(".profile");
13080 getuid() == geteuid() && getgid() == getegid() &&
13084 shinit = lookupvar("ENV");
13085 if (shinit != NULL && *shinit != '\0') {
13086 read_profile(shinit);
13092 /* evalstring pushes parsefile stack.
13093 * Ensure we don't falsely claim that 0 (stdin)
13094 * is one of stacked source fds.
13095 * Testcase: ash -c 'exec 1>&0' must not complain. */
13096 // if (!sflag) g_parsefile->pf_fd = -1;
13097 // ^^ not necessary since now we special-case fd 0
13098 // in is_hidden_fd() to not be considered "hidden fd"
13099 evalstring(minusc, 0);
13102 if (sflag || minusc == NULL) {
13103 #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13105 const char *hp = lookupvar("HISTFILE");
13107 line_input_state->hist_file = hp;
13110 state4: /* XXX ??? - why isn't this before the "if" statement */
13118 extern void _mcleanup(void);
13128 * Copyright (c) 1989, 1991, 1993, 1994
13129 * The Regents of the University of California. All rights reserved.
13131 * This code is derived from software contributed to Berkeley by
13132 * Kenneth Almquist.
13134 * Redistribution and use in source and binary forms, with or without
13135 * modification, are permitted provided that the following conditions
13137 * 1. Redistributions of source code must retain the above copyright
13138 * notice, this list of conditions and the following disclaimer.
13139 * 2. Redistributions in binary form must reproduce the above copyright
13140 * notice, this list of conditions and the following disclaimer in the
13141 * documentation and/or other materials provided with the distribution.
13142 * 3. Neither the name of the University nor the names of its contributors
13143 * may be used to endorse or promote products derived from this software
13144 * without specific prior written permission.
13146 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13147 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13148 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13149 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13150 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13151 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13152 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13153 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13154 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13155 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF